Webhook Support
discord.py-message-components offers support for creating, editing, and executing webhooks through the Webhook
class.
Webhook
- clsWebhook.from_url
- clsWebhook.partial
- defavatar_url_as
- defdelete
- defdelete_message
- defedit
- defedit_message
- defexecute
- defsend
- class discord.Webhook(data, *, adapter, state=None)
Bases:
Hashable
Represents a Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as
Guild.webhooks()
andTextChannel.webhooks()
. The ones received by the library will automatically have an adapter bound using the library’s HTTP _session. Those webhooks will havesend()
,delete()
andedit()
as coroutines.The second form involves creating a webhook object manually without having it bound to a websocket connection using the
from_url()
orpartial()
classmethods. This form allows finer grained control over how requests are done, allowing you to mix async and sync code using either aiohttp or requests.For example, creating a webhook from a URL and using aiohttp:
from discord import Webhook, AsyncWebhookAdapter import aiohttp async def foo(): async with aiohttp.ClientSession() as _session: webhook = Webhook.from_url('url-here', adapter=AsyncWebhookAdapter(_session)) await webhook.send('Hello World', username='Foo')
Or creating a webhook from an ID and token and using requests:
import requests from discord import Webhook, RequestsWebhookAdapter webhook = Webhook.partial(123456, 'abcdefg', adapter=RequestsWebhookAdapter()) webhook.send('Hello World', username='Foo')
- x == y
Checks if two webhooks are equal.
- x != y
Checks if two webhooks are not equal.
- hash(x)
Returns the webhooks’s hash.
Changed in version 1.4: Webhooks are now comparable and hashable.
Changed in version 2.0: Added support for forum channels, threads, components, the ability to edit attachments and to suppress notifications.
- token
The authentication token of the webhook. If this is
None
then the webhook cannot be used to make requests.- Type:
Optional[
str
]
- guild_id
The guild ID this webhook is for.
- Type:
Optional[
int
]
- channel_id
The channel ID this webhook is for.
- Type:
Optional[
int
]
- user
The user this webhook was created by. If the webhook was received without authentication then this will be
None
.- Type:
Optional[
abc.User
]
- name
The default name of the webhook.
- Type:
Optional[
str
]
- avatar
The default avatar of the webhook.
- Type:
Optional[
str
]
- classmethod partial(id, token, *, adapter)
Creates a partial
Webhook
.- Parameters:
id (
int
) – The ID of the webhook.token (
str
) – The authentication token of the webhook.adapter (
WebhookAdapter
) – The webhook adapter to use when sending requests. This is typicallyAsyncWebhookAdapter
for aiohttp orRequestsWebhookAdapter
for requests.
- Returns:
A partial
Webhook
. A partial webhook is just a webhook object with an ID and a token.- Return type:
- classmethod from_url(url, *, adapter)
Creates a partial
Webhook
from a webhook URL.- Parameters:
url (
str
) – The URL of the webhook.adapter (
WebhookAdapter
) – The webhook adapter to use when sending requests. This is typicallyAsyncWebhookAdapter
for aiohttp orRequestsWebhookAdapter
for requests.
- Raises:
InvalidArgument – The URL is invalid.
- Returns:
A partial
Webhook
. A partial webhook is just a webhook object with an ID and a token.- Return type:
- property guild
The guild this webhook belongs to.
If this is a partial webhook, then this will always return
None
.- Type:
Optional[
Guild
]
- property channel
The text or forum channel this webhook belongs to.
If this is a partial webhook, then this will always return
None
.- Type:
Optional[
TextChannel
,ForumChannel
]
- property avatar_url
Returns an
Asset
for the avatar the webhook has.If the webhook does not have a traditional avatar, an asset for the default avatar is returned instead.
This is equivalent to calling
avatar_url_as()
with the default parameters.- Type:
- avatar_url_as(*, format=None, size=1024)
Returns an
Asset
for the avatar the webhook has.If the webhook does not have a traditional avatar, an asset for the default avatar is returned instead.
The format must be one of ‘jpeg’, ‘jpg’, or ‘png’. The size must be a power of 2 between 16 and 1024.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- delete(*, reason=None)
This function could be a coroutine.
Deletes this Webhook.
If the webhook is constructed with a
RequestsWebhookAdapter
then this is not a coroutine.- Parameters:
reason (Optional[
str
]) –The reason for deleting this webhook. Shows up on the audit log.
Added in version 1.4.
- Raises:
HTTPException – Deleting the webhook failed.
NotFound – This webhook does not exist.
Forbidden – You do not have permissions to delete this webhook.
InvalidArgument – This webhook does not have a token associated with it.
- edit(*, reason=None, **kwargs)
This function could be a coroutine.
Edits this Webhook.
If the webhook is constructed with a
RequestsWebhookAdapter
then this is not a coroutine.- Parameters:
name (Optional[
str
]) – The webhook’s new default name.avatar (Optional[
bytes
]) – A bytes-like object representing the webhook’s new default avatar.reason (Optional[
str
]) –The reason for editing this webhook. Shows up on the audit log.
Added in version 1.4.
- Raises:
HTTPException – Editing the webhook failed.
NotFound – This webhook does not exist.
InvalidArgument – This webhook does not have a token associated with it.
- send(content=None, *, wait=False, thread_id=MISSING, thread_name=MISSING, username=MISSING, avatar_url=MISSING, tts=False, file=MISSING, files=MISSING, embed=MISSING, embeds=MISSING, components=MISSING, allowed_mentions=MISSING, suppress_embeds=False, suppress_notifications=False)
This function could be a coroutine.
Sends a message using the webhook.
If the webhook is constructed with a
RequestsWebhookAdapter
then this is not a coroutine.The content must be a type that can convert to a string through
str(content)
.All parameters are optional but at least one of
content
,file
/files
,embed
/embeds
or if possiblecomponents
must be provided.If the webhook belongs to a
ForumChannel
then eitherthread_id``(to send the message to an existing post) or ``thread_name
(to create a new post) must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type..- Parameters:
content (
str
) – The content of the message to send.wait (
bool
) – Whether the server should wait before sending a response. This essentially means that the return type of this function changes fromNone
to aWebhookMessage
if set toTrue
.thread_id (
int
) –Send a message to the specified thread/forum-post within a webhook’s channel. The thread/forum-post will automatically be unarchived.
..versionadded:: 2.0
thread_name (
str
) –ForumChannel
webhooks only: Will create a new post with the webhook message will be the starter message...versionadded:: 2.0
username (
str
) – The username to send with this message. If no username is provided then the default username for the webhook is used.avatar_url (Union[
str
,Asset
]) – The avatar URL to send with this message. If no avatar URL is provided then the default avatar for the webhook is used.tts (
bool
) – Indicates if the message should be sent using text-to-speech.file (
File
) – The file to upload. This cannot be mixed withfiles
parameter.files (List[
File
]) – A list of files to send with the content. This cannot be mixed with thefile
parameter.embed (
Embed
) – The rich embed for the content to send. This cannot be mixed withembeds
parameter.embeds (List[
Embed
]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with theembed
parameter.components (List[Union[
ActionRow
, List[Union[Button
, Select]]]]) –A list of up to five
ActionRow`s or :class:`list
, each containing up to fiveButton
or one Select like object.Note
Due to discord limitations this can only be used when the Webhook was created by a bot.
Added in version 2.0.
allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message.
Added in version 1.4.
suppress_embeds (
bool
) –Whether to suppress embeds send with the message, defaults to
False
.Added in version 2.0.
suppress_notifications (
bool
) –Whether to suppress desktop- & push-notifications for the message.
Users will still see a ping-symbol when they are mentioned in the message.
Added in version 2.0.
- Raises:
HTTPException – Sending the message failed.
NotFound – This webhook was not found.
Forbidden – The authorization token for the webhook is incorrect.
InvalidArgument – The length of
embeds
was invalid or there was no token associated with this webhook.
- Returns:
The message that was sent.
- Return type:
Optional[
WebhookMessage
]
- execute(*args, **kwargs)
An alias for
send()
.
- edit_message(message_id, *, content=MISSING, embed=MISSING, embeds=MISSING, components=MISSING, attachments=MISSING, allowed_mentions=MISSING, suppress_embeds=MISSING)
This function could be a coroutine.
Edits a message owned by this webhook.
This is a lower level interface to
WebhookMessage.edit()
in case you only have an ID.Warning
Since API v10, the
attachments
(when passed) must contain all attachments that should be present after edit, including retained and new attachments.As this requires to know the current attachments consider either storing the attachments that were sent with a message or using a fetched version of the message to edit it.
Added in version 1.6.
Changed in version 2.0: The
suppress
keyword-only parameter was renamed tosuppress_embeds
.- Parameters:
message_id (
int
) – The message ID to edit.content (Optional[
str
]) – The content to edit the message with orNone
to clear it.embed (Optional[
Embed
]) – The new embed to replace the original with. Could beNone
to remove all embeds.embeds (Optional[List[
Embed
]]) – A list containing up to 10 embeds. IfNone
empty, all embeds will be removed.components (List[Union[
ActionRow
, List[Union[Button
, Select]]]]) –A list of up to five
ActionRow`s or :class:`list
, each containing up to fiveButton
or one Select like object.Note
Due to discord limitations this can only be used when the webhook is owned by an application.
Added in version 2.0.
attachments (List[Union[
Attachment
,File
]]) –A list containing previous attachments to keep as well as new files to upload.
When empty, all attachment will be removed.
Note
New files will always appear under existing ones.
Added in version 2.0.
allowed_mentions (
AllowedMentions
) – Controls the mentions being processed in this message. Seeabc.Messageable.send()
for more information.suppress_embeds (
bool
) – Whether to suppress embeds send with the message.
- Raises:
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
InvalidArgument – The length of
embeds
was invalid or there was no token associated with this webhook.
- delete_message(message_id, /)
This function could be a coroutine.
Deletes a message owned by this webhook.
This is a lower level interface to
WebhookMessage.delete()
in case you only have an ID.Added in version 1.6.
- Parameters:
message_id (
int
) – The message ID to delete.- Raises:
HTTPException – Deleting the message failed.
Forbidden – Deleted a message that is not yours.
WebhookMessage
- class discord.WebhookMessage(*, state, channel, data)
Bases:
Message
Represents a message sent from your webhook.
This allows you to edit or delete a message sent by your webhook.
This inherits from
discord.Message
with changes toedit()
anddelete()
to work.Added in version 1.6.
- edit(*, content=MISSING, embed=MISSING, embeds=MISSING, components=MISSING, attachments=MISSING, keep_existing_attachments=False, allowed_mentions=MISSING, suppress_embeds=MISSING)
This function could be a coroutine.
Edits a message owned by this webhook.
This is a lower level interface to
WebhookMessage.edit()
in case you only have an ID.Warning
Since API v10, the
attachments
(when passed) must contain all attachments that should be present after edit, including retained and new attachments.As this requires to know the current attachments consider either storing the attachments that were sent with a message or using a fetched version of the message to edit it.
Added in version 1.6.
Changed in version 2.0: The
suppress
keyword-only parameter was renamed tosuppress_embeds
.- Parameters:
content (Optional[
str
]) – The content to edit the message with orNone
to clear it.embed (Optional[
Embed
]) – The new embed to replace the original with. Could beNone
to remove all embeds.embeds (Optional[List[
Embed
]]) – A list containing up to 10 embeds. IfNone
empty, all embeds will be removed.components (List[Union[
ActionRow
, List[Union[Button
, Select]]]]) –A list of up to five
ActionRow`s or :class:`list
, each containing up to fiveButton
or one Select like object.Note
Due to discord limitations this can only be used when the webhook is owned by an application.
Added in version 2.0.
attachments (List[Union[
Attachment
,File
]]) –A list containing previous attachments to keep as well as new files to upload.
When empty, all attachment will be removed.
Note
New files will always appear under existing ones.
Added in version 2.0.
keep_existing_attachments (
bool
) –Whether to auto-add existing attachments to
attachments
, defaults toFalse
.Note
Only needed when
attachments
are passed, otherwise will be ignored.allowed_mentions (
AllowedMentions
) – Controls the mentions being processed in this message. Seeabc.Messageable.send()
for more information.suppress_embeds (
bool
) – Whether to suppress embeds send with the message.
- Raises:
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
InvalidArgument – The length of
embeds
was invalid or there was no token associated with this webhook.
- delete(*, delay=None)
This function is a coroutine.
Deletes the message.
- Parameters:
delay (Optional[
float
]) – If provided, the number of seconds to wait before deleting the message. If this is a coroutine, the waiting is done in the background and deletion failures are ignored. If this is not a coroutine then the delay blocks the thread.- Raises:
Forbidden – You do not have proper permissions to delete the message.
NotFound – The message was deleted already.
HTTPException – Deleting the message failed.
Adapters
Adapters allow you to change how the request should be handled. They all build on a single
interface, WebhookAdapter.request()
.
- class discord.WebhookAdapter
Bases:
object
Base class for all webhook adapters.
- request(verb, url, multipart=None, payload=None, **kwargs)
Actually does the request.
Subclasses must implement this.
- Parameters:
verb (
str
) – The HTTP verb to use for the request.url (
str
) – The URL to send the request to. This will have the query parameters already added to it, if any.multipart (Optional[
dict
]) – A dict containing multipart form data to send with the request. If a filename is being uploaded, then it will be under afile
key which will have a 3-elementtuple
denoting(filename, file, content_type)
.payload (Optional[
dict
]) – The JSON to send with the request, if any.
- handle_execution_response(data, *, wait)
Transforms the webhook execution response into something more meaningful.
This is mainly used to convert the data into a
Message
if necessary.Subclasses must implement this.
- Parameters:
data – The data that was returned from the request.
wait (
bool
) – Whether the webhook execution was asked to wait or not.
- class discord.AsyncWebhookAdapter(session)
Bases:
WebhookAdapter
A webhook adapter suited for use with aiohttp.
Note
You are responsible for cleaning up the client _session.
- Parameters:
session (
aiohttp.ClientSession
) – The _session to use to send requests.
- await request(verb, url, *, payload=None, multipart=None, proxy=None, proxy_auth=None, files=None, reason=None, params=None)
Actually does the request.
Subclasses must implement this.
- Parameters:
verb (
str
) – The HTTP verb to use for the request.url (
str
) – The URL to send the request to. This will have the query parameters already added to it, if any.multipart (Optional[
dict
]) – A dict containing multipart form data to send with the request. If a filename is being uploaded, then it will be under afile
key which will have a 3-elementtuple
denoting(filename, file, content_type)
.payload (Optional[
dict
]) – The JSON to send with the request, if any.
- await handle_execution_response(response, *, wait)
Transforms the webhook execution response into something more meaningful.
This is mainly used to convert the data into a
Message
if necessary.Subclasses must implement this.
- Parameters:
data – The data that was returned from the request.
wait (
bool
) – Whether the webhook execution was asked to wait or not.
- class discord.RequestsWebhookAdapter(session=None, *, sleep=True)
Bases:
WebhookAdapter
A webhook adapter suited for use with
requests
.Only versions of requests higher than 2.13.0 are supported.
- Parameters:
session (Optional[requests.Session]) – The requests _session to use for sending requests. If not given then each request will create a new _session. Note if a _session is given, the webhook adapter will not clean it up for you. You must close the _session yourself.
sleep (
bool
) – Whether to sleep the thread when encountering a 429 or pre-emptive rate limit or a 5xx status code. Defaults toTrue
. If set toFalse
then this will raise anHTTPException
instead.
- request(verb, url, payload=None, multipart=None, *, files=None, reason=None)
Actually does the request.
Subclasses must implement this.
- Parameters:
verb (
str
) – The HTTP verb to use for the request.url (
str
) – The URL to send the request to. This will have the query parameters already added to it, if any.multipart (Optional[
dict
]) – A dict containing multipart form data to send with the request. If a filename is being uploaded, then it will be under afile
key which will have a 3-elementtuple
denoting(filename, file, content_type)
.payload (Optional[
dict
]) – The JSON to send with the request, if any.
- handle_execution_response(response, *, wait)
Transforms the webhook execution response into something more meaningful.
This is mainly used to convert the data into a
Message
if necessary.Subclasses must implement this.
- Parameters:
data – The data that was returned from the request.
wait (
bool
) – Whether the webhook execution was asked to wait or not.