Interactions API Reference¶
The following section outlines the API of interactions, as implemented by the library.
For documentation about the rest of the library, check API Reference.
Models¶
Similar to Discord Models, these are not meant to be constructed by the user.
Interaction¶
- asyncdelete_original_response
- asyncedit_original_response
- defis_expired
- defis_guild_integration
- defis_user_integration
- asyncoriginal_response
- asynctranslate
- class discord.Interaction¶
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
- type¶
The interaction type.
- Type
- channel¶
The channel the interaction was sent from.
Note that due to a Discord limitation, if sent from a DM channel
recipient
isNone
.- Type
Optional[Union[
abc.GuildChannel
,abc.PrivateChannel
,Thread
]]
- entitlements¶
The entitlements that the guild or user has.
- Type
List[
Entitlement
]
- message¶
The message that sent this interaction.
This is only available for
InteractionType.component
interactions.- Type
Optional[
Message
]
- guild_locale¶
The preferred locale of the guild the interaction was sent from, if any.
- Type
Optional[
Locale
]
- extras¶
A dictionary that can be used to store extraneous data for use during interaction processing. The library will not touch any values or keys within this dictionary.
- Type
- command_failed¶
Whether the command associated with this interaction failed to execute. This includes checks and execution.
- Type
- context¶
The context of the interaction.
New in version 2.4.
- Type
- property client¶
The client that is handling this interaction.
Note that
AutoShardedClient
,Bot
, andAutoShardedBot
are all subclasses of client.- Type
- property permissions¶
The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn’t apply, an empty permissions object is returned.
- Type
- property app_permissions¶
The resolved permissions of the application or the bot, including overwrites.
- Type
- namespace¶
The resolved namespace for this interaction.
If the interaction is not an application command related interaction or the client does not have a tree attached to it then this returns an empty namespace.
- command¶
The command being called from this interaction.
If the interaction is not an application command related interaction or the command is not found in the client’s attached tree then
None
is returned.- Type
Optional[Union[
app_commands.Command
,app_commands.ContextMenu
]]
- response¶
Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using
followup
instead.- Type
- property created_at¶
When the interaction was created.
- Type
- property expires_at¶
When the interaction expires.
- Type
- is_guild_integration()¶
bool
: ReturnsTrue
if the interaction is a guild integration.New in version 2.4.
- is_user_integration()¶
bool
: ReturnsTrue
if the interaction is a user integration.New in version 2.4.
- await original_response()¶
This function is a coroutine.
Fetches the original interaction response message associated with the interaction.
If the interaction response was a newly created message (i.e. through
InteractionResponse.send_message()
orInteractionResponse.defer()
, wherethinking
isTrue
) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).Repeated calls to this will return a cached value.
- Raises
HTTPException – Fetching the original response message failed.
ClientException – The channel for the message could not be resolved.
NotFound – The interaction response message does not exist.
- Returns
The original interaction response message.
- Return type
- await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)¶
This function is a coroutine.
Edits the original interaction response message.
This is a lower level interface to
InteractionMessage.edit()
in case you do not want to fetch the message and save an HTTP request.This method is also the only way to edit the original message if the message sent was ephemeral.
- Parameters
content (Optional[
str
]) – The content to edit the message with orNone
to clear it.embeds (List[
Embed
]) – A list of embeds to edit the message with.embed (Optional[
Embed
]) – The embed to edit the message with.None
suppresses the embeds. This should not be mixed with theembeds
parameter.attachments (List[Union[
Attachment
,File
]]) –A list of attachments to keep in the message as well as new files to upload. If
[]
is passed then all attachments are removed.Note
New files will always appear after current attachments.
allowed_mentions (
AllowedMentions
) – Controls the mentions being processed in this message. Seeabc.Messageable.send()
for more information.view (Optional[
View
]) – The updated view to update this message with. IfNone
is passed then the view is removed.
- Raises
HTTPException – Editing the message failed.
NotFound – The interaction response message does not exist.
Forbidden – Edited a message that is not yours.
TypeError – You specified both
embed
andembeds
ValueError – The length of
embeds
was invalid.
- Returns
The newly edited message.
- Return type
- await delete_original_response()¶
This function is a coroutine.
Deletes the original interaction response message.
This is a lower level interface to
InteractionMessage.delete()
in case you do not want to fetch the message and save an HTTP request.- Raises
HTTPException – Deleting the message failed.
NotFound – The interaction response message does not exist or has already been deleted.
Forbidden – Deleted a message that is not yours.
- await translate(string, *, locale=..., data=...)¶
This function is a coroutine.
Translates a string using the set
Translator
.New in version 2.1.
- Parameters
string (Union[
str
,locale_str
]) – The string to translate.locale_str
can be used to add more context, information, or any metadata necessary.locale (
Locale
) – The locale to use, this is handy if you want the translation for a specific locale. Defaults to the user’slocale
.data (Any) – The extraneous data that is being translated. If not specified, either
command
ormessage
will be passed, depending on which is available in the context.
- Returns
The translated string, or
None
if a translator was not set.- Return type
Optional[
str
]
InteractionResponse¶
- asyncautocomplete
- asyncdefer
- asyncedit_message
- defis_done
- asyncpong
- asyncsend_message
- asyncsend_modal
- class discord.InteractionResponse¶
Represents a Discord interaction response.
This type can be accessed through
Interaction.response
.New in version 2.0.
- is_done()¶
bool
: Indicates whether an interaction response has been done before.An interaction can only be responded to once.
- property type¶
The type of response that was sent,
None
if response is not done.
- await defer(*, ephemeral=False, thinking=False)¶
This function is a coroutine.
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types:
- Parameters
ephemeral (
bool
) – Indicates whether the deferred message will eventually be ephemeral. This only applies toInteractionType.application_command
interactions, or ifthinking
isTrue
.thinking (
bool
) – Indicates whether the deferred type should beInteractionResponseType.deferred_channel_message
instead of the defaultInteractionResponseType.deferred_message_update
if both are valid. In UI terms, this is represented as if the bot is thinking of a response. It is your responsibility to eventually send a followup message viaInteraction.followup
to make this thinking state go away. Application commands (AKA Slash commands) cannot useInteractionResponseType.deferred_message_update
.
- Raises
HTTPException – Deferring the interaction failed.
InteractionResponded – This interaction has already been responded to before.
- await pong()¶
This function is a coroutine.
Pongs the ping interaction.
This should rarely be used.
- Raises
HTTPException – Ponging the interaction failed.
InteractionResponded – This interaction has already been responded to before.
- await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None, poll=...)¶
This function is a coroutine.
Responds to this interaction by sending a message.
- Parameters
content (Optional[
str
]) – The content of the message to send.embeds (List[
Embed
]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with theembed
parameter.embed (
Embed
) – The rich embed for the content to send. This cannot be mixed withembeds
parameter.file (
File
) – The file to upload.files (List[
File
]) – A list of files to upload. Must be a maximum of 10.tts (
bool
) – Indicates if the message should be sent using text-to-speech.view (
discord.ui.View
) – The view to send with the message.ephemeral (
bool
) – Indicates if the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes.allowed_mentions (
AllowedMentions
) – Controls the mentions being processed in this message. Seeabc.Messageable.send()
for more information.suppress_embeds (
bool
) – Whether to suppress embeds for the message. This sends the message without any embeds if set toTrue
.silent (
bool
) –Whether to suppress push and desktop notifications for the message. This will increment the mention counter in the UI, but will not actually send a notification.
New in version 2.2.
delete_after (
float
) –If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.
New in version 2.1.
poll (
Poll
) –The poll to send with this message.
New in version 2.4.
- Raises
HTTPException – Sending the message failed.
TypeError – You specified both
embed
andembeds
orfile
andfiles
.ValueError – The length of
embeds
was invalid.InteractionResponded – This interaction has already been responded to before.
- await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None, suppress_embeds=...)¶
This function is a coroutine.
Responds to this interaction by editing the original message of a component or modal interaction.
- Parameters
content (Optional[
str
]) – The new content to replace the message with.None
removes the content.embeds (List[
Embed
]) – A list of embeds to edit the message with.embed (Optional[
Embed
]) – The embed to edit the message with.None
suppresses the embeds. This should not be mixed with theembeds
parameter.attachments (List[Union[
Attachment
,File
]]) –A list of attachments to keep in the message as well as new files to upload. If
[]
is passed then all attachments are removed.Note
New files will always appear after current attachments.
view (Optional[
View
]) – The updated view to update this message with. IfNone
is passed then the view is removed.allowed_mentions (Optional[
AllowedMentions
]) – Controls the mentions being processed in this message. SeeMessage.edit()
for more information.delete_after (
float
) –If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.
New in version 2.2.
suppress_embeds (
bool
) –Whether to suppress embeds for the message. This removes all the embeds if set to
True
. If set toFalse
this brings the embeds back if they were suppressed. Using this parameter requiresmanage_messages
.New in version 2.4.
- Raises
HTTPException – Editing the message failed.
TypeError – You specified both
embed
andembeds
.InteractionResponded – This interaction has already been responded to before.
- await send_modal(modal, /)¶
This function is a coroutine.
Responds to this interaction by sending a modal.
- Parameters
modal (
Modal
) – The modal to send.- Raises
HTTPException – Sending the modal failed.
InteractionResponded – This interaction has already been responded to before.
- await autocomplete(choices)¶
This function is a coroutine.
Responds to this interaction by giving the user the choices they can use.
- Parameters
choices (List[
Choice
]) – The list of new choices as the user is typing.- Raises
HTTPException – Sending the choices failed.
ValueError – This interaction cannot respond with autocomplete.
InteractionResponded – This interaction has already been responded to before.
InteractionMessage¶
- asyncadd_files
- asyncadd_reaction
- asyncclear_reaction
- asyncclear_reactions
- asynccreate_thread
- asyncdelete
- asyncedit
- asyncend_poll
- asyncfetch
- asyncfetch_thread
- defis_system
- asyncpin
- asyncpublish
- asyncremove_attachments
- asyncremove_reaction
- asyncreply
- defto_reference
- asyncunpin
- class discord.InteractionMessage¶
Represents the original interaction response message.
This allows you to edit or delete the message associated with the interaction response. To retrieve this object see
Interaction.original_response()
.This inherits from
discord.Message
with changes toedit()
anddelete()
to work.New in version 2.0.
- await edit(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None, delete_after=None)¶
This function is a coroutine.
Edits the message.
- Parameters
content (Optional[
str
]) – The content to edit the message with orNone
to clear it.embeds (List[
Embed
]) – A list of embeds to edit the message with.embed (Optional[
Embed
]) – The embed to edit the message with.None
suppresses the embeds. This should not be mixed with theembeds
parameter.attachments (List[Union[
Attachment
,File
]]) –A list of attachments to keep in the message as well as new files to upload. If
[]
is passed then all attachments are removed.Note
New files will always appear after current attachments.
allowed_mentions (
AllowedMentions
) – Controls the mentions being processed in this message. Seeabc.Messageable.send()
for more information.view (Optional[
View
]) – The updated view to update this message with. IfNone
is passed then the view is removed.delete_after (Optional[
float
]) –If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.
New in version 2.2.
- Raises
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
TypeError – You specified both
embed
andembeds
ValueError – The length of
embeds
was invalid.
- Returns
The newly edited message.
- Return type
- await add_files(*files)¶
This function is a coroutine.
Adds new files to the end of the message attachments.
New in version 2.0.
- Parameters
*files (
File
) – New files to add to the message.- Raises
HTTPException – Editing the message failed.
Forbidden – Tried to edit a message that isn’t yours.
- Returns
The newly edited message.
- Return type
- await remove_attachments(*attachments)¶
This function is a coroutine.
Removes attachments from the message.
New in version 2.0.
- Parameters
*attachments (
Attachment
) – Attachments to remove from the message.- Raises
HTTPException – Editing the message failed.
Forbidden – Tried to edit a message that isn’t yours.
- Returns
The newly edited message.
- Return type
- await 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. The waiting is done in the background and deletion failures are ignored.- Raises
Forbidden – You do not have proper permissions to delete the message.
NotFound – The message was deleted already.
HTTPException – Deleting the message failed.
- await add_reaction(emoji, /)¶
This function is a coroutine.
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild
Emoji
.You must have
read_message_history
to do this. If nobody else has reacted to the message using this emoji,add_reactions
is required.Changed in version 2.0:
emoji
parameter is now positional-only.Changed in version 2.0: This function will now raise
TypeError
instead ofInvalidArgument
.- Parameters
emoji (Union[
Emoji
,Reaction
,PartialEmoji
,str
]) – The emoji to react with.- Raises
HTTPException – Adding the reaction failed.
Forbidden – You do not have the proper permissions to react to the message.
NotFound – The emoji you specified was not found.
TypeError – The emoji parameter is invalid.
- clean_content¶
A property that returns the content in a “cleaned up” manner. This basically means that mentions are transformed into the way the client shows it. e.g.
<#id>
will transform into#name
.This will also transform @everyone and @here mentions into non-mentions.
Note
This does not affect markdown. If you want to escape or remove markdown then use
utils.escape_markdown()
orutils.remove_markdown()
respectively, along with this function.- Type
- await clear_reaction(emoji)¶
This function is a coroutine.
Clears a specific reaction from the message.
The emoji may be a unicode emoji or a custom guild
Emoji
.You must have
manage_messages
to do this.New in version 1.3.
Changed in version 2.0: This function will now raise
TypeError
instead ofInvalidArgument
.- Parameters
emoji (Union[
Emoji
,Reaction
,PartialEmoji
,str
]) – The emoji to clear.- Raises
HTTPException – Clearing the reaction failed.
Forbidden – You do not have the proper permissions to clear the reaction.
NotFound – The emoji you specified was not found.
TypeError – The emoji parameter is invalid.
- await clear_reactions()¶
This function is a coroutine.
Removes all the reactions from the message.
You must have
manage_messages
to do this.- Raises
HTTPException – Removing the reactions failed.
Forbidden – You do not have the proper permissions to remove all the reactions.
- await create_thread(*, name, auto_archive_duration=..., slowmode_delay=None, reason=None)¶
This function is a coroutine.
Creates a public thread from this message.
You must have
create_public_threads
in order to create a public thread from a message.The channel this message belongs in must be a
TextChannel
.New in version 2.0.
- Parameters
name (
str
) – The name of the thread.auto_archive_duration (
int
) –The duration in minutes before a thread is automatically hidden from the channel list. If not provided, the channel’s default auto archive duration is used.
Must be one of
60
,1440
,4320
, or10080
, if provided.slowmode_delay (Optional[
int
]) – Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is21600
. By default no slowmode rate limit if this isNone
.reason (Optional[
str
]) – The reason for creating a new thread. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to create a thread.
HTTPException – Creating the thread failed.
ValueError – This message does not have guild info attached.
- Returns
The created thread.
- Return type
- property created_at¶
The message’s creation time in UTC.
- Type
- property edited_at¶
An aware UTC datetime object containing the edited time of the message.
- Type
Optional[
datetime.datetime
]
- await end_poll()¶
This function is a coroutine.
Ends the
Poll
attached to this message.This can only be done if you are the message author.
If the poll was successfully ended, then it returns the updated
Message
.- Raises
HTTPException – Ending the poll failed.
- Returns
The updated message.
- Return type
- await fetch()¶
This function is a coroutine.
Fetches the partial message to a full
Message
.- Raises
NotFound – The message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- Returns
The full message.
- Return type
- await fetch_thread()¶
This function is a coroutine.
Retrieves the public thread attached to this message.
Note
This method is an API call. For general usage, consider
thread
instead.New in version 2.4.
- Raises
InvalidData – An unknown channel type was received from Discord or the guild the thread belongs to is not the same as the one in this object points to.
HTTPException – Retrieving the thread failed.
NotFound – There is no thread attached to this message.
Forbidden – You do not have permission to fetch this channel.
- Returns
The public thread attached to this message.
- Return type
- property interaction¶
The interaction that this message is a response to.
New in version 2.0.
Deprecated since version 2.4: This attribute is deprecated and will be removed in a future version. Use
interaction_metadata
instead.- Type
Optional[
MessageInteraction
]
- is_system()¶
bool
: Whether the message is a system message.A system message is a message that is constructed entirely by the Discord API in response to something.
New in version 1.3.
- await pin(*, reason=None)¶
This function is a coroutine.
Pins the message.
You must have
manage_messages
to do this in a non-private channel context.- Parameters
reason (Optional[
str
]) –The reason for pinning the message. Shows up on the audit log.
New in version 1.4.
- Raises
Forbidden – You do not have permissions to pin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Pinning the message failed, probably due to the channel having more than 50 pinned messages.
- await publish()¶
This function is a coroutine.
Publishes this message to the channel’s followers.
The message must have been sent in a news channel. You must have
send_messages
to do this.If the message is not your own then
manage_messages
is also needed.- Raises
Forbidden – You do not have the proper permissions to publish this message or the channel is not a news channel.
HTTPException – Publishing the message failed.
- raw_channel_mentions¶
A property that returns an array of channel IDs matched with the syntax of
<#channel_id>
in the message content.- Type
List[
int
]
- raw_mentions¶
A property that returns an array of user IDs matched with the syntax of
<@user_id>
in the message content.This allows you to receive the user IDs of mentioned users even in a private message context.
- Type
List[
int
]
- raw_role_mentions¶
A property that returns an array of role IDs matched with the syntax of
<@&role_id>
in the message content.- Type
List[
int
]
- await remove_reaction(emoji, member)¶
This function is a coroutine.
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild
Emoji
.If the reaction is not your own (i.e.
member
parameter is not you) thenmanage_messages
is needed.The
member
parameter must represent a member and meet theabc.Snowflake
abc.Changed in version 2.0: This function will now raise
TypeError
instead ofInvalidArgument
.- Parameters
emoji (Union[
Emoji
,Reaction
,PartialEmoji
,str
]) – The emoji to remove.member (
abc.Snowflake
) – The member for which to remove the reaction.
- Raises
HTTPException – Removing the reaction failed.
Forbidden – You do not have the proper permissions to remove the reaction.
NotFound – The member or emoji you specified was not found.
TypeError – The emoji parameter is invalid.
- await reply(content=None, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.send()
to reply to theMessage
.New in version 1.6.
Changed in version 2.0: This function will now raise
TypeError
orValueError
instead ofInvalidArgument
.- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
files
list is not of the appropriate sizeTypeError – You specified both
file
andfiles
.
- Returns
The message that was sent.
- Return type
- system_content¶
A property that returns the content that is rendered regardless of the
Message.type
.In the case of
MessageType.default
andMessageType.reply
, this just returns the regularMessage.content
. Otherwise this returns an English message denoting the contents of the system message.- Type
- property thread¶
The public thread created from this message, if it exists.
Note
For messages received via the gateway this does not retrieve archived threads, as they are not retained in the internal cache. Use
fetch_thread()
instead.New in version 2.4.
- Type
Optional[
Thread
]
- to_reference(*, fail_if_not_exists=True)¶
Creates a
MessageReference
from the current message.New in version 1.6.
- Parameters
fail_if_not_exists (
bool
) –Whether replying using the message reference should raise
HTTPException
if the message no longer exists or Discord could not fetch the message.New in version 1.7.
- Returns
The reference to this message.
- Return type
- await unpin(*, reason=None)¶
This function is a coroutine.
Unpins the message.
You must have
manage_messages
to do this in a non-private channel context.- Parameters
reason (Optional[
str
]) –The reason for unpinning the message. Shows up on the audit log.
New in version 1.4.
- Raises
Forbidden – You do not have permissions to unpin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Unpinning the message failed.
MessageInteraction¶
- class discord.MessageInteraction¶
Represents the interaction that a
Message
is a response to.New in version 2.0.
- x == y
Checks if two message interactions are equal.
- x != y
Checks if two message interactions are not equal.
- hash(x)
Returns the message interaction’s hash.
- type¶
The interaction type.
- Type
- property created_at¶
The interaction’s creation time in UTC.
- Type
MessageInteractionMetadata¶
- class discord.MessageInteractionMetadata¶
Represents the interaction metadata of a
Message
if it was sent in response to an interaction.New in version 2.4.
- x == y
Checks if two message interactions are equal.
- x != y
Checks if two message interactions are not equal.
- hash(x)
Returns the message interaction’s hash.
- type¶
The interaction type.
- Type
- original_response_message_id¶
The ID of the original response message if the message is a follow-up.
- Type
Optional[
int
]
- interacted_message_id¶
The ID of the message that containes the interactive components, if applicable.
- Type
Optional[
int
]
- modal_interaction¶
The metadata of the modal submit interaction that triggered this interaction, if applicable.
- Type
Optional[
MessageInteractionMetadata
]
- property created_at¶
The interaction’s creation time in UTC.
- Type
- property original_response_message¶
The original response message if the message is a follow-up and is found in cache.
- Type
Optional[
Message
]
Component¶
ActionRow¶
- class discord.ActionRow¶
Represents a Discord Bot UI Kit Action Row.
This is a component that holds up to 5 children components in a row.
This inherits from
Component
.New in version 2.0.
- children¶
The children components that this holds, if any.
- Type
List[Union[
Button
,SelectMenu
,TextInput
]]
- property type¶
The type of component.
- Type
TextInput¶
- class discord.TextInput¶
Represents a text input from the Discord Bot UI Kit.
Note
The user constructible and usable type to create a text input is
discord.ui.TextInput
not this one.New in version 2.0.
- property type¶
The type of component.
- Type
AppCommand¶
- asyncdelete
- asyncedit
- asyncfetch_permissions
- class discord.app_commands.AppCommand¶
Represents an application command.
In common parlance this is referred to as a “Slash Command” or a “Context Menu Command”.
New in version 2.0.
- x == y
Checks if two application commands are equal.
- x != y
Checks if two application commands are not equal.
- hash(x)
Returns the application command’s hash.
- str(x)
Returns the application command’s name.
- type¶
The application command’s type.
- Type
- name_localizations¶
The localised names of the application command. Used for display purposes.
- description_localizations¶
The localised descriptions of the application command. Used for display purposes.
- options¶
A list of options.
- Type
List[Union[
Argument
,AppCommandGroup
]]
- default_member_permissions¶
The default member permissions that can run this command.
- Type
Optional[
Permissions
]
- dm_permission¶
A boolean that indicates whether this command can be run in direct messages.
- Type
- allowed_contexts¶
The contexts that this command is allowed to be used in. Overrides the
dm_permission
attribute.New in version 2.4.
- Type
Optional[
AppCommandContext
]
- allowed_installs¶
The installation contexts that this command is allowed to be installed in.
New in version 2.4.
- Type
Optional[
AppInstallationType
]
- guild_id¶
The ID of the guild this command is registered in. A value of
None
denotes that it is a global command.- Type
Optional[
int
]
- await delete()¶
This function is a coroutine.
Deletes the application command.
- Raises
NotFound – The application command was not found.
Forbidden – You do not have permission to delete this application command.
HTTPException – Deleting the application command failed.
MissingApplicationID – The client does not have an application ID.
- await edit(*, name=..., description=..., default_member_permissions=..., dm_permission=..., options=...)¶
This function is a coroutine.
Edits the application command.
- Parameters
name (
str
) – The new name for the application command.description (
str
) – The new description for the application command.default_member_permissions (Optional[
Permissions
]) – The new default permissions needed to use this application command. Pass value ofNone
to remove any permission requirements.dm_permission (
bool
) – Indicates if the application command can be used in DMs.options (List[Union[
Argument
,AppCommandGroup
]]) – List of new options for this application command.
- Raises
NotFound – The application command was not found.
Forbidden – You do not have permission to edit this application command.
HTTPException – Editing the application command failed.
MissingApplicationID – The client does not have an application ID.
- Returns
The newly edited application command.
- Return type
- await fetch_permissions(guild)¶
This function is a coroutine.
Retrieves this command’s permission in the guild.
- Parameters
guild (
Snowflake
) – The guild to retrieve the permissions from.- Raises
Forbidden – You do not have permission to fetch the application command’s permissions.
HTTPException – Fetching the application command’s permissions failed.
MissingApplicationID – The client does not have an application ID.
NotFound – The application command’s permissions could not be found. This can also indicate that the permissions are synced with the guild (i.e. they are unchanged from the default).
- Returns
An object representing the application command’s permissions in the guild.
- Return type
AppCommandGroup¶
- class discord.app_commands.AppCommandGroup¶
Represents an application command subcommand.
New in version 2.0.
- type¶
The type of subcommand.
- Type
- name_localizations¶
The localised names of the subcommand. Used for display purposes.
- description_localizations¶
The localised descriptions of the subcommand. Used for display purposes.
- options¶
A list of options.
- Type
List[Union[
Argument
,AppCommandGroup
]]
- parent¶
The parent application command.
- Type
Union[
AppCommand
,AppCommandGroup
]
- property qualified_name¶
Returns the fully qualified command name.
The qualified name includes the parent name as well. For example, in a command like
/foo bar
the qualified name isfoo bar
.- Type
AppCommandChannel¶
- class discord.app_commands.AppCommandChannel¶
Represents an application command partially resolved channel object.
New in version 2.0.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns the channel’s name.
- type¶
The type of channel.
- Type
- permissions¶
The resolved permissions of the user who invoked the application command in that channel.
- Type
- resolve()¶
Resolves the application command channel to the appropriate channel from cache if found.
- Returns
The resolved guild channel or
None
if not found in cache.- Return type
Optional[
abc.GuildChannel
]
- await fetch()¶
This function is a coroutine.
Fetches the partial channel to a full
abc.GuildChannel
.- Raises
NotFound – The channel was not found.
Forbidden – You do not have the permissions required to get a channel.
HTTPException – Retrieving the channel failed.
- Returns
The full channel.
- Return type
- property created_at¶
An aware timestamp of when this channel was created in UTC.
- Type
AppCommandThread¶
- class discord.app_commands.AppCommandThread¶
Represents an application command partially resolved thread object.
New in version 2.0.
- x == y
Checks if two thread are equal.
- x != y
Checks if two thread are not equal.
- hash(x)
Returns the thread’s hash.
- str(x)
Returns the thread’s name.
- type¶
The type of thread.
- Type
- permissions¶
The resolved permissions of the user who invoked the application command in that thread.
- Type
- invitable¶
Whether non-moderators can add other non-moderators to this thread. This is always
True
for public threads.- Type
- auto_archive_duration¶
The duration in minutes until the thread is automatically hidden from the channel list. Usually a value of 60, 1440, 4320 and 10080.
- Type
- archive_timestamp¶
An aware timestamp of when the thread’s archived status was last updated in UTC.
- Type
- property parent¶
The parent channel this thread belongs to.
- Type
Optional[
TextChannel
]
- property created_at¶
An aware timestamp of when the thread was created in UTC.
Note
This timestamp only exists for threads created after 9 January 2022, otherwise returns
None
.
- resolve()¶
Resolves the application command channel to the appropriate channel from cache if found.
- Returns
The resolved guild channel or
None
if not found in cache.- Return type
Optional[
abc.GuildChannel
]
AppCommandPermissions¶
- class discord.app_commands.AppCommandPermissions¶
Represents the permissions for an application command.
New in version 2.0.
- id¶
The ID of the permission target, such as a role, channel, or guild. The special
guild_id - 1
sentinel is used to represent “all channels”.- Type
- target¶
The role, user, or channel associated with this permission. This could also be the
AllChannels
sentinel type. Falls back toObject
if the target could not be found in the cache.- Type
Any
- type¶
The type of permission.
AppCommandContext¶
AppInstallationType¶
- class discord.app_commands.AppInstallationType(*, guild=None, user=None)¶
Represents the installation location of an application command.
New in version 2.4.
- Parameters
GuildAppCommandPermissions¶
- class discord.app_commands.GuildAppCommandPermissions¶
Represents the permissions for an application command in a guild.
New in version 2.0.
- command¶
The application command associated with the permissions.
- Type
- id¶
ID of the command or the application ID. When this is the application ID instead of a command ID, the permissions apply to all commands that do not contain explicit overwrites.
- Type
- permissions¶
The permissions, this is a max of 100.
- Type
List[
AppCommandPermissions
]
Argument¶
- class discord.app_commands.Argument¶
Represents an application command argument.
New in version 2.0.
- type¶
The type of argument.
- Type
- name_localizations¶
The localised names of the argument. Used for display purposes.
- description_localizations¶
The localised descriptions of the argument. Used for display purposes.
- parent¶
The parent application command that has this argument.
- Type
Union[
AppCommand
,AppCommandGroup
]
- channel_types¶
The channel types that are allowed for this parameter.
- Type
List[
ChannelType
]
AllChannels¶
Data Classes¶
Similar to Data Classes, these can be received and constructed by users.
SelectOption¶
- class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)¶
Represents a select menu’s option.
These can be created by users.
New in version 2.0.
- Parameters
label (
str
) – The label of the option. This is displayed to users. Can only be up to 100 characters.value (
str
) – The value of the option. This is not displayed to users. If not provided when constructed then it defaults to the label. Can only be up to 100 characters.description (Optional[
str
]) – An additional description of the option, if any. Can only be up to 100 characters.emoji (Optional[Union[
str
,Emoji
,PartialEmoji
]]) – The emoji of the option, if available.default (
bool
) – Whether this option is selected by default.
- value¶
The value of the option. This is not displayed to users. If not provided when constructed then it defaults to the label.
- Type
- property emoji¶
The emoji of the option, if available.
- Type
Optional[
PartialEmoji
]
SelectDefaultValue¶
- class discord.SelectDefaultValue(*, id, type)¶
Represents a select menu’s default value.
These can be created by users.
New in version 2.4.
- Parameters
id (
int
) – The id of a role, user, or channel.type (
SelectDefaultValueType
) – The type of value thatid
represents.
- property type¶
The type of value that
id
represents.
- classmethod from_channel(channel, /)¶
Creates a
SelectDefaultValue
with the type set tochannel
.- Parameters
channel (
Snowflake
) – The channel to create the default value for.- Returns
The default value created with the channel.
- Return type
- classmethod from_role(role, /)¶
Creates a
SelectDefaultValue
with the type set torole
.- Parameters
role (
Snowflake
) – The role to create the default value for.- Returns
The default value created with the role.
- Return type
- classmethod from_user(user, /)¶
Creates a
SelectDefaultValue
with the type set touser
.- Parameters
user (
Snowflake
) – The user to create the default value for.- Returns
The default value created with the user.
- Return type
Choice¶
- class discord.app_commands.Choice(*, name, value)¶
Represents an application command argument choice.
New in version 2.0.
- x == y
Checks if two choices are equal.
- x != y
Checks if two choices are not equal.
- hash(x)
Returns the choice’s hash.
- Parameters
name (Union[
str
,locale_str
]) – The name of the choice. Used for display purposes. Can only be up to 100 characters.name_localizations (Dict[
Locale
,str
]) – The localised names of the choice. Used for display purposes.value (Union[
int
,str
,float
]) – The value of the choice. If it’s a string, it can only be up to 100 characters long.
Enumerations¶
- class discord.InteractionType¶
Specifies the type of
Interaction
.New in version 2.0.
- ping¶
Represents Discord pinging to see if the interaction response server is alive.
- application_command¶
Represents a slash command interaction.
- component¶
Represents a component based interaction, i.e. using the Discord Bot UI Kit.
- autocomplete¶
Represents an auto complete interaction.
- modal_submit¶
Represents submission of a modal interaction.
- class discord.InteractionResponseType¶
Specifies the response type for the interaction.
New in version 2.0.
- pong¶
Pongs the interaction when given a ping.
See also
InteractionResponse.pong()
- channel_message¶
Respond to the interaction with a message.
See also
InteractionResponse.send_message()
- deferred_channel_message¶
Responds to the interaction with a message at a later time.
See also
InteractionResponse.defer()
- deferred_message_update¶
Acknowledges the component interaction with a promise that the message will update later (though there is no need to actually update the message).
See also
InteractionResponse.defer()
- message_update¶
Responds to the interaction by editing the message.
See also
InteractionResponse.edit_message()
- autocomplete_result¶
Responds to the autocomplete interaction with suggested choices.
See also
InteractionResponse.autocomplete()
- modal¶
Responds to the interaction with a modal.
See also
InteractionResponse.send_modal()
- class discord.ComponentType¶
Represents the component type of a component.
New in version 2.0.
- action_row¶
Represents the group component which holds different components in a row.
- button¶
Represents a button component.
- text_input¶
Represents a text box component.
- select¶
Represents a select component.
- user_select¶
Represents a user select component.
- role_select¶
Represents a role select component.
- mentionable_select¶
Represents a select in which both users and roles can be selected.
- class discord.ButtonStyle¶
Represents the style of the button component.
New in version 2.0.
- primary¶
Represents a blurple button for the primary action.
- secondary¶
Represents a grey button for the secondary action.
- success¶
Represents a green button for a successful action.
- danger¶
Represents a red button for a dangerous action.
- link¶
Represents a link button.
Represents a button denoting that buying a SKU is required to perform this action.
New in version 2.4.
- class discord.TextStyle¶
Represents the style of the text box component.
New in version 2.0.
- short¶
Represents a short text box.
- paragraph¶
Represents a long form text box.
- class discord.AppCommandOptionType¶
The application command’s option type. This is usually the type of parameter an application command takes.
New in version 2.0.
- subcommand¶
A subcommand.
- subcommand_group¶
A subcommand group.
- string¶
A string parameter.
- integer¶
A integer parameter.
- boolean¶
A boolean parameter.
- user¶
A user parameter.
- channel¶
A channel parameter.
- role¶
A role parameter.
- mentionable¶
A mentionable parameter.
- number¶
A number parameter.
- attachment¶
An attachment parameter.
Bot UI Kit¶
The library has helpers to aid in creating component-based UIs. These are all in the discord.ui
package.
View¶
- clsView.from_message
- defadd_item
- defclear_items
- asyncinteraction_check
- defis_dispatching
- defis_finished
- defis_persistent
- asyncon_error
- asyncon_timeout
- defremove_item
- defstop
- asyncwait
- class discord.ui.View(*, timeout=180.0)¶
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
- Parameters
timeout (Optional[
float
]) – Timeout in seconds from last interaction with the UI before no longer accepting input. IfNone
then there is no timeout.
- property timeout¶
The timeout in seconds from last interaction with the UI before no longer accepting input. If
None
then there is no timeout.- Type
Optional[
float
]
- classmethod from_message(message, /, *, timeout=180.0)¶
Converts a message’s components into a
View
.The
Message.components
of a message are read-only and separate types from those in thediscord.ui
namespace. In order to modify and edit message components they must be converted into aView
first.- Parameters
message (
discord.Message
) – The message with components to convert into a view.timeout (Optional[
float
]) – The timeout of the converted view.
- Returns
The converted view. This always returns a
View
and not one of its subclasses.- Return type
- add_item(item)¶
Adds an item to the view.
This function returns the class instance to allow for fluent-style chaining.
- Parameters
item (
Item
) – The item to add to the view.- Raises
ValueError – Maximum number of children has been exceeded (25) or the row the item is trying to be added to is full.
- remove_item(item)¶
Removes an item from the view.
This function returns the class instance to allow for fluent-style chaining.
- Parameters
item (
Item
) – The item to remove from the view.
- clear_items()¶
Removes all items from the view.
This function returns the class instance to allow for fluent-style chaining.
- await interaction_check(interaction, /)¶
This function is a coroutine.
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns
True
.Note
If an exception occurs within the body then the check is considered a failure and
on_error()
is called.- Parameters
interaction (
Interaction
) – The interaction that occurred.- Returns
Whether the view children’s callbacks should be called.
- Return type
- await on_timeout()¶
This function is a coroutine.
A callback that is called when a view’s timeout elapses without being explicitly stopped.
- await on_error(interaction, error, item, /)¶
This function is a coroutine.
A callback that is called when an item’s callback or
interaction_check()
fails with an error.The default implementation logs to the library logger.
- Parameters
interaction (
Interaction
) – The interaction that led to the failure.error (
Exception
) – The exception that was raised.item (
Item
) – The item that failed the dispatch.
- stop()¶
Stops listening to interaction events from this view.
This operation cannot be undone.
Modal¶
- clsModal.from_message
- defadd_item
- defclear_items
- asyncinteraction_check
- defis_dispatching
- defis_finished
- defis_persistent
- asyncon_error
- asyncon_submit
- asyncon_timeout
- defremove_item
- defstop
- asyncwait
- class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)¶
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples
import discord from discord import ui class Questionnaire(ui.Modal, title='Questionnaire Response'): name = ui.TextInput(label='Name') answer = ui.TextInput(label='Answer', style=discord.TextStyle.paragraph) async def on_submit(self, interaction: discord.Interaction): await interaction.response.send_message(f'Thanks for your response, {self.name}!', ephemeral=True)
- Parameters
title (
str
) – The title of the modal. Can only be up to 45 characters.timeout (Optional[
float
]) – Timeout in seconds from last interaction with the UI before no longer accepting input. IfNone
then there is no timeout.custom_id (
str
) – The ID of the modal that gets received during an interaction. If not given then one is generated for you. Can only be up to 100 characters.
- await on_submit(interaction, /)¶
This function is a coroutine.
Called when the modal is submitted.
- Parameters
interaction (
Interaction
) – The interaction that submitted this modal.
- await on_error(interaction, error, /)¶
This function is a coroutine.
A callback that is called when
on_submit()
fails with an error.The default implementation logs to the library logger.
- Parameters
interaction (
Interaction
) – The interaction that led to the failure.error (
Exception
) – The exception that was raised.
- add_item(item)¶
Adds an item to the view.
This function returns the class instance to allow for fluent-style chaining.
- Parameters
item (
Item
) – The item to add to the view.- Raises
ValueError – Maximum number of children has been exceeded (25) or the row the item is trying to be added to is full.
- clear_items()¶
Removes all items from the view.
This function returns the class instance to allow for fluent-style chaining.
- classmethod from_message(message, /, *, timeout=180.0)¶
Converts a message’s components into a
View
.The
Message.components
of a message are read-only and separate types from those in thediscord.ui
namespace. In order to modify and edit message components they must be converted into aView
first.- Parameters
message (
discord.Message
) – The message with components to convert into a view.timeout (Optional[
float
]) – The timeout of the converted view.
- Returns
The converted view. This always returns a
View
and not one of its subclasses.- Return type
- await interaction_check(interaction, /)¶
This function is a coroutine.
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns
True
.Note
If an exception occurs within the body then the check is considered a failure and
on_error()
is called.- Parameters
interaction (
Interaction
) – The interaction that occurred.- Returns
Whether the view children’s callbacks should be called.
- Return type
- is_persistent()¶
bool
: Whether the view is set up as persistent.A persistent view has all their components with a set
custom_id
and atimeout
set toNone
.
- await on_timeout()¶
This function is a coroutine.
A callback that is called when a view’s timeout elapses without being explicitly stopped.
- remove_item(item)¶
Removes an item from the view.
This function returns the class instance to allow for fluent-style chaining.
- Parameters
item (
Item
) – The item to remove from the view.
- stop()¶
Stops listening to interaction events from this view.
This operation cannot be undone.
Item¶
- asynccallback
- asyncinteraction_check
- class discord.ui.Item¶
Represents the base UI item that all UI components inherit from.
The current UI items supported are:
New in version 2.0.
- await callback(interaction)¶
This function is a coroutine.
The callback associated with this UI item.
This can be overridden by subclasses.
- Parameters
interaction (
Interaction
) – The interaction that triggered this UI item.
- await interaction_check(interaction, /)¶
This function is a coroutine.
A callback that is called when an interaction happens within this item that checks whether the callback should be processed.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns
True
.Note
If an exception occurs within the body then the check is considered a failure and
discord.ui.View.on_error()
is called.For
DynamicItem
this does not call theon_error
handler.New in version 2.4.
- Parameters
interaction (
Interaction
) – The interaction that occurred.- Returns
Whether the callback should be called.
- Return type
DynamicItem¶
- clsDynamicItem.from_custom_id
- asynccallback
- asyncinteraction_check
- class discord.ui.DynamicItem(item, *, row=None)¶
Represents an item with a dynamic
custom_id
that can be used to store state within thatcustom_id
.The
custom_id
parsing is done using there
module by passing atemplate
parameter to the class parameter list.This item is generated every time the component is dispatched. This means that any variable that holds an instance of this class will eventually be out of date and should not be used long term. Their only purpose is to act as a “template” for the actual dispatched item.
When this item is generated,
view
is set to a regularView
instance from the original message given from the interaction. This means that custom view subclasses cannot be accessed from this item.New in version 2.4.
- Parameters
item (
Item
) – The item to wrap with dynamic custom ID parsing.template (Union[
str
,re.Pattern
]) – The template to use for parsing thecustom_id
. This can be a string or a compiled regular expression. This must be passed as a keyword argument to the class creation.row (Optional[
int
]) – The relative row this button belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults toNone
, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).
- property template¶
The compiled regular expression that is used to parse the
custom_id
.- Type
re.Pattern
- classmethod await from_custom_id(interaction, item, match, /)¶
This function is a coroutine.
A classmethod that is called when the
custom_id
of a component matches thetemplate
of the class. This is called when the component is dispatched.It must return a new instance of the
DynamicItem
.Subclasses must implement this method.
Exceptions raised in this method are logged and ignored.
Warning
This method is called before the callback is dispatched, therefore it means that it is subject to the same timing restrictions as the callback. Ergo, you must reply to an interaction within 3 seconds of it being dispatched.
- Parameters
interaction (
Interaction
) – The interaction that the component belongs to.item (
Item
) – The base item that is being dispatched.match (
re.Match
) – The match object that was created from thetemplate
matching thecustom_id
.
- Returns
The new instance of the
DynamicItem
with information from thematch
object.- Return type
- await callback(interaction)¶
This function is a coroutine.
The callback associated with this UI item.
This can be overridden by subclasses.
- Parameters
interaction (
Interaction
) – The interaction that triggered this UI item.
- await interaction_check(interaction, /)¶
This function is a coroutine.
A callback that is called when an interaction happens within this item that checks whether the callback should be processed.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns
True
.Note
If an exception occurs within the body then the check is considered a failure and
discord.ui.View.on_error()
is called.For
DynamicItem
this does not call theon_error
handler.New in version 2.4.
- Parameters
interaction (
Interaction
) – The interaction that occurred.- Returns
Whether the callback should be called.
- Return type
Button¶
- asynccallback
- asyncinteraction_check
- class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None, sku_id=None)¶
Represents a UI button.
New in version 2.0.
- Parameters
style (
discord.ButtonStyle
) – The style of the button.custom_id (Optional[
str
]) – The ID of the button that gets received during an interaction. If this button is for a URL, it does not have a custom ID. Can only be up to 100 characters.url (Optional[
str
]) – The URL this button sends you to.disabled (
bool
) – Whether the button is disabled or not.label (Optional[
str
]) – The label of the button, if any. Can only be up to 80 characters.emoji (Optional[Union[
PartialEmoji
,Emoji
,str
]]) – The emoji of the button, if available.row (Optional[
int
]) – The relative row this button belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults toNone
, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).sku_id (Optional[
int
]) –The SKU ID this button sends you to. Can’t be combined with
url
,label
,emoji
norcustom_id
.New in version 2.4.
- property style¶
The style of the button.
- Type
- property custom_id¶
The ID of the button that gets received during an interaction.
If this button is for a URL, it does not have a custom ID.
- Type
Optional[
str
]
- property emoji¶
The emoji of the button, if available.
- Type
Optional[
PartialEmoji
]
- await callback(interaction)¶
This function is a coroutine.
The callback associated with this UI item.
This can be overridden by subclasses.
- Parameters
interaction (
Interaction
) – The interaction that triggered this UI item.
- await interaction_check(interaction, /)¶
This function is a coroutine.
A callback that is called when an interaction happens within this item that checks whether the callback should be processed.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns
True
.Note
If an exception occurs within the body then the check is considered a failure and
discord.ui.View.on_error()
is called.For
DynamicItem
this does not call theon_error
handler.New in version 2.4.
- Parameters
interaction (
Interaction
) – The interaction that occurred.- Returns
Whether the callback should be called.
- Return type
- @discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)¶
A decorator that attaches a button to a component.
The function being decorated should have three parameters,
self
representing thediscord.ui.View
, thediscord.Interaction
you receive and thediscord.ui.Button
being pressed.Note
Buttons with a URL or an SKU cannot be created with this function. Consider creating a
Button
manually instead. This is because these buttons cannot have a callback associated with them since Discord does not do any processing with them.- Parameters
label (Optional[
str
]) – The label of the button, if any. Can only be up to 80 characters.custom_id (Optional[
str
]) – The ID of the button that gets received during an interaction. It is recommended not to set this parameter to prevent conflicts. Can only be up to 100 characters.style (
ButtonStyle
) – The style of the button. Defaults toButtonStyle.grey
.disabled (
bool
) – Whether the button is disabled or not. Defaults toFalse
.emoji (Optional[Union[
str
,Emoji
,PartialEmoji
]]) – The emoji of the button. This can be in string form or aPartialEmoji
or a fullEmoji
.row (Optional[
int
]) – The relative row this button belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults toNone
, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).
TextInput¶
- asynccallback
- asyncinteraction_check
- class discord.ui.TextInput(*, label, style=<TextStyle.short: 1>, custom_id=..., placeholder=None, default=None, required=True, min_length=None, max_length=None, row=None)¶
Represents a UI text input.
- str(x)
Returns the value of the text input or an empty string if the value is
None
.
New in version 2.0.
- Parameters
label (
str
) – The label to display above the text input. Can only be up to 45 characters.custom_id (
str
) – The ID of the text input that gets received during an interaction. If not given then one is generated for you. Can only be up to 100 characters.style (
discord.TextStyle
) – The style of the text input.placeholder (Optional[
str
]) – The placeholder text to display when the text input is empty. Can only be up to 100 characters.default (Optional[
str
]) – The default value of the text input. Can only be up to 4000 characters.required (
bool
) – Whether the text input is required.min_length (Optional[
int
]) – The minimum length of the text input. Must be between 0 and 4000.max_length (Optional[
int
]) – The maximum length of the text input. Must be between 1 and 4000.row (Optional[
int
]) – The relative row this text input belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you’d like to control the relative positioning of the row then passing an index is advised. For example, row=1 will show up before row=2. Defaults toNone
, which is automatic ordering. The row number must be between 0 and 4 (i.e. zero indexed).
- property style¶
The style of the text input.
- Type
- await callback(interaction)¶
This function is a coroutine.
The callback associated with this UI item.
This can be overridden by subclasses.
- Parameters
interaction (
Interaction
) – The interaction that triggered this UI item.
- await interaction_check(interaction, /)¶
This function is a coroutine.
A callback that is called when an interaction happens within this item that checks whether the callback should be processed.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns
True
.Note
If an exception occurs within the body then the check is considered a failure and
discord.ui.View.on_error()
is called.For
DynamicItem
this does not call theon_error
handler.New in version 2.4.
- Parameters
interaction (
Interaction
) – The interaction that occurred.- Returns
Whether the callback should be called.
- Return type
Application Commands¶
The library has helpers to aid in creation of application commands. These are all in the discord.app_commands
package.
CommandTree¶
- defadd_command
- defclear_commands
- @command
- @context_menu
- defcopy_global_to
- @error
- asyncfetch_command
- asyncfetch_commands
- defget_command
- defget_commands
- asyncinteraction_check
- asyncon_error
- defremove_command
- asyncset_translator
- asyncsync
- defwalk_commands
- class discord.app_commands.CommandTree(client, *, fallback_to_global=True, allowed_contexts=..., allowed_installs=...)¶
Represents a container that holds application command information.
- Parameters
client (
Client
) – The client instance to get application command information from.fallback_to_global (
bool
) – If a guild-specific command is not found when invoked, then try falling back into a global command in the tree. For example, if the tree locally has a/ping
command under the global namespace but the guild has a guild-specific/ping
, instead of failing to find the guild-specific/ping
command it will fall back to the global/ping
command. This has the potential to raise moreCommandSignatureMismatch
errors than usual. Defaults toTrue
.allowed_contexts (
AppCommandContext
) –The default allowed contexts that applies to all commands in this tree. Note that you can override this on a per command basis.
New in version 2.4.
allowed_installs (
AppInstallationType
) –The default allowed install locations that apply to all commands in this tree. Note that you can override this on a per command basis.
New in version 2.4.
- @command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)¶
A decorator that creates an application command from a regular function directly under this tree.
- Parameters
name (Union[
str
,locale_str
]) – The name of the application command. If not given, it defaults to a lower-case version of the callback name.description (Union[
str
,locale_str
]) – The description of the application command. This shows up in the UI to describe the application command. If not given, it defaults to the first line of the docstring of the callback shortened to 100 characters.nsfw (
bool
) –Whether the command is NSFW and should only work in NSFW channels. Defaults to
False
.Due to a Discord limitation, this does not work on subcommands.
guild (Optional[
Snowflake
]) –The guild to add the command to. If not given or
None
then it becomes a global command instead.Note
Due to a Discord limitation, this keyword argument cannot be used in conjunction with contexts (e.g.
app_commands.allowed_contexts()
) or installation types (e.g.app_commands.allowed_installs()
).guilds (List[
Snowflake
]) –The list of guilds to add the command to. This cannot be mixed with the
guild
parameter. If no guilds are given at all then it becomes a global command instead.Note
Due to a Discord limitation, this keyword argument cannot be used in conjunction with contexts (e.g.
app_commands.allowed_contexts()
) or installation types (e.g.app_commands.allowed_installs()
).auto_locale_strings (
bool
) – If this is set toTrue
, then all translatable strings will implicitly be wrapped intolocale_str
rather thanstr
. This could avoid some repetition and be more ergonomic for certain defaults such as default command names, command descriptions, and parameter names. Defaults toTrue
.extras (
dict
) – A dictionary that can be used to store extraneous data. The library will not touch any values or keys within this dictionary.
A decorator that creates an application command context menu from a regular function directly under this tree.
This function must have a signature of
Interaction
as its first parameter and taking either aMember
,User
, orMessage
, or atyping.Union
ofMember
andUser
as its second parameter.Examples
@app_commands.context_menu() async def react(interaction: discord.Interaction, message: discord.Message): await interaction.response.send_message('Very cool message!', ephemeral=True) @app_commands.context_menu() async def ban(interaction: discord.Interaction, user: discord.Member): await interaction.response.send_message(f'Should I actually ban {user}...', ephemeral=True)
- Parameters
name (Union[
str
,locale_str
]) – The name of the context menu command. If not given, it defaults to a title-case version of the callback name. Note that unlike regular slash commands this can have spaces and upper case characters in the name.nsfw (
bool
) –Whether the command is NSFW and should only work in NSFW channels. Defaults to
False
.Due to a Discord limitation, this does not work on subcommands.
guild (Optional[
Snowflake
]) –The guild to add the command to. If not given or
None
then it becomes a global command instead.Note
Due to a Discord limitation, this keyword argument cannot be used in conjunction with contexts (e.g.
app_commands.allowed_contexts()
) or installation types (e.g.app_commands.allowed_installs()
).guilds (List[
Snowflake
]) –The list of guilds to add the command to. This cannot be mixed with the
guild
parameter. If no guilds are given at all then it becomes a global command instead.Note
Due to a Discord limitation, this keyword argument cannot be used in conjunction with contexts (e.g.
app_commands.allowed_contexts()
) or installation types (e.g.app_commands.allowed_installs()
).auto_locale_strings (
bool
) – If this is set toTrue
, then all translatable strings will implicitly be wrapped intolocale_str
rather thanstr
. This could avoid some repetition and be more ergonomic for certain defaults such as default command names, command descriptions, and parameter names. Defaults toTrue
.extras (
dict
) – A dictionary that can be used to store extraneous data. The library will not touch any values or keys within this dictionary.
- @error(coro)¶
A decorator that registers a coroutine as a local error handler.
This must match the signature of the
on_error()
callback.The error passed will be derived from
AppCommandError
.
- await fetch_command(command_id, /, *, guild=None)¶
This function is a coroutine.
Fetches an application command from the application.
- Parameters
- Raises
HTTPException – Fetching the command failed.
MissingApplicationID – The application ID could not be found.
NotFound – The application command was not found. This could also be because the command is a guild command and the guild was not specified and vice versa.
- Returns
The application command.
- Return type
- await fetch_commands(*, guild=None)¶
This function is a coroutine.
Fetches the application’s current commands.
If no guild is passed then global commands are fetched, otherwise the guild’s commands are fetched instead.
Note
This includes context menu commands.
- Parameters
guild (Optional[
Snowflake
]) – The guild to fetch the commands from. If not passed then global commands are fetched instead.- Raises
HTTPException – Fetching the commands failed.
MissingApplicationID – The application ID could not be found.
- Returns
The application’s commands.
- Return type
List[
AppCommand
]
- copy_global_to(*, guild)¶
Copies all global commands to the specified guild.
This method is mainly available for development purposes, as it allows you to copy your global commands over to a testing guild easily.
Note that this method will override pre-existing guild commands that would conflict.
- Parameters
guild (
Snowflake
) – The guild to copy the commands to.- Raises
CommandLimitReached – The maximum number of commands was reached for that guild. This is currently 100 for slash commands and 5 for context menu commands.
- add_command(command, /, *, guild=..., guilds=..., override=False)¶
Adds an application command to the tree.
This only adds the command locally – in order to sync the commands and enable them in the client,
sync()
must be called.The root parent of the command is added regardless of the type passed.
- Parameters
command (Union[
Command
,Group
]) – The application command or group to add.guild (Optional[
Snowflake
]) –The guild to add the command to. If not given or
None
then it becomes a global command instead.Note
Due to a Discord limitation, this keyword argument cannot be used in conjunction with contexts (e.g.
app_commands.allowed_contexts()
) or installation types (e.g.app_commands.allowed_installs()
).guilds (List[
Snowflake
]) –The list of guilds to add the command to. This cannot be mixed with the
guild
parameter. If no guilds are given at all then it becomes a global command instead.Note
Due to a Discord limitation, this keyword argument cannot be used in conjunction with contexts (e.g.
app_commands.allowed_contexts()
) or installation types (e.g.app_commands.allowed_installs()
).override (
bool
) – Whether to override a command with the same name. IfFalse
an exception is raised. Default isFalse
.
- Raises
CommandAlreadyRegistered – The command was already registered and no override was specified.
TypeError – The application command passed is not a valid application command. Or,
guild
andguilds
were both given.CommandLimitReached – The maximum number of commands was reached globally or for that guild. This is currently 100 for slash commands and 5 for context menu commands.
- remove_command(command, /, *, guild=None, type=<AppCommandType.chat_input: 1>)¶
Removes an application command from the tree.
This only removes the command locally – in order to sync the commands and remove them in the client,
sync()
must be called.- Parameters
command (
str
) – The name of the root command to remove.guild (Optional[
Snowflake
]) – The guild to remove the command from. If not given orNone
then it removes a global command instead.type (
AppCommandType
) – The type of command to remove. Defaults tochat_input
, i.e. slash commands.
- Returns
The application command that got removed. If nothing was removed then
None
is returned instead.- Return type
Optional[Union[
Command
,ContextMenu
,Group
]]
- clear_commands(*, guild, type=None)¶
Clears all application commands from the tree.
This only removes the commands locally – in order to sync the commands and remove them in the client,
sync()
must be called.- Parameters
guild (Optional[
Snowflake
]) – The guild to remove the commands from. IfNone
then it removes all global commands instead.type (
AppCommandType
) – The type of command to clear. If not given orNone
then it removes all commands regardless of the type.
- get_command(command, /, *, guild=None, type=<AppCommandType.chat_input: 1>)¶
Gets an application command from the tree.
- Parameters
command (
str
) – The name of the root command to get.guild (Optional[
Snowflake
]) – The guild to get the command from. If not given orNone
then it gets a global command instead.type (
AppCommandType
) – The type of command to get. Defaults tochat_input
, i.e. slash commands.
- Returns
The application command that was found. If nothing was found then
None
is returned instead.- Return type
Optional[Union[
Command
,ContextMenu
,Group
]]
- get_commands(*, guild=None, type=None)¶
Gets all application commands from the tree.
- Parameters
guild (Optional[
Snowflake
]) – The guild to get the commands from, not including global commands. If not given orNone
then only global commands are returned.type (Optional[
AppCommandType
]) – The type of commands to get. When not given orNone
, then all command types are returned.
- Returns
The application commands from the tree.
- Return type
List[Union[
ContextMenu
,Command
,Group
]]
- for ... in walk_commands(*, guild=None, type=<AppCommandType.chat_input: 1>)¶
An iterator that recursively walks through all application commands and child commands from the tree.
- Parameters
guild (Optional[
Snowflake
]) – The guild to iterate the commands from, not including global commands. If not given orNone
then only global commands are iterated.type (
AppCommandType
) – The type of commands to iterate over. Defaults tochat_input
, i.e. slash commands.
- Yields
Union[
ContextMenu
,Command
,Group
] – The application commands from the tree.
- await on_error(interaction, error, /)¶
This function is a coroutine.
A callback that is called when any command raises an
AppCommandError
.The default implementation logs the exception using the library logger if the command does not have any error handlers attached to it.
To get the command that failed,
discord.Interaction.command
should be used.- Parameters
interaction (
Interaction
) – The interaction that is being handled.error (
AppCommandError
) – The exception that was raised.
- property translator¶
The translator, if any, responsible for handling translation of commands.
To change the translator, use
set_translator()
.- Type
Optional[
Translator
]
- await set_translator(translator)¶
This function is a coroutine.
Sets the translator to use for translating commands.
If a translator was previously set, it will be unloaded using its
Translator.unload()
method.When a translator is set, it will be loaded using its
Translator.load()
method.- Parameters
translator (Optional[
Translator
]) – The translator to use. IfNone
then the translator is just removed and unloaded.- Raises
TypeError – The translator was not
None
or aTranslator
instance.
- await sync(*, guild=None)¶
This function is a coroutine.
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
- Parameters
guild (Optional[
Snowflake
]) – The guild to sync the commands to. IfNone
then it syncs all global commands instead.- Raises
HTTPException – Syncing the commands failed.
CommandSyncFailure – Syncing the commands failed due to a user related error, typically because the command has invalid data. This is equivalent to an HTTP status code of 400.
Forbidden – The client does not have the
applications.commands
scope in the guild.MissingApplicationID – The client does not have an application ID.
TranslationError – An error occurred while translating the commands.
- Returns
The application’s commands that got synced.
- Return type
List[
AppCommand
]
- await interaction_check(interaction, /)¶
This function is a coroutine.
A global check to determine if an
Interaction
should be processed by the tree.The default implementation returns True (all interactions are processed), but can be overridden if custom behaviour is desired.
Commands¶
Command¶
- defadd_check
- @autocomplete
- @error
- defget_parameter
- defremove_check
- class discord.app_commands.Command(*, name, description, callback, nsfw=False, parent=None, guild_ids=None, allowed_contexts=None, allowed_installs=None, auto_locale_strings=True, extras=...)¶
A class that implements an application command.
These are usually not created manually, instead they are created using one of the following decorators:
New in version 2.0.
- Parameters
name (Union[
str
,locale_str
]) – The name of the application command.description (Union[
str
,locale_str
]) – The description of the application command. This shows up in the UI to describe the application command.callback (coroutine) – The coroutine that is executed when the command is called.
auto_locale_strings (
bool
) – If this is set toTrue
, then all translatable strings will implicitly be wrapped intolocale_str
rather thanstr
. This could avoid some repetition and be more ergonomic for certain defaults such as default command names, command descriptions, and parameter names. Defaults toTrue
.nsfw (
bool
) –Whether the command is NSFW and should only work in NSFW channels. Defaults to
False
.Due to a Discord limitation, this does not work on subcommands.
parent (Optional[
Group
]) – The parent application command.None
if there isn’t one.extras (
dict
) – A dictionary that can be used to store extraneous data. The library will not touch any values or keys within this dictionary.
- description¶
The description of the application command. This shows up in the UI to describe the application command.
- Type
- checks¶
A list of predicates that take a
Interaction
parameter to indicate whether the command callback should be executed. If an exception is necessary to be thrown to signal failure, then one inherited fromAppCommandError
should be used. If all the checks fail without propagating an exception,CheckFailure
is raised.
- default_permissions¶
The default permissions that can execute this command on Discord. Note that server administrators can override this value in the client. Setting an empty permissions field will disallow anyone except server administrators from using the command in a guild.
Due to a Discord limitation, this does not work on subcommands.
- Type
Optional[
Permissions
]
- guild_only¶
Whether the command should only be usable in guild contexts.
Due to a Discord limitation, this does not work on subcommands.
- Type
- allowed_contexts¶
The contexts that the command is allowed to be used in. Overrides
guild_only
if this is set.New in version 2.4.
- Type
Optional[
AppCommandContext
]
- allowed_installs¶
The installation contexts that the command is allowed to be installed on.
New in version 2.4.
- Type
Optional[
AppInstallationType
]
- nsfw¶
Whether the command is NSFW and should only work in NSFW channels.
Due to a Discord limitation, this does not work on subcommands.
- Type
- extras¶
A dictionary that can be used to store extraneous data. The library will not touch any values or keys within this dictionary.
- Type
- @autocomplete(name)¶
A decorator that registers a coroutine as an autocomplete prompt for a parameter.
The coroutine callback must have 2 parameters, the
Interaction
, and the current value by the user (the string currently being typed by the user).To get the values from other parameters that may be filled in, accessing
Interaction.namespace
will give aNamespace
object with those values.Parent
checks
are ignored within an autocomplete. However, checks can be added to the autocomplete callback and the ones added will be called. If the checks fail for any reason then an empty list is sent as the interaction response.The coroutine decorator must return a list of
Choice
objects. Only up to 25 objects are supported.Warning
The choices returned from this coroutine are suggestions. The user may ignore them and input their own value.
Example:
@app_commands.command() async def fruits(interaction: discord.Interaction, fruit: str): await interaction.response.send_message(f'Your favourite fruit seems to be {fruit}') @fruits.autocomplete('fruit') async def fruits_autocomplete( interaction: discord.Interaction, current: str, ) -> List[app_commands.Choice[str]]: fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry'] return [ app_commands.Choice(name=fruit, value=fruit) for fruit in fruits if current.lower() in fruit.lower() ]
- @error(coro)¶
A decorator that registers a coroutine as a local error handler.
The local error handler is called whenever an exception is raised in the body of the command or during handling of the command. The error handler must take 2 parameters, the interaction and the error.
The error passed will be derived from
AppCommandError
.
- property parameters¶
Returns a list of parameters for this command.
This does not include the
self
orinteraction
parameters.- Returns
The parameters of this command.
- Return type
List[
Parameter
]
- get_parameter(name)¶
Retrieves a parameter by its name.
The name must be the Python identifier rather than the renamed one for display on Discord.
- property qualified_name¶
Returns the fully qualified command name.
The qualified name includes the parent name as well. For example, in a command like
/foo bar
the qualified name isfoo bar
.- Type
- add_check(func, /)¶
Adds a check to the command.
This is the non-decorator interface to
check()
.- Parameters
func – The function that will be used as a check.
- remove_check(func, /)¶
Removes a check from the command.
This function is idempotent and will not raise an exception if the function is not in the command’s checks.
- Parameters
func – The function to remove from the checks.
Parameter¶
- class discord.app_commands.Parameter¶
A class that contains the parameter information of a
Command
callback.New in version 2.0.
- locale_name¶
The display name’s locale string, if available.
- Type
Optional[
locale_str
]
- locale_description¶
The description’s locale string, if available.
- Type
Optional[
locale_str
]
- type¶
The underlying type of this parameter.
- Type
- channel_types¶
The channel types that are allowed for this parameter.
- Type
List[
ChannelType
]
Group¶
- defadd_command
- @command
- @error
- defget_command
- asyncinteraction_check
- asyncon_error
- defremove_command
- defwalk_commands
- class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., allowed_contexts=..., allowed_installs=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)¶
A class that implements an application command group.
These are usually inherited rather than created manually.
Decorators such as
guild_only()
,guilds()
, anddefault_permissions()
will apply to the group if used on top of a subclass. For example:from discord import app_commands @app_commands.guild_only() class MyGroup(app_commands.Group): pass
New in version 2.0.
- Parameters
name (Union[
str
,locale_str
]) – The name of the group. If not given, it defaults to a lower-case kebab-case version of the class name.description (Union[
str
,locale_str
]) – The description of the group. This shows up in the UI to describe the group. If not given, it defaults to the docstring of the class shortened to 100 characters.auto_locale_strings (
bool
) – If this is set toTrue
, then all translatable strings will implicitly be wrapped intolocale_str
rather thanstr
. This could avoid some repetition and be more ergonomic for certain defaults such as default command names, command descriptions, and parameter names. Defaults toTrue
.default_permissions (Optional[
Permissions
]) –The default permissions that can execute this group on Discord. Note that server administrators can override this value in the client. Setting an empty permissions field will disallow anyone except server administrators from using the command in a guild.
Due to a Discord limitation, this does not work on subcommands.
guild_only (
bool
) –Whether the group should only be usable in guild contexts. Defaults to
False
.Due to a Discord limitation, this does not work on subcommands.
nsfw (
bool
) –Whether the command is NSFW and should only work in NSFW channels. Defaults to
False
.Due to a Discord limitation, this does not work on subcommands.
parent (Optional[
Group
]) – The parent application command.None
if there isn’t one.extras (
dict
) – A dictionary that can be used to store extraneous data. The library will not touch any values or keys within this dictionary.
- default_permissions¶
The default permissions that can execute this group on Discord. Note that server administrators can override this value in the client. Setting an empty permissions field will disallow anyone except server administrators from using the command in a guild.
Due to a Discord limitation, this does not work on subcommands.
- Type
Optional[
Permissions
]
- guild_only¶
Whether the group should only be usable in guild contexts.
Due to a Discord limitation, this does not work on subcommands.
- Type
- allowed_contexts¶
The contexts that this group is allowed to be used in. Overrides guild_only if set.
New in version 2.4.
- Type
Optional[
AppCommandContext
]
- allowed_installs¶
The installation contexts that the command is allowed to be installed on.
New in version 2.4.
- Type
Optional[
AppInstallationType
]
- nsfw¶
Whether the command is NSFW and should only work in NSFW channels.
Due to a Discord limitation, this does not work on subcommands.
- Type
- extras¶
A dictionary that can be used to store extraneous data. The library will not touch any values or keys within this dictionary.
- Type
- @command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)¶
A decorator that creates an application command from a regular function under this group.
- Parameters
name (Union[
str
,locale_str
]) – The name of the application command. If not given, it defaults to a lower-case version of the callback name.description (Union[
str
,locale_str
]) – The description of the application command. This shows up in the UI to describe the application command. If not given, it defaults to the first line of the docstring of the callback shortened to 100 characters.nsfw (
bool
) – Whether the command is NSFW and should only work in NSFW channels. Defaults toFalse
.auto_locale_strings (
bool
) – If this is set toTrue
, then all translatable strings will implicitly be wrapped intolocale_str
rather thanstr
. This could avoid some repetition and be more ergonomic for certain defaults such as default command names, command descriptions, and parameter names. Defaults toTrue
.extras (
dict
) – A dictionary that can be used to store extraneous data. The library will not touch any values or keys within this dictionary.
- @error(coro)¶
A decorator that registers a coroutine as a local error handler.
The local error handler is called whenever an exception is raised in a child command. The error handler must take 2 parameters, the interaction and the error.
The error passed will be derived from
AppCommandError
.
- property qualified_name¶
Returns the fully qualified group name.
The qualified name includes the parent name as well. For example, in a group like
/foo bar
the qualified name isfoo bar
.- Type
- for ... in walk_commands()¶
An iterator that recursively walks through all commands that this group contains.
- await on_error(interaction, error, /)¶
This function is a coroutine.
A callback that is called when a child’s command raises an
AppCommandError
.To get the command that failed,
discord.Interaction.command
should be used.The default implementation does nothing.
- Parameters
interaction (
Interaction
) – The interaction that is being handled.error (
AppCommandError
) – The exception that was raised.
- await interaction_check(interaction, /)¶
This function is a coroutine.
A callback that is called when an interaction happens within the group that checks whether a command inside the group should be executed.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns
True
.Note
If an exception occurs within the body then the check is considered a failure and error handlers such as
on_error()
is called. SeeAppCommandError
for more information.- Parameters
interaction (
Interaction
) – The interaction that occurred.- Returns
Whether the view children’s callbacks should be called.
- Return type
- add_command(command, /, *, override=False)¶
Adds a command or group to this group’s internal list of commands.
- Parameters
- Raises
CommandAlreadyRegistered – The command or group is already registered. Note that the
CommandAlreadyRegistered.guild_id
attribute will always beNone
in this case.ValueError – There are too many commands already registered or the group is too deeply nested.
TypeError – The wrong command type was passed.
- remove_command(name, /)¶
Removes a command or group from the internal list of commands.
Decorators¶
- @discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)¶
Creates an application command from a regular function.
- Parameters
name (
str
) – The name of the application command. If not given, it defaults to a lower-case version of the callback name.description (
str
) – The description of the application command. This shows up in the UI to describe the application command. If not given, it defaults to the first line of the docstring of the callback shortened to 100 characters.nsfw (
bool
) –Whether the command is NSFW and should only work in NSFW channels. Defaults to
False
.Due to a Discord limitation, this does not work on subcommands.
auto_locale_strings (
bool
) – If this is set toTrue
, then all translatable strings will implicitly be wrapped intolocale_str
rather thanstr
. This could avoid some repetition and be more ergonomic for certain defaults such as default command names, command descriptions, and parameter names. Defaults toTrue
.extras (
dict
) – A dictionary that can be used to store extraneous data. The library will not touch any values or keys within this dictionary.
Creates an application command context menu from a regular function.
This function must have a signature of
Interaction
as its first parameter and taking either aMember
,User
, orMessage
, or atyping.Union
ofMember
andUser
as its second parameter.Examples
@app_commands.context_menu() async def react(interaction: discord.Interaction, message: discord.Message): await interaction.response.send_message('Very cool message!', ephemeral=True) @app_commands.context_menu() async def ban(interaction: discord.Interaction, user: discord.Member): await interaction.response.send_message(f'Should I actually ban {user}...', ephemeral=True)
- Parameters
name (Union[
str
,locale_str
]) – The name of the context menu command. If not given, it defaults to a title-case version of the callback name. Note that unlike regular slash commands this can have spaces and upper case characters in the name.nsfw (
bool
) –Whether the command is NSFW and should only work in NSFW channels. Defaults to
False
.Due to a Discord limitation, this does not work on subcommands.
auto_locale_strings (
bool
) – If this is set toTrue
, then all translatable strings will implicitly be wrapped intolocale_str
rather thanstr
. This could avoid some repetition and be more ergonomic for certain defaults such as default command names, command descriptions, and parameter names. Defaults toTrue
.extras (
dict
) – A dictionary that can be used to store extraneous data. The library will not touch any values or keys within this dictionary.
- @discord.app_commands.describe(**parameters)¶
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
@app_commands.command(description='Bans a member') @app_commands.describe(member='the member to ban') async def ban(interaction: discord.Interaction, member: discord.Member): await interaction.response.send_message(f'Banned {member}')
Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings.
Example:
@app_commands.command() async def ban(interaction: discord.Interaction, member: discord.Member): """Bans a member Parameters ----------- member: discord.Member the member to ban """ await interaction.response.send_message(f'Banned {member}')
- Parameters
**parameters (Union[
str
,locale_str
]) – The description of the parameters.- Raises
TypeError – The parameter name is not found.
- @discord.app_commands.rename(**parameters)¶
Renames the given parameters by their name using the key of the keyword argument as the name.
This renames the parameter within the Discord UI. When referring to the parameter in other decorators, the parameter name used in the function is used instead of the renamed one.
Example:
@app_commands.command() @app_commands.rename(the_member_to_ban='member') async def ban(interaction: discord.Interaction, the_member_to_ban: discord.Member): await interaction.response.send_message(f'Banned {the_member_to_ban}')
- Parameters
**parameters (Union[
str
,locale_str
]) – The name of the parameters.- Raises
ValueError – The parameter name is already used by another parameter.
TypeError – The parameter name is not found.
- @discord.app_commands.choices(**parameters)¶
Instructs the given parameters by their name to use the given choices for their choices.
Example:
@app_commands.command() @app_commands.describe(fruits='fruits to choose from') @app_commands.choices(fruits=[ Choice(name='apple', value=1), Choice(name='banana', value=2), Choice(name='cherry', value=3), ]) async def fruit(interaction: discord.Interaction, fruits: Choice[int]): await interaction.response.send_message(f'Your favourite fruit is {fruits.name}.')
Note
This is not the only way to provide choices to a command. There are two more ergonomic ways of doing this. The first one is to use a
typing.Literal
annotation:@app_commands.command() @app_commands.describe(fruits='fruits to choose from') async def fruit(interaction: discord.Interaction, fruits: Literal['apple', 'banana', 'cherry']): await interaction.response.send_message(f'Your favourite fruit is {fruits}.')
The second way is to use an
enum.Enum
:class Fruits(enum.Enum): apple = 1 banana = 2 cherry = 3 @app_commands.command() @app_commands.describe(fruits='fruits to choose from') async def fruit(interaction: discord.Interaction, fruits: Fruits): await interaction.response.send_message(f'Your favourite fruit is {fruits}.')
- Parameters
**parameters – The choices of the parameters.
- Raises
TypeError – The parameter name is not found or the parameter type was incorrect.
- @discord.app_commands.autocomplete(**parameters)¶
Associates the given parameters with the given autocomplete callback.
Autocomplete is only supported on types that have
str
,int
, orfloat
values.Checks
are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.For more information, see the
Command.autocomplete()
documentation.Warning
The choices returned from this coroutine are suggestions. The user may ignore them and input their own value.
Example:
async def fruit_autocomplete( interaction: discord.Interaction, current: str, ) -> List[app_commands.Choice[str]]: fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry'] return [ app_commands.Choice(name=fruit, value=fruit) for fruit in fruits if current.lower() in fruit.lower() ] @app_commands.command() @app_commands.autocomplete(fruit=fruit_autocomplete) async def fruits(interaction: discord.Interaction, fruit: str): await interaction.response.send_message(f'Your favourite fruit seems to be {fruit}')
- Parameters
**parameters – The parameters to mark as autocomplete.
- Raises
TypeError – The parameter name is not found or the parameter type was incorrect.
- @discord.app_commands.guilds(*guild_ids)¶
Associates the given guilds with the command.
When the command instance is added to a
CommandTree
, the guilds that are specified by this decorator become the default guilds that it’s added to rather than being a global command.Note
Due to an implementation quirk and Python limitation, if this is used in conjunction with the
CommandTree.command()
orCommandTree.context_menu()
decorator then this must go below that decorator.Note
Due to a Discord limitation, this decorator cannot be used in conjunction with contexts (e.g.
app_commands.allowed_contexts()
) or installation types (e.g.app_commands.allowed_installs()
).Example:
MY_GUILD_ID = discord.Object(...) # Guild ID here @app_commands.command() @app_commands.guilds(MY_GUILD_ID) async def bonk(interaction: discord.Interaction): await interaction.response.send_message('Bonk', ephemeral=True)
- @discord.app_commands.guild_only(func=None)¶
A decorator that indicates this command can only be used in a guild context.
This is not implemented as a
check()
, and is instead verified by Discord server side. Therefore, there is no error handler called when a command is used within a private message.This decorator can be called with or without parentheses.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Examples
@app_commands.command() @app_commands.guild_only() async def my_guild_only_command(interaction: discord.Interaction) -> None: await interaction.response.send_message('I am only available in guilds!')
- @discord.app_commands.dm_only(func=None)¶
A decorator that indicates this command can only be used in the context of bot DMs.
This is not implemented as a
check()
, and is instead verified by Discord server side. Therefore, there is no error handler called when a command is used within a guild or group DM.This decorator can be called with or without parentheses.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Examples
@app_commands.command() @app_commands.dm_only() async def my_dm_only_command(interaction: discord.Interaction) -> None: await interaction.response.send_message('I am only available in DMs!')
- @discord.app_commands.private_channel_only(func=None)¶
A decorator that indicates this command can only be used in the context of DMs and group DMs.
This is not implemented as a
check()
, and is instead verified by Discord server side. Therefore, there is no error handler called when a command is used within a guild.This decorator can be called with or without parentheses.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
New in version 2.4.
Examples
@app_commands.command() @app_commands.private_channel_only() async def my_private_channel_only_command(interaction: discord.Interaction) -> None: await interaction.response.send_message('I am only available in DMs and GDMs!')
- @discord.app_commands.allowed_contexts(guilds=..., dms=..., private_channels=...)¶
A decorator that indicates this command can only be used in certain contexts. Valid contexts are guilds, DMs and private channels.
This is not implemented as a
check()
, and is instead verified by Discord server side.Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
New in version 2.4.
Examples
@app_commands.command() @app_commands.allowed_contexts(guilds=True, dms=False, private_channels=True) async def my_command(interaction: discord.Interaction) -> None: await interaction.response.send_message('I am only available in guilds and private channels!')
- @discord.app_commands.user_install(func=None)¶
A decorator that indicates this command should be installed for users.
This is not implemented as a
check()
, and is instead verified by Discord server side.Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
New in version 2.4.
Examples
@app_commands.command() @app_commands.user_install() async def my_user_install_command(interaction: discord.Interaction) -> None: await interaction.response.send_message('I am installed in users by default!')
- @discord.app_commands.guild_install(func=None)¶
A decorator that indicates this command should be installed in guilds.
This is not implemented as a
check()
, and is instead verified by Discord server side.Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
New in version 2.4.
Examples
@app_commands.command() @app_commands.guild_install() async def my_guild_install_command(interaction: discord.Interaction) -> None: await interaction.response.send_message('I am installed in guilds by default!')
- @discord.app_commands.allowed_installs(guilds=..., users=...)¶
A decorator that indicates this command should be installed in certain contexts. Valid contexts are guilds and users.
This is not implemented as a
check()
, and is instead verified by Discord server side.Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
New in version 2.4.
Examples
@app_commands.command() @app_commands.allowed_installs(guilds=False, users=True) async def my_command(interaction: discord.Interaction) -> None: await interaction.response.send_message('I am installed in users by default!')
- @discord.app_commands.default_permissions(**perms)¶
A decorator that sets the default permissions needed to execute this command.
When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.
Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.
This is sent to Discord server side, and is not a
check()
. Therefore, error handlers are not called.Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Warning
This serves as a hint and members are not required to have the permissions given to actually execute this command. If you want to ensure that members have the permissions needed, consider using
has_permissions()
instead.- Parameters
**perms (
bool
) – Keyword arguments denoting the permissions to set as the default.
Example
@app_commands.command() @app_commands.default_permissions(manage_messages=True) async def test(interaction: discord.Interaction): await interaction.response.send_message('You may or may not have manage messages.')
Checks¶
- @discord.app_commands.check(predicate)¶
A decorator that adds a check to an application command.
These checks should be predicates that take in a single parameter taking a
Interaction
. If the check returns aFalse
-like value then during invocation aCheckFailure
exception is raised and sent to the appropriate error handlers.These checks can be either a coroutine or not.
Examples
Creating a basic check to see if the command invoker is you.
def check_if_it_is_me(interaction: discord.Interaction) -> bool: return interaction.user.id == 85309593344815104 @tree.command() @app_commands.check(check_if_it_is_me) async def only_for_me(interaction: discord.Interaction): await interaction.response.send_message('I know you!', ephemeral=True)
Transforming common checks into its own decorator:
def is_me(): def predicate(interaction: discord.Interaction) -> bool: return interaction.user.id == 85309593344815104 return app_commands.check(predicate) @tree.command() @is_me() async def only_me(interaction: discord.Interaction): await interaction.response.send_message('Only you!')
- Parameters
predicate (Callable[[
Interaction
],bool
]) – The predicate to check if the command should be invoked.
- @discord.app_commands.checks.has_role(item, /)¶
A
check()
that is added that checks if the member invoking the command has the role specified via the name or ID specified.If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
This check raises one of two special exceptions,
MissingRole
if the user is missing a role, orNoPrivateMessage
if it is used in a private message. Both inherit fromCheckFailure
.New in version 2.0.
Note
This is different from the permission system that Discord provides for application commands. This is done entirely locally in the program rather than being handled by Discord.
- @discord.app_commands.checks.has_any_role(*items)¶
A
check()
that is added that checks if the member invoking the command has any of the roles specified. This means that if they have one out of the three roles specified, then this check will returnTrue
.Similar to
has_role()
, the names or IDs passed in must be exact.This check raises one of two special exceptions,
MissingAnyRole
if the user is missing all roles, orNoPrivateMessage
if it is used in a private message. Both inherit fromCheckFailure
.New in version 2.0.
Note
This is different from the permission system that Discord provides for application commands. This is done entirely locally in the program rather than being handled by Discord.
- Parameters
items (List[Union[
str
,int
]]) – An argument list of names or IDs to check that the member has roles wise.
Example
@tree.command() @app_commands.checks.has_any_role('Library Devs', 'Moderators', 492212595072434186) async def cool(interaction: discord.Interaction): await interaction.response.send_message('You are cool indeed')
- @discord.app_commands.checks.has_permissions(**perms)¶
A
check()
that is added that checks if the member has all of the permissions necessary.Note that this check operates on the permissions given by
discord.Interaction.permissions
.The permissions passed in must be exactly like the properties shown under
discord.Permissions
.This check raises a special exception,
MissingPermissions
that is inherited fromCheckFailure
.New in version 2.0.
Note
This is different from the permission system that Discord provides for application commands. This is done entirely locally in the program rather than being handled by Discord.
- Parameters
**perms (
bool
) – Keyword arguments denoting the permissions to check for.
Example
@tree.command() @app_commands.checks.has_permissions(manage_messages=True) async def test(interaction: discord.Interaction): await interaction.response.send_message('You can manage messages.')
- @discord.app_commands.checks.bot_has_permissions(**perms)¶
Similar to
has_permissions()
except checks if the bot itself has the permissions listed. This relies ondiscord.Interaction.app_permissions
.This check raises a special exception,
BotMissingPermissions
that is inherited fromCheckFailure
.New in version 2.0.
- @discord.app_commands.checks.cooldown(rate, per, *, key=...)¶
A decorator that adds a cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the
key
function provided. If akey
is not provided then it defaults to a user-level cooldown. Thekey
function must take a single parameter, thediscord.Interaction
and return a value that is used as a key to the internal cooldown mapping.The
key
function can optionally be a coroutine.If a cooldown is triggered, then
CommandOnCooldown
is raised to the error handlers.Examples
Setting a one per 5 seconds per member cooldown on a command:
@tree.command() @app_commands.checks.cooldown(1, 5.0, key=lambda i: (i.guild_id, i.user.id)) async def test(interaction: discord.Interaction): await interaction.response.send_message('Hello') @test.error async def on_test_error(interaction: discord.Interaction, error: app_commands.AppCommandError): if isinstance(error, app_commands.CommandOnCooldown): await interaction.response.send_message(str(error), ephemeral=True)
- Parameters
rate (
int
) – The number of times a command can be used before triggering a cooldown.per (
float
) – The amount of seconds to wait for a cooldown when it’s been triggered.key (Optional[Callable[[
discord.Interaction
],collections.abc.Hashable
]]) – A function that returns a key to the mapping denoting the type of cooldown. Can optionally be a coroutine. If not given then defaults to a user-level cooldown. IfNone
is passed then it is interpreted as a “global” cooldown.
- @discord.app_commands.checks.dynamic_cooldown(factory, *, key=...)¶
A decorator that adds a dynamic cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the
key
function provided. If akey
is not provided then it defaults to a user-level cooldown. Thekey
function must take a single parameter, thediscord.Interaction
and return a value that is used as a key to the internal cooldown mapping.If a
factory
function is given, it must be a function that accepts a single parameter of typediscord.Interaction
and must return aCooldown
orNone
. IfNone
is returned then that cooldown is effectively bypassed.Both
key
andfactory
can optionally be coroutines.If a cooldown is triggered, then
CommandOnCooldown
is raised to the error handlers.Examples
Setting a cooldown for everyone but the owner.
def cooldown_for_everyone_but_me(interaction: discord.Interaction) -> Optional[app_commands.Cooldown]: if interaction.user.id == 80088516616269824: return None return app_commands.Cooldown(1, 10.0) @tree.command() @app_commands.checks.dynamic_cooldown(cooldown_for_everyone_but_me) async def test(interaction: discord.Interaction): await interaction.response.send_message('Hello') @test.error async def on_test_error(interaction: discord.Interaction, error: app_commands.AppCommandError): if isinstance(error, app_commands.CommandOnCooldown): await interaction.response.send_message(str(error), ephemeral=True)
- Parameters
factory (Optional[Callable[[
discord.Interaction
], Optional[Cooldown
]]]) – A function that takes an interaction and returns a cooldown that will apply to that interaction orNone
if the interaction should not have a cooldown.key (Optional[Callable[[
discord.Interaction
],collections.abc.Hashable
]]) – A function that returns a key to the mapping denoting the type of cooldown. Can optionally be a coroutine. If not given then defaults to a user-level cooldown. IfNone
is passed then it is interpreted as a “global” cooldown.
Cooldown¶
- defcopy
- defget_retry_after
- defget_tokens
- defreset
- defupdate_rate_limit
- class discord.app_commands.Cooldown(rate, per)¶
Represents a cooldown for a command.
New in version 2.0.
- get_tokens(current=None)¶
Returns the number of available tokens before rate limiting is applied.
- Parameters
current (Optional[
float
]) – The time in seconds since Unix epoch to calculate tokens at. If not supplied thentime.time()
is used.- Returns
The number of tokens available before the cooldown is to be applied.
- Return type
- get_retry_after(current=None)¶
Returns the time in seconds until the cooldown will be reset.
- Parameters
current (Optional[
float
]) – The current time in seconds since Unix epoch. If not supplied, thentime.time()
is used.- Returns
The number of seconds to wait before this cooldown will be reset.
- Return type
- update_rate_limit(current=None, *, tokens=1)¶
Updates the cooldown rate limit.
- Parameters
current (Optional[
float
]) – The time in seconds since Unix epoch to update the rate limit at. If not supplied, thentime.time()
is used.tokens (
int
) – The amount of tokens to deduct from the rate limit.
- Returns
The retry-after time in seconds if rate limited.
- Return type
Optional[
float
]
- reset()¶
Reset the cooldown to its initial state.
Namespace¶
- class discord.app_commands.Namespace¶
An object that holds the parameters being passed to a command in a mostly raw state.
This class is deliberately simple and just holds the option name and resolved value as a simple key-pair mapping. These attributes can be accessed using dot notation. For example, an option with the name of
example
can be accessed usingns.example
. If an attribute is not found, thenNone
is returned rather than an attribute error.Warning
The key names come from the raw Discord data, which means that if a parameter was renamed then the renamed key is used instead of the function parameter name.
New in version 2.0.
- x == y
Checks if two namespaces are equal by checking if all attributes are equal.
- x != y
Checks if two namespaces are not equal.
- x[key]
Returns an attribute if it is found, otherwise raises a
KeyError
.
- key in x
Checks if the attribute is in the namespace.
- iter(x)
Returns an iterator of
(name, value)
pairs. This allows it to be, for example, constructed as a dict or a list of pairs.
This namespace object converts resolved objects into their appropriate form depending on their type. Consult the table below for conversion information.
Option Type
Resolved Type
Note
In autocomplete interactions, the namespace might not be validated or filled in. Discord does not send the resolved data as well, so this means that certain fields end up just as IDs rather than the resolved data. In these cases, a
discord.Object
is returned instead.This is a Discord limitation.
Transformers¶
Transformer¶
- asyncautocomplete
- asynctransform
- class discord.app_commands.Transformer¶
The base class that allows a type annotation in an application command parameter to map into a
AppCommandOptionType
and transform the raw value into one from this type.This class is customisable through the overriding of methods and properties in the class and by using it as the second type parameter of the
Transform
class. For example, to convert a string into a custom pair type:class Point(typing.NamedTuple): x: int y: int class PointTransformer(app_commands.Transformer): async def transform(self, interaction: discord.Interaction, value: str) -> Point: (x, _, y) = value.partition(',') return Point(x=int(x.strip()), y=int(y.strip())) @app_commands.command() async def graph( interaction: discord.Interaction, point: app_commands.Transform[Point, PointTransformer], ): await interaction.response.send_message(str(point))
If a class is passed instead of an instance to the second type parameter, then it is constructed with no arguments passed to the
__init__
method.New in version 2.0.
- property type¶
The option type associated with this transformer.
This must be a
property
.Defaults to
string
.- Type
- property channel_types¶
A list of channel types that are allowed to this parameter.
Only valid if the
type()
returnschannel
.This must be a
property
.Defaults to an empty list.
- Type
List[
ChannelType
]
- property min_value¶
The minimum supported value for this parameter.
Only valid if the
type()
returnsnumber
integer
, orstring
.This must be a
property
.Defaults to
None
.- Type
Optional[
int
]
- property max_value¶
The maximum supported value for this parameter.
Only valid if the
type()
returnsnumber
integer
, orstring
.This must be a
property
.Defaults to
None
.- Type
Optional[
int
]
- property choices¶
A list of up to 25 choices that are allowed to this parameter.
Only valid if the
type()
returnsnumber
integer
, orstring
.This must be a
property
.Defaults to
None
.- Type
Optional[List[
Choice
]]
- await transform(interaction, value, /)¶
This function could be a coroutine.
Transforms the converted option value into another value.
The value passed into this transform function is the same as the one in the
conversion table
.- Parameters
interaction (
Interaction
) – The interaction being handled.value (Any) – The value of the given argument after being resolved. See the
conversion table
for how certain option types correspond to certain values.
- await autocomplete(interaction, value, /)¶
This function is a coroutine.
An autocomplete prompt handler to be automatically used by options using this transformer.
- Parameters
interaction (
Interaction
) – The autocomplete interaction being handled.value (Union[
str
,int
,float
]) – The current value entered by the user.
- Returns
A list of choices to be displayed to the user, a maximum of 25.
- Return type
List[
Choice
]
Transform¶
- class discord.app_commands.Transform¶
A type annotation that can be applied to a parameter to customise the behaviour of an option type by transforming with the given
Transformer
. This requires the usage of two generic parameters, the first one is the type you’re converting to and the second one is the type of theTransformer
actually doing the transformation.During type checking time this is equivalent to
typing.Annotated
so type checkers understand the intent of the code.For example usage, check
Transformer
.New in version 2.0.
Range¶
- class discord.app_commands.Range¶
A type annotation that can be applied to a parameter to require a numeric or string type to fit within the range provided.
During type checking time this is equivalent to
typing.Annotated
so type checkers understand the intent of the code.Some example ranges:
Range[int, 10]
means the minimum is 10 with no maximum.Range[int, None, 10]
means the maximum is 10 with no minimum.Range[int, 1, 10]
means the minimum is 1 and the maximum is 10.Range[float, 1.0, 5.0]
means the minimum is 1.0 and the maximum is 5.0.Range[str, 1, 10]
means the minimum length is 1 and the maximum length is 10.
New in version 2.0.
Examples
@app_commands.command() async def range(interaction: discord.Interaction, value: app_commands.Range[int, 10, 12]): await interaction.response.send_message(f'Your value is {value}', ephemeral=True)
Translations¶
Translator¶
- class discord.app_commands.Translator¶
A class that handles translations for commands, parameters, and choices.
Translations are done lazily in order to allow for async enabled translations as well as supporting a wide array of translation systems such as
gettext
and Project Fluent.In order for a translator to be used, it must be set using the
CommandTree.set_translator()
method. The translation flow for a string is as follows:- Use
locale_str
instead ofstr
in areas of a command you want to be translated. Currently, these are command names, command descriptions, parameter names, parameter descriptions, and choice names.
This can also be used inside the
describe()
decorator.
- Use
Call
CommandTree.set_translator()
to the translator instance that will handle the translations.Call
CommandTree.sync()
The library will call
Translator.translate()
on all the relevant strings being translated.
New in version 2.0.
- await load()¶
This function is a coroutine.
An asynchronous setup function for loading the translation system.
The default implementation does nothing.
This is invoked when
CommandTree.set_translator()
is called.
- await unload()¶
This function is a coroutine.
An asynchronous teardown function for unloading the translation system.
The default implementation does nothing.
This is invoked when
CommandTree.set_translator()
is called if a tree already has a translator or whendiscord.Client.close()
is called.
- await translate(string, locale, context)¶
This function is a coroutine.
Translates the given string to the specified locale.
If the string cannot be translated,
None
should be returned.The default implementation returns
None
.If an exception is raised in this method, it should inherit from
TranslationError
. If it doesn’t, then when this is called the exception will be chained with it instead.- Parameters
string (
locale_str
) – The string being translated.locale (
Locale
) – The locale being requested for translation.context (
TranslationContext
) – The translation context where the string originated from. For better type checking ergonomics, theTranslationContextTypes
type can be used instead to aid with type narrowing. It is functionally equivalent toTranslationContext
.
locale_str¶
- class discord.app_commands.locale_str(message, /, **kwargs)¶
Marks a string as ready for translation.
This is done lazily and is not actually translated until
CommandTree.sync()
is called.The sync method then ultimately defers the responsibility of translating to the
Translator
instance used by theCommandTree
. For more information on the translation flow, see theTranslator
documentation.- str(x)
Returns the message passed to the string.
- x == y
Checks if the string is equal to another string.
- x != y
Checks if the string is not equal to another string.
- hash(x)
Returns the hash of the string.
New in version 2.0.
- message¶
The message being translated. Once set, this cannot be changed.
Warning
This must be the default “message” that you send to Discord. Discord sends this message back to the library and the library uses it to access the data in order to dispatch commands.
For example, in a command name context, if the command name is
foo
then the message must also befoo
. For other translation systems that require a message ID such as Fluent, consider using a keyword argument to pass it in.- Type
TranslationContext¶
- class discord.app_commands.TranslationContext(location, data)¶
A class that provides context for the
locale_str
being translated.This is useful to determine where exactly the string is located and aid in looking up the actual translation.
- location¶
The location where this string is located.
- data¶
The extraneous data that is being translated.
- Type
Any
TranslationContextLocation¶
- class discord.app_commands.TranslationContextLocation¶
An enum representing the location context that the translation occurs in when requested for translation.
New in version 2.0.
- command_name¶
The translation involved a command name.
- command_description¶
The translation involved a command description.
- group_name¶
The translation involved a group name.
- group_description¶
The translation involved a group description.
- parameter_name¶
The translation involved a parameter name.
- parameter_description¶
The translation involved a parameter description.
- choice_name¶
The translation involved a choice name.
- other¶
The translation involved something else entirely. This is useful for running
Translator.translate()
for custom usage.
Exceptions¶
- exception discord.app_commands.AppCommandError¶
The base exception type for all application command related errors.
This inherits from
discord.DiscordException
.This exception and exceptions inherited from it are handled in a special way as they are caught and passed into various error handlers in this order:
New in version 2.0.
- exception discord.app_commands.CommandInvokeError(command, e)¶
An exception raised when the command being invoked raised an exception.
This inherits from
AppCommandError
.New in version 2.0.
- original¶
The original exception that was raised. You can also get this via the
__cause__
attribute.- Type
- command¶
The command that failed.
- Type
Union[
Command
,ContextMenu
]
- exception discord.app_commands.TransformerError(value, opt_type, transformer)¶
An exception raised when a
Transformer
or type annotation fails to convert to its target type.This inherits from
AppCommandError
.If an exception occurs while converting that does not subclass
AppCommandError
then the exception is wrapped into this exception. The original exception can be retrieved using the__cause__
attribute. Otherwise if the exception derives fromAppCommandError
then it will be propagated as-is.New in version 2.0.
- value¶
The value that failed to convert.
- Type
Any
- type¶
The type of argument that failed to convert.
- Type
- transformer¶
The transformer that failed the conversion.
- Type
- exception discord.app_commands.TranslationError(*msg, string=None, locale=None, context)¶
An exception raised when the library fails to translate a string.
This inherits from
AppCommandError
.If an exception occurs while calling
Translator.translate()
that does not subclass this then the exception is wrapped into this exception. The original exception can be retrieved using the__cause__
attribute. Otherwise it will be propagated as-is.New in version 2.0.
- string¶
The string that caused the error, if any.
- Type
Optional[Union[
str
,locale_str
]]
- context¶
The context of the translation that triggered the error.
- Type
- exception discord.app_commands.CheckFailure¶
An exception raised when check predicates in a command have failed.
This inherits from
AppCommandError
.New in version 2.0.
- exception discord.app_commands.NoPrivateMessage(message=None)¶
An exception raised when a command does not work in a direct message.
This inherits from
CheckFailure
.New in version 2.0.
- exception discord.app_commands.MissingRole(missing_role)¶
An exception raised when the command invoker lacks a role to run a command.
This inherits from
CheckFailure
.New in version 2.0.
- missing_role¶
The required role that is missing. This is the parameter passed to
has_role()
.
- exception discord.app_commands.MissingAnyRole(missing_roles)¶
An exception raised when the command invoker lacks any of the roles specified to run a command.
This inherits from
CheckFailure
.New in version 2.0.
- missing_roles¶
The roles that the invoker is missing. These are the parameters passed to
has_any_role()
.
- exception discord.app_commands.MissingPermissions(missing_permissions, *args)¶
An exception raised when the command invoker lacks permissions to run a command.
This inherits from
CheckFailure
.New in version 2.0.
- exception discord.app_commands.BotMissingPermissions(missing_permissions, *args)¶
An exception raised when the bot’s member lacks permissions to run a command.
This inherits from
CheckFailure
.New in version 2.0.
- exception discord.app_commands.CommandOnCooldown(cooldown, retry_after)¶
An exception raised when the command being invoked is on cooldown.
This inherits from
CheckFailure
.New in version 2.0.
- exception discord.app_commands.CommandLimitReached(guild_id, limit, type=<AppCommandType.chat_input: 1>)¶
An exception raised when the maximum number of application commands was reached either globally or in a guild.
This inherits from
AppCommandError
.New in version 2.0.
- type¶
The type of command that reached the limit.
- Type
- exception discord.app_commands.CommandAlreadyRegistered(name, guild_id)¶
An exception raised when a command is already registered.
This inherits from
AppCommandError
.New in version 2.0.
- exception discord.app_commands.CommandSignatureMismatch(command)¶
An exception raised when an application command from Discord has a different signature from the one provided in the code. This happens because your command definition differs from the command definition you provided Discord. Either your code is out of date or the data from Discord is out of sync.
This inherits from
AppCommandError
.New in version 2.0.
- command¶
The command that had the signature mismatch.
- Type
Union[
Command
,ContextMenu
,Group
]
- exception discord.app_commands.CommandNotFound(name, parents, type=<AppCommandType.chat_input: 1>)¶
An exception raised when an application command could not be found.
This inherits from
AppCommandError
.New in version 2.0.
- parents¶
A list of parent command names that were previously found prior to the application command not being found.
- Type
List[
str
]
- type¶
The type of command that was not found.
- Type
- exception discord.app_commands.MissingApplicationID(message=None)¶
An exception raised when the client does not have an application ID set. An application ID is required for syncing application commands.
This inherits from
AppCommandError
.New in version 2.0.
- exception discord.app_commands.CommandSyncFailure(child, commands)¶
An exception raised when
CommandTree.sync()
failed.This provides syncing failures in a slightly more readable format.
This inherits from
AppCommandError
andHTTPException
.New in version 2.0.