The following section outlines the API of discord.py’s command extension module.
Bots¶ Bot¶Represents a Discord bot.
This class is a subclass of discord.Client
and as a result anything that you can do with a discord.Client
you can do with this bot.
This class also subclasses GroupMixin
to provide the functionality to manage commands.
Unlike discord.Client
, this class does not require manually setting a CommandTree
and is automatically set upon instantiating the class.
Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message
as its second parameter and returns the prefix. This is to facilitate “dynamic” command prefixes. This callable can be either a regular function or a coroutine.
An empty string as the prefix always matches, enabling prefix-less command invocation. While this may be useful in DMs it should be avoided in servers, as it’s likely to cause performance issues and unintended command invocations.
The command prefix could also be an iterable of strings indicating that multiple checks for the prefix should be used and the first one to match will be the invocation prefix. You can get this prefix via Context.prefix
.
Note
When passing multiple prefixes be careful to not pass a prefix that matches a longer prefix occurring later in the sequence. For example, if the command prefix is ('!', '!?')
the '!?'
prefix will never be matched to any message as the previous one matches messages starting with !?
. This is especially important when passing an empty string, it should always be last as no prefix after it will be matched.
Whether the commands should be case insensitive. Defaults to False
. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well.
The content prefixed into the default help message.
The help command implementation to use. This can be dynamically set at runtime. To remove the help command pass None
. For more information on implementing a help command, see Help Commands.
Optional[HelpCommand
]
The user ID that owns the bot. If this is not set and is then queried via is_owner()
then it is fetched automatically using application_info()
.
Optional[int
]
The user IDs that owns the bot. This is similar to owner_id
. If this is not set and the application is team based, then it is fetched automatically using application_info()
. For performance reasons it is recommended to use a set
for the collection. You cannot set both owner_id
and owner_ids
.
New in version 1.3.
Optional[Collection[int
]]
Whether to strip whitespace characters after encountering the command prefix. This allows for ! hello
and !hello
to both work if the command_prefix
is set to !
. Defaults to False
.
New in version 1.7.
The type of application command tree to use. Defaults to CommandTree
.
New in version 2.0.
Type[CommandTree
]
The default allowed contexts that applies to all application commands in the application command tree.
Note that you can override this on a per command basis.
New in version 2.4.
The default allowed install locations that apply to all application commands in the application command tree.
Note that you can override this on a per command basis.
New in version 2.4.
A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a Context
.
Note
Similar to before_invoke()
, this is not called unless checks and argument parsing procedures succeed. This hook is, however, always called regardless of the internal command callback raising an error (i.e. CommandInvokeError
). This makes it ideal for clean-up scenarios.
Changed in version 2.0: coro
parameter is now positional-only.
A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a Context
.
Note
The before_invoke()
and after_invoke()
hooks are only called if all checks and argument parsing procedures pass without error. If any check or argument parsing procedures fail then the hooks are not called.
Changed in version 2.0: coro
parameter is now positional-only.
A decorator that adds a global check to the bot.
A global check is similar to a check()
that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.
Note
This function can either be a regular function or a coroutine.
Similar to a command check()
, this takes a single parameter of type Context
and can only raise exceptions inherited from CommandError
.
Example
@bot.check def check_commands(ctx): return ctx.command.qualified_name in allowed_commands
Changed in version 2.0: func
parameter is now positional-only.
A decorator that adds a “call once” global check to the bot.
Unlike regular global checks, this one is called only once per invoke()
call.
Regular global checks are called whenever a command is called or Command.can_run()
is called. This type of check bypasses that and ensures that it’s called only once, even inside the default help command.
Note
When using this function the Context
sent to a group subcommand may only parse the parent command and not the subcommands due to it being invoked once per Bot.invoke()
call.
Note
This function can either be a regular function or a coroutine.
Similar to a command check()
, this takes a single parameter of type Context
and can only raise exceptions inherited from CommandError
.
Example
@bot.check_once def whitelist(ctx): return ctx.message.author.id in my_whitelist
Changed in version 2.0: func
parameter is now positional-only.
A shortcut decorator that invokes command()
and adds it to the internal command list via add_command()
.
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
Callable[…, Command
]
A decorator that registers an event to listen to.
You can find more info about the events on the documentation below.
The events must be a coroutine, if not, TypeError
is raised.
Example
@client.event async def on_ready(): print('Ready!')
Changed in version 2.0: coro
parameter is now positional-only.
TypeError – The coroutine passed is not actually a coroutine.
A shortcut decorator that invokes group()
and adds it to the internal command list via add_command()
.
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
Callable[…, Group
]
A shortcut decorator that invokes hybrid_command()
and adds it to the internal command list via add_command()
.
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
Callable[…, HybridCommand
]
A shortcut decorator that invokes hybrid_group()
and adds it to the internal command list via add_command()
.
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
Callable[…, HybridGroup
]
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as on_ready()
The functions being listened to must be a coroutine.
Example
@bot.listen() async def on_message(message): print('one') # in some other file... @bot.listen('on_message') async def my_message(message): print('two')
Would print one and two in an unspecified order.
TypeError – The function being listened to is not a coroutine.
The activity being used upon logging in.
Optional[BaseActivity
]
Adds a global check to the bot.
This is the non-decorator interface to check()
and check_once()
.
Changed in version 2.0: func
parameter is now positional-only.
This function is a coroutine.
Adds a “cog” to the bot.
A cog is a class that has its own event listeners and commands.
If the cog is a app_commands.Group
then it is added to the bot’s CommandTree
as well.
Note
Exceptions raised inside a Cog
’s cog_load()
method will be propagated to the caller.
Changed in version 2.0: ClientException
is raised when a cog with the same name is already loaded.
Changed in version 2.0: cog
parameter is now positional-only.
Changed in version 2.0: This method is now a coroutine.
cog (Cog
) – The cog to register to the bot.
override (bool
) –
If a previously loaded cog with the same name should be ejected instead of raising an error.
New in version 2.0.
guild (Optional[Snowflake
]) –
If the cog is an application command group, then this would be the guild where the cog group would be added to. If not given then it becomes a global command instead.
New in version 2.0.
guilds (List[Snowflake
]) –
If the cog is an application command group, then this would be the guilds where the cog group would be added to. If not given then it becomes a global command instead. Cannot be mixed with guild
.
New in version 2.0.
CommandError – An error happened during loading.
ClientException – A cog with the same name is already loaded.
Adds a Command
into the internal list of commands.
This is usually not called, instead the command()
or group()
shortcut decorators are used instead.
Changed in version 1.4: Raise CommandRegistrationError
instead of generic ClientException
Changed in version 2.0: command
parameter is now positional-only.
command (Command
) – The command to add.
CommandRegistrationError – If the command or its alias is already registered by different command.
TypeError – If the command passed is not a subclass of Command
.
Registers DynamicItem
classes for persistent listening.
This method accepts class types rather than instances.
New in version 2.4.
*items (Type[DynamicItem
]) – The classes of dynamic items to add.
TypeError – A class is not a subclass of DynamicItem
.
The non decorator alternative to listen()
.
Changed in version 2.0: func
parameter is now positional-only.
Example
async def on_ready(): pass async def my_message(message): pass bot.add_listener(on_ready) bot.add_listener(my_message, 'on_message')
Registers a View
for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
view (Union[discord.ui.View
, discord.ui.LayoutView
]) – The view to register for dispatching.
message_id (Optional[int
]) – The message ID that the view is attached to. This is currently used to refresh the view’s state during message update events. If not given then message update events are not propagated for the view.
TypeError – A view was not passed.
ValueError – The view is not persistent or is already finished. A persistent view has no timeout and all their components have an explicitly provided custom_id.
The allowed mention configuration.
New in version 1.4.
Optional[AllowedMentions
]
The client’s application info.
This is retrieved on login()
and is not updated afterwards. This allows populating the application_id without requiring a gateway connection.
This is None
if accessed before login()
is called.
New in version 2.0.
Optional[AppInfo
]
The client’s application flags.
New in version 2.0.
The client’s application ID.
If this is not passed via __init__
then this is retrieved through the gateway when an event contains the data or after a call to login()
. Usually after on_connect()
is called.
New in version 2.0.
Optional[int
]
This function is a coroutine.
Retrieves the bot’s application information.
HTTPException – Retrieving the information failed somehow.
The bot’s application information.
This function is a coroutine.
A hook that is called before IDENTIFYing a session. This is useful if you wish to have more control over the synchronization of multiple IDENTIFYing clients.
The default implementation sleeps for 5 seconds.
New in version 1.4.
Read-only list of messages the connected client has cached.
New in version 1.1.
Sequence[Message
]
This function is a coroutine.
Changes the client’s presence.
Example
game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game)
Changed in version 2.0: Removed the afk
keyword-only parameter.
Changed in version 2.0: This function will now raise TypeError
instead of InvalidArgument
.
activity (Optional[BaseActivity
]) – The activity being done. None
if no currently active activity is done.
status (Optional[Status
]) – Indicates what status to change to. If None
, then Status.online
is used.
TypeError – If the activity
parameter is not the proper type.
Clears the internal state of the bot.
After this, the bot can be considered “re-opened”, i.e. is_closed()
and is_ready()
both return False
along with the bot’s internal cache cleared.
This function is a coroutine.
Closes the connection to Discord.
A unique set of commands without aliases that are registered.
Set[Command
]
This function is a coroutine.
Creates a websocket connection and lets the websocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated.
reconnect (bool
) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).
GatewayNotFound – If the gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage.
ConnectionClosed – The websocket connection has been terminated.
This function is a coroutine.
Create an emoji for the current application.
New in version 2.5.
name (str
) – The emoji name. Must be between 2 and 32 characters long.
image (bytes
) – The bytes-like object representing the image data to use. Only JPG, PNG and GIF images are supported.
MissingApplicationID – The application ID could not be found.
HTTPException – Creating the emoji failed.
The emoji that was created.
This function is a coroutine.
Creates a DMChannel
with this user.
This should be rarely called, as this is done transparently for most people.
New in version 2.0.
This function is a coroutine.
Creates a test Entitlement
for the application.
New in version 2.4.
sku (Snowflake
) – The SKU to create the entitlement for.
owner (Snowflake
) – The ID of the owner.
owner_type (EntitlementOwnerType
) – The type of the owner.
MissingApplicationID – The application ID could not be found.
NotFound – The SKU or owner could not be found.
HTTPException – Creating the entitlement failed.
This function is a coroutine.
Creates a Guild
.
Bot accounts in more than 10 guilds are not allowed to create guilds.
Changed in version 2.0: name
and icon
parameters are now keyword-only. The region
parameter has been removed.
Changed in version 2.0: This function will now raise ValueError
instead of InvalidArgument
.
Deprecated since version 2.6: This function is deprecated and will be removed in a future version.
name (str
) – The name of the guild.
icon (Optional[bytes
]) – The bytes-like object representing the icon. See ClientUser.edit()
for more details on what is expected.
code (str
) –
The code for a template to create the guild with.
New in version 1.4.
HTTPException – Guild creation failed.
ValueError – Invalid icon image format given. Must be PNG or JPG.
The guild created. This is not the same guild that is added to cache.
This function is a coroutine.
Revokes an Invite
, URL, or ID to an invite.
You must have manage_channels
in the associated guild to do this.
Changed in version 2.0: invite
parameter is now positional-only.
Forbidden – You do not have permissions to revoke invites.
NotFound – The invite is invalid or expired.
HTTPException – Revoking the invite failed.
The emojis that the connected client has.
Sequence[Emoji
]
Retrieves an asynchronous iterator of the Entitlement
that applications has.
New in version 2.4.
Examples
Usage
async for entitlement in client.entitlements(limit=100): print(entitlement.user_id, entitlement.ends_at)
Flattening into a list
entitlements = [entitlement async for entitlement in client.entitlements(limit=100)] # entitlements is now a list of Entitlement...
All parameters are optional.
limit (Optional[int
]) – The number of entitlements to retrieve. If None
, it retrieves every entitlement for this application. Note, however, that this would make it a slow operation. Defaults to 100
.
before (Optional[Union[Snowflake
, datetime.datetime
]]) – Retrieve entitlements before this date or entitlement. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
after (Optional[Union[Snowflake
, datetime.datetime
]]) – Retrieve entitlements after this date or entitlement. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
skus (Optional[Sequence[Snowflake
]]) – A list of SKUs to filter by.
user (Optional[Snowflake
]) – The user to filter by.
guild (Optional[Snowflake
]) – The guild to filter by.
exclude_ended (bool
) – Whether to exclude ended entitlements. Defaults to False
.
exclude_deleted (bool
) –
Whether to exclude deleted entitlements. Defaults to True
.
New in version 2.5.
MissingApplicationID – The application ID could not be found.
HTTPException – Fetching the entitlements failed.
TypeError – Both after
and before
were provided, as Discord does not support this type of pagination.
Entitlement
– The entitlement with the application.
A read-only mapping of extension name to extension.
Mapping[str
, types.ModuleType
]
This function is a coroutine.
Retrieves an emoji for the current application.
New in version 2.5.
emoji_id (int
) – The emoji ID to retrieve.
MissingApplicationID – The application ID could not be found.
HTTPException – Retrieving the emoji failed.
The emoji requested.
This function is a coroutine.
Retrieves all emojis for the current application.
New in version 2.5.
MissingApplicationID – The application ID could not be found.
HTTPException – Retrieving the emojis failed.
The list of emojis for the current application.
List[Emoji
]
This function is a coroutine.
Retrieves a abc.GuildChannel
, abc.PrivateChannel
, or Thread
with the specified ID.
Note
This method is an API call. For general usage, consider get_channel()
instead.
New in version 1.2.
Changed in version 2.0: channel_id
parameter is now positional-only.
InvalidData – An unknown channel type was received from Discord.
HTTPException – Retrieving the channel failed.
NotFound – Invalid Channel ID.
Forbidden – You do not have permission to fetch this channel.
The channel from the ID.
Union[abc.GuildChannel
, abc.PrivateChannel
, Thread
]
This function is a coroutine.
Retrieves a Entitlement
with the specified ID.
New in version 2.4.
entitlement_id (int
) – The entitlement’s ID to fetch from.
NotFound – An entitlement with this ID does not exist.
MissingApplicationID – The application ID could not be found.
HTTPException – Fetching the entitlement failed.
The entitlement you requested.
This function is a coroutine.
Retrieves a Guild
from an ID.
Note
This method is an API call. For general usage, consider get_guild()
instead.
Changed in version 2.0: guild_id
parameter is now positional-only.
guild_id (int
) – The guild’s ID to fetch from.
with_counts (bool
) –
Whether to include count information in the guild. This fills the Guild.approximate_member_count
and Guild.approximate_presence_count
attributes without needing any privileged intents. Defaults to True
.
New in version 2.0.
NotFound – The guild doesn’t exist or you got no access to it.
HTTPException – Getting the guild failed.
The guild from the ID.
This function is a coroutine.
Retrieves a preview of a Guild
from an ID. If the guild is discoverable, you don’t have to be a member of it.
New in version 2.5.
NotFound – The guild doesn’t exist, or is not discoverable and you are not in it.
HTTPException – Getting the guild failed.
The guild preview from the ID.
Retrieves an asynchronous iterator that enables receiving your guilds.
Note
This method is an API call. For general usage, consider guilds
instead.
Examples
Usage
async for guild in client.fetch_guilds(limit=150): print(guild.name)
Flattening into a list
guilds = [guild async for guild in client.fetch_guilds(limit=150)] # guilds is now a list of Guild...
All parameters are optional.
limit (Optional[int
]) –
The number of guilds to retrieve. If None
, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to 200
.
Changed in version 2.0: The default has been changed to 200.
before (Union[abc.Snowflake
, datetime.datetime
]) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
after (Union[abc.Snowflake
, datetime.datetime
]) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
with_counts (bool
) –
Whether to include count information in the guilds. This fills the Guild.approximate_member_count
and Guild.approximate_presence_count
attributes without needing any privileged intents. Defaults to True
.
New in version 2.3.
HTTPException – Getting the guilds failed.
Guild
– The guild with the guild data parsed.
This function is a coroutine.
Gets an Invite
from a discord.gg URL or ID.
url (Union[Invite
, str
]) – The Discord invite ID or URL (must be a discord.gg URL).
with_counts (bool
) – Whether to include count information in the invite. This fills the Invite.approximate_member_count
and Invite.approximate_presence_count
fields.
with_expiration (bool
) –
Whether to include the expiration date of the invite. This fills the Invite.expires_at
field.
New in version 2.0.
Deprecated since version 2.6: This parameter is deprecated and will be removed in a future version as it is no longer needed to fill the Invite.expires_at
field.
scheduled_event_id (Optional[int
]) –
The ID of the scheduled event this invite is for.
Note
It is not possible to provide a url that contains an event_id
parameter when using this parameter.
New in version 2.0.
ValueError – The url contains an event_id
, but scheduled_event_id
has also been provided.
NotFound – The invite has expired or is invalid.
HTTPException – Getting the invite failed.
The invite from the URL/ID.
This function is a coroutine.
Retrieves a premium sticker pack with the specified ID.
New in version 2.5.
sticker_pack_id (int
) – The sticker pack’s ID to fetch from.
NotFound – A sticker pack with this ID does not exist.
HTTPException – Retrieving the sticker pack failed.
The retrieved premium sticker pack.
This function is a coroutine.
Retrieves all available premium sticker packs.
New in version 2.0.
HTTPException – Retrieving the sticker packs failed.
All available premium sticker packs.
List[StickerPack
]
This function is a coroutine.
Retrieves the bot’s available SKUs.
New in version 2.4.
MissingApplicationID – The application ID could not be found.
HTTPException – Retrieving the SKUs failed.
The bot’s available SKUs.
List[SKU
]
This function is a coroutine.
Retrieves all default soundboard sounds.
New in version 2.5.
HTTPException – Retrieving the default soundboard sounds failed.
All default soundboard sounds.
List[SoundboardDefaultSound
]
This function is a coroutine.
Gets a StageInstance
for a stage channel id.
New in version 2.0.
channel_id (int
) – The stage channel ID.
NotFound – The stage instance or channel could not be found.
HTTPException – Getting the stage instance failed.
The stage instance from the stage channel ID.
This function is a coroutine.
Retrieves a Sticker
with the specified ID.
New in version 2.0.
HTTPException – Retrieving the sticker failed.
NotFound – Invalid sticker ID.
The sticker you requested.
Union[StandardSticker
, GuildSticker
]
This function is a coroutine.
Gets a Template
from a discord.new URL or code.
code (Union[Template
, str
]) – The Discord Template Code or URL (must be a discord.new URL).
NotFound – The template is invalid.
HTTPException – Getting the template failed.
The template from the URL/code.
This function is a coroutine.
Retrieves a User
based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Changed in version 2.0: user_id
parameter is now positional-only.
user_id (int
) – The user’s ID to fetch from.
NotFound – A user with this ID does not exist.
HTTPException – Fetching the user failed.
The user you requested.
This function is a coroutine.
Retrieves a Webhook
with the specified ID.
Changed in version 2.0: webhook_id
parameter is now positional-only.
HTTPException – Retrieving the webhook failed.
NotFound – Invalid webhook ID.
Forbidden – You do not have permission to fetch this webhook.
The webhook you requested.
This function is a coroutine.
Gets a Widget
from a guild ID.
Note
The guild must have the widget enabled to get this information.
Changed in version 2.0: guild_id
parameter is now positional-only.
guild_id (int
) – The ID of the guild.
Forbidden – The widget for this guild is disabled.
HTTPException – Retrieving the widget failed.
The guild’s widget.
A generator that retrieves every abc.GuildChannel
the client can ‘access’.
This is equivalent to:
for guild in client.guilds: for channel in guild.channels: yield channel
abc.GuildChannel
– A channel the client can ‘access’.
Returns a generator with every Member
the client can see.
This is equivalent to:
for guild in client.guilds: for member in guild.members: yield member
Member
– A member the client can see.
Returns a channel or thread with the given ID.
Changed in version 2.0: id
parameter is now positional-only.
id (int
) – The ID to search for.
The returned channel or None
if not found.
Optional[Union[abc.GuildChannel
, Thread
, abc.PrivateChannel
]]
Gets the cog instance requested.
If the cog is not found, None
is returned instead.
Changed in version 2.0: name
parameter is now positional-only.
Get a Command
from the internal list of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. 'foo bar'
) will get the subcommand bar
of the group command foo
. If a subcommand is not found then None
is returned just as usual.
Changed in version 2.0: name
parameter is now positional-only.
This function is a coroutine.
Returns the invocation context from the message or interaction.
This is a more low-level counter-part for process_commands()
to allow users more fine grained control over the processing.
The returned context is not guaranteed to be a valid invocation context, Context.valid
must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under invoke()
.
Note
In order for the custom context to be used inside an interaction-based context (such as HybridCommand
) then this method must be overridden to return that class.
Changed in version 2.0: message
parameter is now positional-only and renamed to origin
.
origin (Union[discord.Message
, discord.Interaction
]) – The message or interaction to get the invocation context from.
cls – The factory class that will be used to create the context. By default, this is Context
. Should a custom class be provided, it must be similar enough to Context
's interface.
The invocation context. The type of this can change via the cls
parameter.
Returns an emoji with the given ID.
Changed in version 2.0: id
parameter is now positional-only.
Returns a guild with the given ID.
Changed in version 2.0: id
parameter is now positional-only.
Returns a partial messageable with the given channel ID.
This is useful if you have a channel_id but don’t want to do an API call to send messages to it.
New in version 2.0.
id (int
) – The channel ID to create a partial messageable for.
guild_id (Optional[int
]) –
The optional guild ID to create a partial messageable for.
This is not required to actually send messages, but it does allow the jump_url()
and guild
properties to function properly.
type (Optional[ChannelType
]) – The underlying channel type for the partial messageable.
The partial messageable
This function is a coroutine.
Retrieves the prefix the bot is listening to with the message as a context.
Changed in version 2.0: message
parameter is now positional-only.
message (discord.Message
) – The message context to get the prefix of.
A list of prefixes or a single prefix that the bot is listening for.
Returns a soundboard sound with the given ID.
New in version 2.5.
id (int
) – The ID to search for.
The soundboard sound or None
if not found.
Optional[SoundboardSound
]
Returns a stage instance with the given stage channel ID.
New in version 2.0.
id (int
) – The ID to search for.
The stage instance or None
if not found.
Optional[StageInstance
]
Returns a guild sticker with the given ID.
New in version 2.0.
The sticker or None
if not found.
Optional[GuildSticker
]
Returns a user with the given ID.
Changed in version 2.0: id
parameter is now positional-only.
The guilds that the connected client is a member of.
Sequence[Guild
]
The intents configured for this connection.
New in version 1.5.
This function is a coroutine.
Invokes the command given under the invocation context and handles all the internal event dispatch mechanisms.
Changed in version 2.0: ctx
parameter is now positional-only.
ctx (Context
) – The invocation context to invoke.
bool
: Indicates if the websocket connection is closed.
This function is a coroutine.
Checks if a User
or Member
is the owner of this bot.
If an owner_id
is not set, it is fetched automatically through the use of application_info()
.
Changed in version 1.3: The function also checks if the application is team-owned if owner_ids
is not set.
Changed in version 2.0: user
parameter is now positional-only.
Changed in version 2.4: This function now respects the team member roles if the bot is team-owned. In order to be considered an owner, they must be either an admin or a developer.
bool
: Specifies if the client’s internal cache is ready for use.
bool
: Whether the websocket is currently rate limited.
This can be useful to know when deciding whether you should query members using HTTP or via the gateway.
New in version 1.6.
Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
This function is a coroutine.
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, setup
defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the bot
.
Changed in version 2.0: This method is now a coroutine.
name (str
) – The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test
if you want to import foo/test.py
.
package (Optional[str
]) –
The package name to resolve relative imports with. This is required when loading an extension using a relative path, e.g .foo.test
. Defaults to None
.
New in version 1.7.
ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package
parameter.
ExtensionAlreadyLoaded – The extension is already loaded.
NoEntryPointError – The extension does not have a setup function.
ExtensionFailed – The extension or its setup function had an execution error.
This function is a coroutine.
Logs in the client with the specified credentials and calls the setup_hook()
.
token (str
) – The authentication token. Do not prefix this token with anything as the library will do it for you.
LoginFailure – The wrong credentials are passed.
HTTPException – An unknown HTTP related error occurred, usually when it isn’t 200 or the known incorrect credentials passing status code.
This function is a coroutine.
The default command error handler provided by the bot.
By default this logs to the library logger, however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
Changed in version 2.0: context
and exception
parameters are now positional-only. Instead of writing to sys.stderr
this now uses the library logger.
This function is a coroutine.
The default error handler provided by the client.
By default this logs to the library logger however it could be overridden to have a different implementation. Check on_error()
for more details.
Changed in version 2.0: event_method
parameter is now positional-only and instead of writing to sys.stderr
it logs instead.
A sequence of persistent views added to the client.
New in version 2.0.
Sequence[Union[View
, LayoutView
]]
The private channels that the connected client is participating on.
Note
This returns only up to 128 most recent private channels due to an internal working on how Discord deals with private channels.
Sequence[abc.PrivateChannel
]
This function is a coroutine.
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the on_message()
event. If you choose to override the on_message()
event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to get_context()
followed by a call to invoke()
.
This also checks if the message’s author is a bot and doesn’t call get_context()
or invoke()
if so.
Changed in version 2.0: message
parameter is now positional-only.
message (discord.Message
) – The message to process commands for.
This function is a coroutine.
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a unload_extension()
followed by a load_extension()
except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
name (str
) – The extension name to reload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test
if you want to import foo/test.py
.
package (Optional[str
]) –
The package name to resolve relative imports with. This is required when reloading an extension using a relative path, e.g .foo.test
. Defaults to None
.
New in version 1.7.
ExtensionNotLoaded – The extension was not loaded.
ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package
parameter.
NoEntryPointError – The extension does not have a setup function.
ExtensionFailed – The extension setup function had an execution error.
Removes a global check from the bot.
This function is idempotent and will not raise an exception if the function is not in the global checks.
Changed in version 2.0: func
parameter is now positional-only.
func – The function to remove from the global checks.
call_once (bool
) – If the function was added with call_once=True
in the Bot.add_check()
call or using check_once()
.
This function is a coroutine.
Removes a cog from the bot and returns it.
All registered commands and event listeners that the cog has registered will be removed as well.
If no cog is found then this method has no effect.
Changed in version 2.0: name
parameter is now positional-only.
Changed in version 2.0: This method is now a coroutine.
name (str
) – The name of the cog to remove.
guild (Optional[Snowflake
]) –
If the cog is an application command group, then this would be the guild where the cog group would be removed from. If not given then a global command is removed instead instead.
New in version 2.0.
guilds (List[Snowflake
]) –
If the cog is an application command group, then this would be the guilds where the cog group would be removed from. If not given then a global command is removed instead instead. Cannot be mixed with guild
.
New in version 2.0.
The cog that was removed. None
if not found.
Optional[Cog
]
Remove a Command
from the internal list of commands.
This could also be used as a way to remove aliases.
Changed in version 2.0: name
parameter is now positional-only.
Removes DynamicItem
classes from persistent listening.
This method accepts class types rather than instances.
New in version 2.4.
*items (Type[DynamicItem
]) – The classes of dynamic items to remove.
TypeError – A class is not a subclass of DynamicItem
.
Removes a listener from the pool of listeners.
Changed in version 2.0: func
parameter is now positional-only.
func – The function that was used as a listener to remove.
name (str
) – The name of the event we want to remove. Defaults to func.__name__
.
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use start()
coroutine or connect()
+ login()
.
This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing None
to the log_handler
parameter.
Warning
This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
token (str
) – The authentication token. Do not prefix this token with anything as the library will do it for you.
reconnect (bool
) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).
log_handler (Optional[logging.Handler
]) –
The log handler to use for the library’s logger. If this is None
then the library will not set up anything logging related. Logging will still work if None
is passed, though it is your responsibility to set it up.
The default log handler if not provided is logging.StreamHandler
.
New in version 2.0.
log_formatter (logging.Formatter
) –
The formatter to use with the given log handler. If not provided then it defaults to a colour based logging formatter (if available).
New in version 2.0.
log_level (int
) –
The default log level for the library’s logger. This is only applied if the log_handler
parameter is not None
. Defaults to logging.INFO
.
New in version 2.0.
root_logger (bool
) –
Whether to set up the root logger rather than the library logger. By default, only the library logger ('discord'
) is set up. If this is set to True
then the root logger is set up as well.
Defaults to False
.
New in version 2.0.
This function is a coroutine.
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in login()
, and will be called before any events are dispatched, making it a better solution than doing such setup in the on_ready()
event.
Warning
Since this is called before the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like wait_for()
and wait_until_ready()
.
New in version 2.0.
The soundboard sounds that the connected client has.
New in version 2.5.
List[SoundboardSound
]
This function is a coroutine.
A shorthand coroutine for login()
+ connect()
.
token (str
) – The authentication token. Do not prefix this token with anything as the library will do it for you.
reconnect (bool
) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).
TypeError – An unexpected keyword argument was received.
Status
: The status being used upon logging on to Discord.
The stickers that the connected client has.
New in version 2.0.
Sequence[GuildSticker
]
The command tree responsible for handling the application commands in this bot.
New in version 2.0.
This function is a coroutine.
Unloads an extension.
When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported.
The extension can provide an optional global function, teardown
, to do miscellaneous clean-up if necessary. This function takes a single parameter, the bot
, similar to setup
from load_extension()
.
Changed in version 2.0: This method is now a coroutine.
name (str
) – The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test
if you want to import foo/test.py
.
package (Optional[str
]) –
The package name to resolve relative imports with. This is required when unloading an extension using a relative path, e.g .foo.test
. Defaults to None
.
New in version 1.7.
ExtensionNotFound – The name of the extension could not be resolved using the provided package
parameter.
ExtensionNotLoaded – The extension was not loaded.
Represents the connected client. None
if not logged in.
Optional[ClientUser
]
Returns a list of all the users the bot can see.
List[User
]
Represents a list of voice connections.
These are usually VoiceClient
instances.
List[VoiceProtocol
]
This function is a coroutine.
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The timeout
parameter is passed onto asyncio.wait_for()
. By default, it does not timeout. Note that this does propagate the asyncio.TimeoutError
for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a tuple
containing those arguments is returned instead. Please check the documentation for a list of events and their parameters.
This function returns the first event that meets the requirements.
Examples
Waiting for a user reply:
@client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send(f'Hello {msg.author}!')
Waiting for a thumbs up reaction from the message author:
@client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that 👍 reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '👍' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('👎') else: await channel.send('👍')
Changed in version 2.0: event
parameter is now positional-only.
event (str
) – The event name, similar to the event reference, but without the on_
prefix, to wait for.
check (Optional[Callable[…, bool
]]) – A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for.
timeout (Optional[float
]) – The number of seconds to wait before timing out and raising asyncio.TimeoutError
.
asyncio.TimeoutError – If a timeout is provided and it was reached.
Returns no arguments, a single argument, or a tuple
of multiple arguments that mirrors the parameters passed in the event reference.
Any
This function is a coroutine.
Waits until the client’s internal cache is all ready.
Warning
Calling this inside setup_hook()
can lead to a deadlock.
This is similar to Bot
except that it is inherited from discord.AutoShardedClient
instead.
Asynchronously initialises the bot and automatically cleans.
New in version 2.0.
A callable that implements a command prefix equivalent to being mentioned.
These are meant to be passed into the Bot.command_prefix
attribute.
Changed in version 2.0:
bot
andmsg
parameters are now positional-only.
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the Bot.command_prefix
attribute.
Example
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
Note
This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example:
async def get_prefix(bot, message): extras = await prefixes_for(message.guild) # returns a list return commands.when_mentioned_or(*extras)(bot, message)
These events function similar to the regular events, except they are custom to the command extension module.
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.
A default one is provided (Bot.on_command_error()
).
ctx (Context
) – The invocation context.
error (CommandError
derived) – The error that was raised.
An event that is called when a command is found and is about to be invoked.
This event is called regardless of whether the command itself succeeds via error or completes.
ctx (Context
) – The invocation context.
An event that is called when a command has completed its invocation.
This event is called only if the command succeeded, i.e. all checks have passed and the user input it correctly.
ctx (Context
) – The invocation context.
A decorator that transforms a function into a Command
or if called with group()
, Group
.
By default the help
attribute is received automatically from the docstring of the function and is cleaned up with the use of inspect.cleandoc
. If the docstring is bytes
, then it is decoded into str
using utf-8 encoding.
All checks added using the check()
& co. decorators are added into the function. There is no way to supply your own checks through this decorator.
TypeError – If the function is not a coroutine or is already a command.
A decorator that transforms a function into a Group
.
This is similar to the command()
decorator but the cls
parameter is set to Group
by default.
Changed in version 1.1: The cls
parameter can now be passed.
A decorator that transforms a function into a HybridCommand
.
A hybrid command is one that functions both as a regular Command
and one that is also a app_commands.Command
.
The callback being attached to the command must be representable as an application command callback. Converters are silently converted into a Transformer
with a discord.AppCommandOptionType.string
type.
Checks and error handlers are dispatched and called as-if they were commands similar to Command
. This means that they take Context
as a parameter rather than discord.Interaction
.
All checks added using the check()
& co. decorators are added into the function. There is no way to supply your own checks through this decorator.
New in version 2.0.
name (Union[str
, locale_str
]) – The name to create the command with. By default this uses the function name unchanged.
with_app_command (bool
) – Whether to register the command also as an application command.
**attrs – Keyword arguments to pass into the construction of the hybrid command.
TypeError – If the function is not a coroutine or is already a command.
A decorator that transforms a function into a HybridGroup
.
This is similar to the group()
decorator except it creates a hybrid group instead.
name (Union[str
, locale_str
]) – The name to create the group with. By default this uses the function name unchanged.
with_app_command (bool
) – Whether to register the command also as an application command.
TypeError – If the function is not a coroutine or is already a command.
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the decorator or functional interface.
The name of the command.
The coroutine that is executed when the command is called.
The long help text for the command.
Optional[str
]
The short help text for the command.
Optional[str
]
A replacement for arguments in the default help text.
Optional[str
]
A boolean that indicates if the command is currently enabled. If the command is invoked while it is disabled, then DisabledCommand
is raised to the on_command_error()
event. Defaults to True
.
The parent group that this command belongs to. None
if there isn’t one.
Optional[Group
]
The cog that this command belongs to. None
if there isn’t one.
Optional[Cog
]
A list of predicates that verifies if the command could be executed with the given Context
as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError
should be used. Note that if the checks fail then CheckFailure
exception is raised to the on_command_error()
event.
The message prefixed into the default help command.
If True
, the default help command does not show this in the help output.
If False
and a keyword-only argument is provided then the keyword only argument is stripped and handled as if it was a regular argument that handles MissingRequiredArgument
and default values in a regular matter rather than passing the rest completely raw. If True
then the keyword-only argument will pass in the rest of the arguments in a completely raw matter. Defaults to False
.
The subcommand that was invoked, if any.
Optional[Command
]
If True
and a variadic positional argument is specified, requires the user to specify at least one argument. Defaults to False
.
New in version 1.5.
If True
, ignores extraneous strings passed to a command if all its requirements are met (e.g. ?foo a b c
when only expecting a
and b
). Otherwise on_command_error()
and local error handlers are called with TooManyArguments
. Defaults to True
.
If True
, cooldown processing is done after argument parsing, which calls converters. If False
then cooldown processing is done first and then the converters are called second. Defaults to False
.
A dict of user provided extras to attach to the Command.
Note
This object may be copied by the library.
New in version 2.0.
A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a Context
.
See Bot.after_invoke()
for more info.
Changed in version 2.0: coro
parameter is now positional-only.
A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a Context
.
See Bot.before_invoke()
for more info.
Changed in version 2.0: coro
parameter is now positional-only.
A decorator that registers a coroutine as a local error handler.
A local error handler is an on_command_error()
event limited to a single command. However, the on_command_error()
is still invoked afterwards as the catch-all.
Changed in version 2.0: coro
parameter is now positional-only.
Adds a check to the command.
This is the non-decorator interface to check()
.
New in version 1.3.
Changed in version 2.0: func
parameter is now positional-only.
func – The function that will be used as a check.
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.
New in version 1.3.
Changed in version 2.0: func
parameter is now positional-only.
func – The function to remove from the checks.
Updates Command
instance with updated attribute.
This works similarly to the command()
decorator in terms of parameters in that they are passed to the Command
or subclass constructors, sans the name and callback.
This function is a coroutine.
Calls the internal callback that the command holds.
Note
This bypasses all mechanisms – including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments and types to this function.
New in version 1.3.
Changed in version 2.0: context
parameter is now positional-only.
Creates a copy of this command.
A new instance of this command.
Dict[str
, Parameter
]: Retrieves the parameter dictionary without the context or self parameters.
Useful for inspecting signature.
The cooldown of a command when invoked or None
if the command doesn’t have a registered cooldown.
New in version 2.0.
Optional[Cooldown
]
Retrieves the fully qualified parent command name.
This the base command name required to execute it. For example, in ?one two three
the parent name would be one two
.
Retrieves the parents of this command.
If the command has no parents then it returns an empty list
.
For example in commands ?a b c test
, the parents are [c, b, a]
.
New in version 1.1.
List[Group
]
Retrieves the root parent of this command.
If the command has no parents then it returns None
.
For example in commands ?a b c test
, the root parent is a
.
Optional[Group
]
Retrieves the fully qualified command name.
This is the full parent name with the command name as well. For example, in ?one two three
the qualified name would be one two three
.
Checks whether the command is currently on cooldown.
Changed in version 2.0: ctx
parameter is now positional-only.
Resets the cooldown on this command.
Changed in version 2.0: ctx
parameter is now positional-only.
ctx (Context
) – The invocation context to reset the cooldown under.
Retrieves the amount of seconds before this command can be tried again.
New in version 1.4.
Changed in version 2.0: ctx
parameter is now positional-only.
bool
: Checks whether the command has an error handler registered.
New in version 1.7.
The name of the cog this command belongs to, if any.
Optional[str
]
Gets the “short” documentation of a command.
By default, this is the brief
attribute. If that lookup leads to an empty string then the first line of the help
attribute is used instead.
Returns a POSIX-like signature useful for help command output.
This function is a coroutine.
Checks if the command can be executed by checking all the predicates inside the checks
attribute. This also checks whether the command is disabled.
Changed in version 1.3: Checks whether the command is disabled or not
Changed in version 2.0: ctx
parameter is now positional-only.
ctx (Context
) – The ctx of the command currently being invoked.
CommandError – Any command error that was raised during a check call will be propagated by this function.
A boolean indicating if the command can be invoked.
A class that implements a grouping protocol for commands to be executed as subcommands.
This class is a subclass of Command
and thus all options valid in Command
are valid in here as well.
Indicates if the group callback should begin parsing and invocation only if no subcommand was found. Useful for making it an error handling function to tell the user that no subcommand was found or to have different functionality in case no subcommand was found. If this is False
, then the group callback will always be invoked first. This means that the checks and the parsing dictated by its parameters will be executed. Defaults to False
.
Indicates if the group’s commands should be case insensitive. Defaults to False
.
A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a Context
.
See Bot.after_invoke()
for more info.
Changed in version 2.0: coro
parameter is now positional-only.
A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a Context
.
See Bot.before_invoke()
for more info.
Changed in version 2.0: coro
parameter is now positional-only.
A shortcut decorator that invokes command()
and adds it to the internal command list via add_command()
.
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
Callable[…, Command
]
A decorator that registers a coroutine as a local error handler.
A local error handler is an on_command_error()
event limited to a single command. However, the on_command_error()
is still invoked afterwards as the catch-all.
Changed in version 2.0: coro
parameter is now positional-only.
A shortcut decorator that invokes group()
and adds it to the internal command list via add_command()
.
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
Callable[…, Group
]
Adds a check to the command.
This is the non-decorator interface to check()
.
New in version 1.3.
Changed in version 2.0: func
parameter is now positional-only.
func – The function that will be used as a check.
Adds a Command
into the internal list of commands.
This is usually not called, instead the command()
or group()
shortcut decorators are used instead.
Changed in version 1.4: Raise CommandRegistrationError
instead of generic ClientException
Changed in version 2.0: command
parameter is now positional-only.
command (Command
) – The command to add.
CommandRegistrationError – If the command or its alias is already registered by different command.
TypeError – If the command passed is not a subclass of Command
.
This function is a coroutine.
Checks if the command can be executed by checking all the predicates inside the checks
attribute. This also checks whether the command is disabled.
Changed in version 1.3: Checks whether the command is disabled or not
Changed in version 2.0: ctx
parameter is now positional-only.
ctx (Context
) – The ctx of the command currently being invoked.
CommandError – Any command error that was raised during a check call will be propagated by this function.
A boolean indicating if the command can be invoked.
Dict[str
, Parameter
]: Retrieves the parameter dictionary without the context or self parameters.
Useful for inspecting signature.
The name of the cog this command belongs to, if any.
Optional[str
]
A unique set of commands without aliases that are registered.
Set[Command
]
The cooldown of a command when invoked or None
if the command doesn’t have a registered cooldown.
New in version 2.0.
Optional[Cooldown
]
Retrieves the fully qualified parent command name.
This the base command name required to execute it. For example, in ?one two three
the parent name would be one two
.
Get a Command
from the internal list of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. 'foo bar'
) will get the subcommand bar
of the group command foo
. If a subcommand is not found then None
is returned just as usual.
Changed in version 2.0: name
parameter is now positional-only.
Retrieves the amount of seconds before this command can be tried again.
New in version 1.4.
Changed in version 2.0: ctx
parameter is now positional-only.
bool
: Checks whether the command has an error handler registered.
New in version 1.7.
Checks whether the command is currently on cooldown.
Changed in version 2.0: ctx
parameter is now positional-only.
Retrieves the parents of this command.
If the command has no parents then it returns an empty list
.
For example in commands ?a b c test
, the parents are [c, b, a]
.
New in version 1.1.
List[Group
]
Retrieves the fully qualified command name.
This is the full parent name with the command name as well. For example, in ?one two three
the qualified name would be one two three
.
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.
New in version 1.3.
Changed in version 2.0: func
parameter is now positional-only.
func – The function to remove from the checks.
Remove a Command
from the internal list of commands.
This could also be used as a way to remove aliases.
Changed in version 2.0: name
parameter is now positional-only.
Resets the cooldown on this command.
Changed in version 2.0: ctx
parameter is now positional-only.
ctx (Context
) – The invocation context to reset the cooldown under.
Retrieves the root parent of this command.
If the command has no parents then it returns None
.
For example in commands ?a b c test
, the root parent is a
.
Optional[Group
]
Gets the “short” documentation of a command.
By default, this is the brief
attribute. If that lookup leads to an empty string then the first line of the help
attribute is used instead.
Returns a POSIX-like signature useful for help command output.
A mixin that implements common functionality for classes that behave similar to Group
and are allowed to register commands.
Whether the commands should be case insensitive. Defaults to False
.
A shortcut decorator that invokes command()
and adds it to the internal command list via add_command()
.
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
Callable[…, Command
]
A shortcut decorator that invokes group()
and adds it to the internal command list via add_command()
.
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
Callable[…, Group
]
A unique set of commands without aliases that are registered.
Set[Command
]
Adds a Command
into the internal list of commands.
This is usually not called, instead the command()
or group()
shortcut decorators are used instead.
Changed in version 1.4: Raise CommandRegistrationError
instead of generic ClientException
Changed in version 2.0: command
parameter is now positional-only.
command (Command
) – The command to add.
CommandRegistrationError – If the command or its alias is already registered by different command.
TypeError – If the command passed is not a subclass of Command
.
Remove a Command
from the internal list of commands.
This could also be used as a way to remove aliases.
Changed in version 2.0: name
parameter is now positional-only.
An iterator that recursively walks through all commands and subcommands.
Changed in version 1.4: Duplicates due to aliases are no longer returned
Get a Command
from the internal list of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. 'foo bar'
) will get the subcommand bar
of the group command foo
. If a subcommand is not found then None
is returned just as usual.
Changed in version 2.0: name
parameter is now positional-only.
A class that is both an application command and a regular text command.
This has the same parameters and attributes as a regular Command
. However, it also doubles as an application command
. In order for this to work, the callbacks must have the same subset that is supported by application commands.
These are not created manually, instead they are created via the decorator or functional interface.
New in version 2.0.
A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a Context
.
See Bot.after_invoke()
for more info.
Changed in version 2.0: coro
parameter is now positional-only.
A decorator that registers a coroutine as an autocomplete prompt for a parameter.
This is the same as autocomplete()
. It is only applicable for the application command and doesn’t do anything if the command is a regular command.
A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a Context
.
See Bot.before_invoke()
for more info.
Changed in version 2.0: coro
parameter is now positional-only.
A decorator that registers a coroutine as a local error handler.
A local error handler is an on_command_error()
event limited to a single command. However, the on_command_error()
is still invoked afterwards as the catch-all.
Changed in version 2.0: coro
parameter is now positional-only.
This function is a coroutine.
Checks if the command can be executed by checking all the predicates inside the checks
attribute. This also checks whether the command is disabled.
Changed in version 1.3: Checks whether the command is disabled or not
Changed in version 2.0: ctx
parameter is now positional-only.
ctx (Context
) – The ctx of the command currently being invoked.
CommandError – Any command error that was raised during a check call will be propagated by this function.
A boolean indicating if the command can be invoked.
A class that is both an application command group and a regular text group.
This has the same parameters and attributes as a regular Group
. However, it also doubles as an application command group
. Note that application commands groups cannot have callbacks associated with them, so the callback is only called if it’s not invoked as an application command.
Hybrid groups will always have Group.invoke_without_command
set to True
.
These are not created manually, instead they are created via the decorator or functional interface.
New in version 2.0.
The command name to use as a fallback for the application command. Since application command groups cannot be invoked, this creates a subcommand within the group that can be invoked with the given group callback. If None
then no fallback command is given. Defaults to None
.
Optional[str
]
The fallback command name’s locale string, if available.
Optional[locale_str
]
A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a Context
.
See Bot.after_invoke()
for more info.
Changed in version 2.0: coro
parameter is now positional-only.
A decorator that registers a coroutine as an autocomplete prompt for a parameter.
This is the same as autocomplete()
. It is only applicable for the application command and doesn’t do anything if the command is a regular command.
This is only available if the group has a fallback application command registered.
A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a Context
.
See Bot.before_invoke()
for more info.
Changed in version 2.0: coro
parameter is now positional-only.
A shortcut decorator that invokes hybrid_command()
and adds it to the internal command list via add_command()
.
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
Callable[…, HybridCommand
]
A decorator that registers a coroutine as a local error handler.
A local error handler is an on_command_error()
event limited to a single command. However, the on_command_error()
is still invoked afterwards as the catch-all.
Changed in version 2.0: coro
parameter is now positional-only.
A shortcut decorator that invokes hybrid_group()
and adds it to the internal command list via add_command()
.
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
Callable[…, HybridGroup
]
This function is a coroutine.
Checks if the command can be executed by checking all the predicates inside the checks
attribute. This also checks whether the command is disabled.
Changed in version 1.3: Checks whether the command is disabled or not
Changed in version 2.0: ctx
parameter is now positional-only.
ctx (Context
) – The ctx of the command currently being invoked.
CommandError – Any command error that was raised during a check call will be propagated by this function.
A boolean indicating if the command can be invoked.
Adds a check to the command.
This is the non-decorator interface to check()
.
New in version 1.3.
Changed in version 2.0: func
parameter is now positional-only.
func – The function that will be used as a check.
Adds a HybridCommand
into the internal list of commands.
This is usually not called, instead the command()
or group()
shortcut decorators are used instead.
command (HybridCommand
) – The command to add.
CommandRegistrationError – If the command or its alias is already registered by different command.
TypeError – If the command passed is not a subclass of HybridCommand
.
Dict[str
, Parameter
]: Retrieves the parameter dictionary without the context or self parameters.
Useful for inspecting signature.
The name of the cog this command belongs to, if any.
Optional[str
]
A unique set of commands without aliases that are registered.
Set[Command
]
The cooldown of a command when invoked or None
if the command doesn’t have a registered cooldown.
New in version 2.0.
Optional[Cooldown
]
Retrieves the fully qualified parent command name.
This the base command name required to execute it. For example, in ?one two three
the parent name would be one two
.
Get a Command
from the internal list of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. 'foo bar'
) will get the subcommand bar
of the group command foo
. If a subcommand is not found then None
is returned just as usual.
Changed in version 2.0: name
parameter is now positional-only.
Retrieves the amount of seconds before this command can be tried again.
New in version 1.4.
Changed in version 2.0: ctx
parameter is now positional-only.
bool
: Checks whether the command has an error handler registered.
New in version 1.7.
Checks whether the command is currently on cooldown.
Changed in version 2.0: ctx
parameter is now positional-only.
Retrieves the parents of this command.
If the command has no parents then it returns an empty list
.
For example in commands ?a b c test
, the parents are [c, b, a]
.
New in version 1.1.
List[Group
]
Retrieves the fully qualified command name.
This is the full parent name with the command name as well. For example, in ?one two three
the qualified name would be one two three
.
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.
New in version 1.3.
Changed in version 2.0: func
parameter is now positional-only.
func – The function to remove from the checks.
Resets the cooldown on this command.
Changed in version 2.0: ctx
parameter is now positional-only.
ctx (Context
) – The invocation context to reset the cooldown under.
Retrieves the root parent of this command.
If the command has no parents then it returns None
.
For example in commands ?a b c test
, the root parent is a
.
Optional[Group
]
Gets the “short” documentation of a command.
By default, this is the brief
attribute. If that lookup leads to an empty string then the first line of the help
attribute is used instead.
Returns a POSIX-like signature useful for help command output.
Updates Command
instance with updated attribute.
This works similarly to the command()
decorator in terms of parameters in that they are passed to the Command
or subclass constructors, sans the name and callback.
An iterator that recursively walks through all commands and subcommands.
Changed in version 1.4: Duplicates due to aliases are no longer returned
Remove a Command
from the internal list of commands.
This could also be used as a way to remove aliases.
Changed in version 2.0: name
parameter is now positional-only.
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the Cogs page.
When inheriting from this class, the options shown in CogMeta
are equally valid here.
Returns the commands that are defined inside this cog.
This does not include discord.app_commands.Command
or discord.app_commands.Group
instances.
Returns the app commands that are defined inside this cog.
A list
of discord.app_commands.Command
s and discord.app_commands.Group
s that are defined inside this cog, not including subcommands.
List[Union[discord.app_commands.Command
, discord.app_commands.Group
]]
Returns the cog’s specified name, not the class name.
Returns the cog’s description, typically the cleaned docstring.
An iterator that recursively walks through this cog’s commands and subcommands.
An iterator that recursively walks through this cog’s app commands and subcommands.
Union[discord.app_commands.Command
, discord.app_commands.Group
] – An app command or group from the cog.
Returns the associated group with this cog.
This is only available if inheriting from GroupCog
.
Optional[discord.app_commands.Group
]
Returns a list
of (name, function) listener pairs that are defined in this cog.
A decorator that marks a function as a listener.
This is the cog equivalent of Bot.listen()
.
bool
: Checks whether the cog has an error handler.
New in version 1.7.
bool
: Checks whether the cog has an app error handler.
New in version 2.1.
This function could be a coroutine.
A special method that is called when the cog gets loaded.
Subclasses must replace this if they want special asynchronous loading behaviour. Note that the __init__
special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.
New in version 2.0.
This function could be a coroutine.
A special method that is called when the cog gets removed.
Subclasses must replace this if they want special unloading behaviour.
Exceptions raised in this method are ignored during extension unloading.
Changed in version 2.0: This method can now be a coroutine.
A special method that registers as a Bot.check_once()
check.
This function can be a coroutine and must take a sole parameter, ctx
, to represent the Context
.
A special method that registers as a Bot.check()
check.
This function can be a coroutine and must take a sole parameter, ctx
, to represent the Context
.
A special method that registers as a check()
for every command and subcommand in this cog.
This function can be a coroutine and must take a sole parameter, ctx
, to represent the Context
.
A special method that registers as a discord.app_commands.check()
for every app command and subcommand in this cog.
This function can be a coroutine and must take a sole parameter, interaction
, to represent the Interaction
.
New in version 2.0.
This function is a coroutine.
A special method that is called whenever an error is dispatched inside this cog.
This is similar to on_command_error()
except only applying to the commands inside this cog.
This must be a coroutine.
ctx (Context
) – The invocation context where the error happened.
error (CommandError
) – The error that happened.
This function is a coroutine.
A special method that is called whenever an error within an application command is dispatched inside this cog.
This is similar to discord.app_commands.CommandTree.on_error()
except only applying to the application commands inside this cog.
This must be a coroutine.
interaction (Interaction
) – The interaction that is being handled.
error (AppCommandError
) – The exception that was raised.
This function is a coroutine.
A special method that acts as a cog local pre-invoke hook.
This is similar to Command.before_invoke()
.
This must be a coroutine.
ctx (Context
) – The invocation context.
This function is a coroutine.
A special method that acts as a cog local post-invoke hook.
This is similar to Command.after_invoke()
.
This must be a coroutine.
ctx (Context
) – The invocation context.
Represents a cog that also doubles as a parent discord.app_commands.Group
for the application commands defined within it.
This inherits from Cog
and the options in CogMeta
also apply to this. See the Cog
documentation for methods.
Decorators such as guild_only()
, guilds()
, and default_permissions()
will apply to the group if used on top of the cog.
Hybrid commands will also be added to the Group, giving the ability to categorize slash commands into groups, while keeping the prefix-style command as a root-level command.
For example:
from discord import app_commands from discord.ext import commands @app_commands.guild_only() class MyCog(commands.GroupCog, group_name='my-cog'): pass
New in version 2.0.
A special method that registers as a discord.app_commands.check()
for every app command and subcommand in this cog.
This function can be a coroutine and must take a sole parameter, interaction
, to represent the Interaction
.
New in version 2.0.
A metaclass for defining a cog.
Note that you should probably not use this directly. It is exposed purely for documentation purposes along with making custom metaclasses to intermix with other metaclasses such as the abc.ABCMeta
metaclass.
For example, to create an abstract cog mixin class, the following would be done.
import abc class CogABCMeta(commands.CogMeta, abc.ABCMeta): pass class SomeMixin(metaclass=abc.ABCMeta): pass class SomeCogMixin(SomeMixin, commands.Cog, metaclass=CogABCMeta): pass
Note
When passing an attribute of a metaclass that is documented below, note that you must pass it as a keyword-only argument to the class creation like the following example:
class MyCog(commands.Cog, name='My Cog'): pass
The cog name. By default, it is the name of the class with no modification.
The cog description. By default, it is the cleaned docstring of the class.
New in version 1.6.
A list of attributes to apply to every command inside this cog. The dictionary is passed into the Command
options at __init__
. If you specify attributes inside the command attribute in the class, it will override the one specified inside this attribute. For example:
class MyCog(commands.Cog, command_attrs=dict(hidden=True)): @commands.command() async def foo(self, ctx): pass # hidden -> True @commands.command(hidden=False) async def bar(self, ctx): pass # hidden -> False
The group name of a cog. This is only applicable for GroupCog
instances. By default, it’s the same value as name
.
New in version 2.0.
Union[str
, locale_str
]
The group description of a cog. This is only applicable for GroupCog
instances. By default, it’s the same value as description
.
New in version 2.0.
Union[str
, locale_str
]
Whether the application command group is NSFW. This is only applicable for GroupCog
instances. By default, it’s False
.
New in version 2.0.
If this is set to True
, then all translatable strings will implicitly be wrapped into locale_str
rather than str
. Defaults to True
.
New in version 2.0.
The base implementation for help command formatting.
Note
Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in GH-2123.
This means that relying on the state of this class to be the same between command invocations would not work as expected.
The context that invoked this help formatter. This is generally set after the help command assigned, command_callback()
, has been called.
Optional[Context
]
Specifies if hidden commands should be shown in the output. Defaults to False
.
Specifies if commands should have their Command.checks
called and verified. If True
, always calls Command.checks
. If None
, only calls Command.checks
in a guild setting. If False
, never calls Command.checks
. Defaults to True
.
Changed in version 1.7.
Optional[bool
]
A dictionary of options to pass in for the construction of the help command. This allows you to change the command behaviour without actually changing the implementation of the command. The attributes will be the same as the ones passed in the Command
constructor.
Adds a check to the help command.
New in version 1.4.
Changed in version 2.0: func
parameter is now positional-only.
func – The function that will be used as a check.
Removes a check from the help command.
This function is idempotent and will not raise an exception if the function is not in the command’s checks.
New in version 1.4.
Changed in version 2.0: func
parameter is now positional-only.
func – The function to remove from the checks.
Retrieves the bot mapping passed to send_bot_help()
.
Similar to Context.invoked_with
except properly handles the case where Context.send_help()
is used.
If the help command was used regularly then this returns the Context.invoked_with
attribute. Otherwise, if it the help command was called using Context.send_help()
then it returns the internal command name of the help command.
The command name that triggered this invocation.
Optional[str
]
Retrieves the signature portion of the help page.
Changed in version 2.0: command
parameter is now positional-only.
Removes mentions from the string to prevent abuse.
This includes @everyone
, @here
, member mentions and role mentions.
Changed in version 2.0: string
parameter is now positional-only.
The string with mentions removed.
A property for retrieving or setting the cog for the help command.
When a cog is set for the help command, it is as-if the help command belongs to that cog. All cog special methods will apply to the help command and it will be automatically unset on unload.
To unbind the cog from the help command, you can set it to None
.
The cog that is currently set for the help command.
Optional[Cog
]
This function could be a coroutine.
A method called when a command is not found in the help command. This is useful to override for i18n.
Defaults to No command called {0} found.
Changed in version 2.0: string
parameter is now positional-only.
This function could be a coroutine.
A method called when a command did not have a subcommand requested in the help command. This is useful to override for i18n.
Defaults to either:
'Command "{command.qualified_name}" has no subcommands.'
If there is no subcommand in the command
parameter.
'Command "{command.qualified_name}" has no subcommand named {string}'
If the command
parameter has subcommands but not one named string
.
Changed in version 2.0: command
and string
parameters are now positional-only.
The string to use when the command did not have the subcommand requested.
This function is a coroutine.
Returns a filtered list of commands and optionally sorts them.
This takes into account the verify_checks
and show_hidden
attributes.
Changed in version 2.0: commands
parameter is now positional-only.
commands (Iterable[Command
]) – An iterable of commands that are getting filtered.
sort (bool
) – Whether to sort the result.
key (Optional[Callable[[Command
], Any]]) – An optional key function to pass to sorted()
that takes a Command
as its sole parameter. If sort
is passed as True
then this will default as the command name.
A list of commands that passed the filter.
List[Command
]
Returns the largest name length of the specified command list.
Changed in version 2.0: commands
parameter is now positional-only.
Returns the Messageable
where the help command will be output.
You can override this method to customise the behaviour.
By default this returns the context’s channel.
The destination where the help command will be output.
This function is a coroutine.
Handles the implementation when an error happens in the help command. For example, the result of command_not_found()
will be passed here.
You can override this method to customise the behaviour.
By default, this sends the error message to the destination specified by get_destination()
.
Changed in version 2.0: error
parameter is now positional-only.
error (str
) – The error message to display to the user. Note that this has had mentions removed to prevent abuse.
This function is a coroutine.
The help command’s error handler, as specified by Error Handling.
Useful to override if you need some specific behaviour when the error handler is called.
By default this method does nothing and just propagates to the default error handlers.
Changed in version 2.0: ctx
and error
parameters are now positional-only.
ctx (Context
) – The invocation context.
error (CommandError
) – The error that was raised.
This function is a coroutine.
Handles the implementation of the bot command page in the help command. This function is called when the help command is called with no arguments.
It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination()
to know where to send, as this is a customisation point for other users.
You can override this method to customise the behaviour.
Note
You can access the invocation context with HelpCommand.context
.
Also, the commands in the mapping are not filtered. To do the filtering you will have to call filter_commands()
yourself.
Changed in version 2.0: mapping
parameter is now positional-only.
This function is a coroutine.
Handles the implementation of the cog page in the help command. This function is called when the help command is called with a cog as the argument.
It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination()
to know where to send, as this is a customisation point for other users.
You can override this method to customise the behaviour.
Changed in version 2.0: cog
parameter is now positional-only.
cog (Cog
) – The cog that was requested for help.
This function is a coroutine.
Handles the implementation of the group page in the help command. This function is called when the help command is called with a group as the argument.
It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination()
to know where to send, as this is a customisation point for other users.
You can override this method to customise the behaviour.
Note
You can access the invocation context with HelpCommand.context
.
To get the commands that belong to this group without aliases see Group.commands
. The commands returned not filtered. To do the filtering you will have to call filter_commands()
yourself.
Changed in version 2.0: group
parameter is now positional-only.
group (Group
) – The group that was requested for help.
This function is a coroutine.
Handles the implementation of the single command page in the help command.
It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination()
to know where to send, as this is a customisation point for other users.
You can override this method to customise the behaviour.
Changed in version 2.0: command
parameter is now positional-only.
command (Command
) – The command that was requested for help.
This function is a coroutine.
A low level method that can be used to prepare the help command before it does anything. For example, if you need to prepare some state in your subclass before the command does its processing then this would be the place to do it.
The default implementation does nothing.
Note
This is called inside the help command callback body. So all the usual rules that happen inside apply here as well.
Changed in version 2.0: ctx
and command
parameters are now positional-only.
This function is a coroutine.
The actual implementation of the help command.
It is not recommended to override this method and instead change the behaviour through the methods that actually get dispatched.
Changed in version 2.0: ctx
parameter is now positional-only.
The implementation of the default help command.
This inherits from HelpCommand
.
It extends it with the following attributes.
The maximum number of characters that fit in a line. Defaults to 80.
Whether to sort the commands in the output alphabetically. Defaults to True
.
A tribool that indicates if the help command should DM the user instead of sending it to the channel it received it from. If the boolean is set to True
, then all help output is DM’d. If False
, none of the help output is DM’d. If None
, then the bot will only DM when the help message becomes too long (dictated by more than dm_help_threshold
characters). Defaults to False
.
Optional[bool
]
The number of characters the paginator must accumulate before getting DM’d to the user if dm_help
is set to None
. Defaults to 1000.
Optional[int
]
How much to indent the commands from a heading. Defaults to 2
.
The arguments list’s heading string used when the help command is invoked with a command name. Useful for i18n. Defaults to "Arguments:"
. Shown when show_parameter_descriptions
is True
.
New in version 2.0.
Whether to show the parameter descriptions. Defaults to True
. Setting this to False
will revert to showing the signature
instead.
New in version 2.0.
The command list’s heading string used when the help command is invoked with a category name. Useful for i18n. Defaults to "Commands:"
The default argument description string used when the argument’s description
is None
. Useful for i18n. Defaults to "No description given."
New in version 2.0.
The string used when there is a command which does not belong to any category(cog). Useful for i18n. Defaults to "No Category"
The paginator used to paginate the help command output.
str
: Shortens text to fit into the width
.
Changed in version 2.0: text
parameter is now positional-only.
str
: Returns help command’s ending note. This is mainly useful to override for i18n purposes.
Retrieves the signature portion of the help page.
Calls get_command_signature()
if show_parameter_descriptions
is False
else returns a modified signature where the command parameters are not shown.
New in version 2.0.
Indents a list of commands after the specified heading.
The formatting is added to the paginator
.
The default implementation is the command name indented by indent
spaces, padded to max_size
followed by the command’s Command.short_doc
and then shortened to fit into the width
.
Changed in version 2.0: commands
parameter is now positional-only.
commands (Sequence[Command
]) – A list of commands to indent for output.
heading (str
) – The heading to add to the output. This is only added if the list of commands is greater than 0.
max_size (Optional[int
]) – The max size to use for the gap between indents. If unspecified, calls get_max_size()
on the commands parameter.
Indents a list of command arguments after the arguments_heading
.
The default implementation is the argument name
indented by indent
spaces, padded to max_size
using get_max_size()
followed by the argument’s description
or default_argument_description
and then shortened to fit into the width
and then displayed_default
between () if one is present after that.
New in version 2.0.
command (Command
) – The command to list the arguments for.
This function is a coroutine.
A helper utility to send the page output from paginator
to the destination.
A utility function to format the non-indented block of commands and groups.
Changed in version 2.0: command
parameter is now positional-only.
Changed in version 2.0: add_command_arguments()
is now called if show_parameter_descriptions
is True
.
command (Command
) – The command to format.
Returns the Messageable
where the help command will be output.
You can override this method to customise the behaviour.
By default this returns the context’s channel.
The destination where the help command will be output.
An implementation of a help command with minimal output.
This inherits from HelpCommand
.
Whether to sort the commands in the output alphabetically. Defaults to True
.
The command list’s heading string used when the help command is invoked with a category name. Useful for i18n. Defaults to "Commands"
The alias list’s heading string used to list the aliases of the command. Useful for i18n. Defaults to "Aliases:"
.
A tribool that indicates if the help command should DM the user instead of sending it to the channel it received it from. If the boolean is set to True
, then all help output is DM’d. If False
, none of the help output is DM’d. If None
, then the bot will only DM when the help message becomes too long (dictated by more than dm_help_threshold
characters). Defaults to False
.
Optional[bool
]
The number of characters the paginator must accumulate before getting DM’d to the user if dm_help
is set to None
. Defaults to 1000.
Optional[int
]
The string used when there is a command which does not belong to any category(cog). Useful for i18n. Defaults to "No Category"
The paginator used to paginate the help command output.
This function is a coroutine.
A helper utility to send the page output from paginator
to the destination.
Returns help command’s opening note. This is mainly useful to override for i18n purposes.
The default implementation returns
Use `{prefix}{command_name} [command]` for more info on a command. You can also use `{prefix}{command_name} [category]` for more info on a category.
The help command opening note.
Retrieves the signature portion of the help page.
Changed in version 2.0: command
parameter is now positional-only.
Return the help command’s ending note. This is mainly useful to override for i18n purposes.
The default implementation does nothing.
The help command ending note.
Adds the minified bot heading with commands to the output.
The formatting should be added to the paginator
.
The default implementation is a bold underline heading followed by commands separated by an EN SPACE (U+2002) in the next line.
Changed in version 2.0: commands
and heading
parameters are now positional-only.
Adds formatting information on a subcommand.
The formatting should be added to the paginator
.
The default implementation is the prefix and the Command.qualified_name
optionally followed by an En dash and the command’s Command.short_doc
.
Changed in version 2.0: command
parameter is now positional-only.
command (Command
) – The command to show information of.
Adds the formatting information on a command’s aliases.
The formatting should be added to the paginator
.
The default implementation is the aliases_heading
bolded followed by a comma separated list of aliases.
This is not called if there are no aliases to format.
Changed in version 2.0: aliases
parameter is now positional-only.
aliases (Sequence[str
]) – A list of aliases to format.
A utility function to format commands and groups.
Changed in version 2.0: command
parameter is now positional-only.
command (Command
) – The command to format.
Returns the Messageable
where the help command will be output.
You can override this method to customise the behaviour.
By default this returns the context’s channel.
The destination where the help command will be output.
A class that aids in paginating code blocks for Discord messages.
Returns the total number of characters in the paginator.
The prefix inserted to every page. e.g. three backticks, if any.
Optional[str
]
The suffix appended at the end of every page. e.g. three backticks, if any.
Optional[str
]
The maximum amount of codepoints allowed in a page.
New in version 1.7.
Clears the paginator to have no pages.
Adds a line to the current page.
If the line exceeds the max_size
then an exception is raised.
RuntimeError – The line was too big for the current max_size
.
Prematurely terminate a page.
Returns the rendered list of pages.
List[str
]
Specifies a type of bucket for, e.g. a cooldown.
The default bucket operates on a global basis.
The user bucket operates on a per-user basis.
The guild bucket operates on a per-guild basis.
The channel bucket operates on a per-channel basis.
The member bucket operates on a per-member basis.
The category bucket operates on a per-category basis.
The role bucket operates on a per-role basis.
New in version 1.3.
A decorator that adds a check to the Command
or its subclasses. These checks could be accessed via Command.checks
.
These checks should be predicates that take in a single parameter taking a Context
. If the check returns a False
-like value then during invocation a CheckFailure
exception is raised and sent to the on_command_error()
event.
If an exception should be thrown in the predicate then it should be a subclass of CommandError
. Any exception not subclassed from it will be propagated while those subclassed will be sent to on_command_error()
.
A special attribute named predicate
is bound to the value returned by this decorator to retrieve the predicate passed to the decorator. This allows the following introspection and chaining to be done:
def owner_or_permissions(**perms): original = commands.has_permissions(**perms).predicate async def extended_check(ctx): if ctx.guild is None: return False return ctx.guild.owner_id == ctx.author.id or await original(ctx) return commands.check(extended_check)
Note
The function returned by predicate
is always a coroutine, even if the original function was not a coroutine.
Changed in version 1.3: The predicate
attribute was added.
Examples
Creating a basic check to see if the command invoker is you.
def check_if_it_is_me(ctx): return ctx.message.author.id == 85309593344815104 @bot.command() @commands.check(check_if_it_is_me) async def only_for_me(ctx): await ctx.send('I know you!')
Transforming common checks into its own decorator:
def is_me(): def predicate(ctx): return ctx.message.author.id == 85309593344815104 return commands.check(predicate) @bot.command() @is_me() async def only_me(ctx): await ctx.send('Only you!')
Changed in version 2.0: predicate
parameter is now positional-only.
A check()
that is added that checks if any of the checks passed will pass, i.e. using logical OR.
If all checks fail then CheckAnyFailure
is raised to signal the failure. It inherits from CheckFailure
.
Note
The predicate
attribute for this function is a coroutine.
New in version 1.3.
*checks (Callable[[Context
], bool
]) – An argument list of checks that have been decorated with the check()
decorator.
TypeError – A check passed has not been decorated with the check()
decorator.
Examples
Creating a basic check to see if it’s the bot owner or the server owner:
def is_guild_owner(): def predicate(ctx): return ctx.guild is not None and ctx.guild.owner_id == ctx.author.id return commands.check(predicate) @bot.command() @commands.check_any(commands.is_owner(), is_guild_owner()) async def only_for_owners(ctx): await ctx.send('Hello mister owner!')
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.
If the message is invoked in a private message context then the check will return False
.
This check raises one of two special exceptions, MissingRole
if the user is missing a role, or NoPrivateMessage
if it is used in a private message. Both inherit from CheckFailure
.
Changed in version 1.1: Raise MissingRole
or NoPrivateMessage
instead of generic CheckFailure
Changed in version 2.0: item
parameter is now positional-only.
A check()
that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide 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 from CheckFailure
.
perms – An argument list of permissions to check for.
Example
@bot.command() @commands.has_permissions(manage_messages=True) async def test(ctx): await ctx.send('You can manage messages.')
Similar to has_permissions()
, but operates on guild wide permissions instead of the current channel permissions.
If this check is called in a DM context, it will raise an exception, NoPrivateMessage
.
New in version 1.3.
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 return True
.
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, or NoPrivateMessage
if it is used in a private message. Both inherit from CheckFailure
.
Changed in version 1.1: Raise MissingAnyRole
or NoPrivateMessage
instead of generic CheckFailure
items (List[Union[str
, int
]]) – An argument list of names or IDs to check that the member has roles wise.
Example
@bot.command() @commands.has_any_role('Library Devs', 'Moderators', 492212595072434186) async def cool(ctx): await ctx.send('You are cool indeed')
Similar to has_role()
except checks if the bot itself has the role.
This check raises one of two special exceptions, BotMissingRole
if the bot is missing the role, or NoPrivateMessage
if it is used in a private message. Both inherit from CheckFailure
.
Changed in version 1.1: Raise BotMissingRole
or NoPrivateMessage
instead of generic CheckFailure
Changed in version 2.0: item
parameter is now positional-only.
Similar to has_permissions()
except checks if the bot itself has the permissions listed.
This check raises a special exception, BotMissingPermissions
that is inherited from CheckFailure
.
Similar to has_guild_permissions()
, but checks the bot members guild permissions.
New in version 1.3.
Similar to has_any_role()
except checks if the bot itself has any of the roles listed.
This check raises one of two special exceptions, BotMissingAnyRole
if the bot is missing all roles, or NoPrivateMessage
if it is used in a private message. Both inherit from CheckFailure
.
Changed in version 1.1: Raise BotMissingAnyRole
or NoPrivateMessage
instead of generic checkfailure
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 can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of type
which must be of enum type BucketType
.
If a cooldown is triggered, then CommandOnCooldown
is triggered in on_command_error()
and the local error handler.
A command can only have a single cooldown.
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.
type (Union[BucketType
, Callable[[Context
], Any]]) –
The type of cooldown to have. If callable, should return a key for the mapping.
Changed in version 1.7: Callables are now supported for custom bucket types.
Changed in version 2.0: When passing a callable, it now needs to accept Context
rather than Message
as its only argument.
A decorator that adds a dynamic cooldown to a Command
This differs from cooldown()
in that it takes a function that accepts a single parameter of type Context
and must return a Cooldown
or None
. If None
is returned then that cooldown is effectively bypassed.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of type
which must be of enum type BucketType
.
If a cooldown is triggered, then CommandOnCooldown
is triggered in on_command_error()
and the local error handler.
A command can only have a single cooldown.
New in version 2.0.
cooldown (Callable[[Context
], Optional[Cooldown
]]) – A function that takes a message and returns a cooldown that will apply to this invocation or None
if the cooldown should be bypassed.
type (BucketType
) – The type of cooldown to have.
A decorator that adds a maximum concurrency to a Command
or its subclasses.
This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket – only a set number of people can run the command.
New in version 1.3.
number (int
) – The maximum number of invocations of this command that can be running at the same time.
per (BucketType
) – The bucket that this concurrency is based on, e.g. BucketType.guild
would allow it to be used up to number
times per guild.
wait (bool
) – Whether the command should wait for the queue to be over. If this is set to False
then instead of waiting until the command can run again, the command raises MaxConcurrencyReached
to its error handler. If this is set to True
then the command waits until it can be executed.
A decorator that registers a coroutine as a pre-invoke hook.
This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog.
New in version 1.4.
Changed in version 2.0: coro
parameter is now positional-only.
Example
async def record_usage(ctx): print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at) @bot.command() @commands.before_invoke(record_usage) async def who(ctx): # Output: <User> used who at <Time> await ctx.send('i am a bot') class What(commands.Cog): @commands.before_invoke(record_usage) @commands.command() async def when(self, ctx): # Output: <User> used when at <Time> await ctx.send(f'and i have existed since {ctx.bot.user.created_at}') @commands.command() async def where(self, ctx): # Output: <Nothing> await ctx.send('on Discord') @commands.command() async def why(self, ctx): # Output: <Nothing> await ctx.send('because someone made me')
A decorator that registers a coroutine as a post-invoke hook.
This allows you to refer to one after invoke hook for several commands that do not have to be within the same cog.
New in version 1.4.
Changed in version 2.0: coro
parameter is now positional-only.
A check()
that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.
This check raises a special exception, NoPrivateMessage
that is inherited from CheckFailure
.
If used on hybrid commands, this will be equivalent to the discord.app_commands.guild_only()
decorator. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
A check()
that indicates this command must only be used in a DM context. Only private messages are allowed when using the command.
This check raises a special exception, PrivateMessageOnly
that is inherited from CheckFailure
.
New in version 1.1.
A check()
that checks if the person invoking this command is the owner of the bot.
This is powered by Bot.is_owner()
.
This check raises a special exception, NotOwner
that is derived from CheckFailure
.
A check()
that checks if the channel is a NSFW channel.
This check raises a special exception, NSFWChannelRequired
that is derived from CheckFailure
.
If used on hybrid commands, this will be equivalent to setting the application command’s nsfw
attribute to True
. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
Changed in version 1.1: Raise NSFWChannelRequired
instead of generic CheckFailure
. DM channels will also now pass this check.
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the Messageable
ABC.
The message that triggered the command being executed.
Note
In the case of an interaction based context, this message is “synthetic” and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.
The bot that contains the command being executed.
The list of transformed arguments that were passed into the command. If this is accessed during the on_command_error()
event then this list could be incomplete.
A dictionary of transformed arguments that were passed into the command. Similar to args
, if this is accessed in the on_command_error()
event then this dict could be incomplete.
The parameter that is currently being inspected and converted. This is only of use for within converters.
New in version 2.0.
Optional[Parameter
]
The argument string of the current_parameter
that is currently being converted. This is only of use for within converters.
New in version 2.0.
Optional[str
]
The interaction associated with this context.
New in version 2.0.
Optional[Interaction
]
The prefix that was used to invoke the command. For interaction based contexts, this is /
for slash commands and \u200b
for context menu commands.
Optional[str
]
The command that is being invoked currently.
Optional[Command
]
The command name that triggered this invocation. Useful for finding out which alias called the command.
Optional[str
]
The command names of the parents that triggered this invocation. Useful for finding out which aliases called the command.
For example in commands ?a b c test
, the invoked parents are ['a', 'b', 'c']
.
New in version 1.7.
List[str
]
The subcommand that was invoked. If no valid subcommand was invoked then this is equal to None
.
Optional[Command
]
The string that was attempted to call a subcommand. This does not have to point to a valid registered subcommand and could just point to a nonsense string. If nothing was passed to attempt a call to a subcommand then this is set to None
.
Optional[str
]
A boolean that indicates if the command failed to be parsed, checked, or invoked.
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using await
.
In an interaction based context, this is equivalent to a defer()
call and does not do any typing calls.
Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!')
Example Usage:
await channel.typing() # Do some computational magic for about 10 seconds await channel.send('Done!')
Changed in version 2.0: This no longer works with the with
syntax, async with
must be used instead.
Changed in version 2.0: Added functionality to await
the context manager to send a typing indicator for 10 seconds.
ephemeral (bool
) –
Indicates whether the deferred message will eventually be ephemeral. Only valid for interaction based contexts.
New in version 2.0.
This function is a coroutine.
Creates a context from a discord.Interaction
. This only works on application command based interactions, such as slash commands or context menus.
On slash command based interactions this creates a synthetic Message
that points to an ephemeral message that the command invoker has executed. This means that Context.author
returns the member that invoked the command.
In a message context menu based interaction, the Context.message
attribute is the message that the command is being executed on. This means that Context.author
returns the author of the message being targetted. To get the member that invoked the command then discord.Interaction.user
should be used instead.
New in version 2.0.
interaction (discord.Interaction
) – The interaction to create a context with.
ValueError – The interaction does not have a valid command.
TypeError – The interaction client is not derived from Bot
or AutoShardedBot
.
This function is a coroutine.
Calls a command with the arguments given.
This is useful if you want to just call the callback that a Command
holds internally.
Note
This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.
You must take care in passing the proper arguments when using this function.
Changed in version 2.0: command
parameter is now positional-only.
This function is a coroutine.
Calls the command again.
This is similar to invoke()
except that it bypasses checks, cooldowns, and error handlers.
Note
If you want to bypass UserInputError
derived exceptions, it is recommended to use the regular invoke()
as it will work more naturally. After all, this will end up using the old arguments the user has used and will thus just fail again.
ValueError – The context to reinvoke is not valid.
Checks if the invocation context is valid to be invoked with.
The cleaned up invoke prefix. i.e. mentions are @name
instead of <@id>
.
New in version 2.0.
Returns the cog associated with this context’s command. None if it does not exist.
Optional[Cog
]
Returns the maximum number of bytes files can have when uploaded to this guild or DM channel associated with this context.
New in version 2.3.
Returns the guild associated with this context’s command. None if not available.
Optional[Guild
]
Returns the channel associated with this context’s command. Shorthand for Message.channel
.
Union[abc.Messageable
]
Union[User
, Member
]: Returns the author associated with this context’s command. Shorthand for Message.author
Union[Member
, ClientUser
]: Similar to Guild.me
except it may return the ClientUser
in private message contexts.
Returns the resolved permissions for the invoking user in this channel. Shorthand for abc.GuildChannel.permissions_for()
or Interaction.permissions
.
New in version 2.0.
Returns the resolved permissions for the bot in this channel. Shorthand for abc.GuildChannel.permissions_for()
or Interaction.app_permissions
.
For interaction-based commands, this will reflect the effective permissions for Context
calls, which may differ from calls through other abc.Messageable
endpoints, like channel
.
Notably, sending messages, embedding links, and attaching files are always permitted, while reading messages might not be.
New in version 2.0.
A shortcut to Guild.voice_client
, if applicable.
Optional[VoiceProtocol
]
This function is a coroutine.
Shows the help command for the specified entity if given. The entity can be a command or a cog.
If no entity is given, then it’ll show help for the entire bot.
If the entity is a string, then it looks up whether it’s a Cog
or a Command
.
Note
Due to the way this function works, instead of returning something similar to command_not_found()
this returns None
on bad input or no help command.
This function is a coroutine.
Retrieves a single Message
from the destination.
id (int
) – The message ID to look for.
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
The message asked for.
Returns an asynchronous iterator that enables receiving the destination’s message history.
You must have read_message_history
to do this.
Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in channel.history(limit=123)] # messages is now a list of Message...
All parameters are optional.
limit (Optional[int
]) – The number of messages to retrieve. If None
, retrieves every message in the channel. Note, however, that this would make it a slow operation.
before (Optional[Union[Snowflake
, datetime.datetime
]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
after (Optional[Union[Snowflake
, datetime.datetime
]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
around (Optional[Union[Snowflake
, datetime.datetime
]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.
oldest_first (Optional[bool
]) – If set to True
, return messages in oldest->newest order. Defaults to True
if after
is specified, otherwise False
.
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
Message
– The message with the message data parsed.
Retrieves an asynchronous iterator of the pinned messages in the channel.
You must have view_channel
and read_message_history
in order to use this.
Changed in version 2.6: Due to a change in Discord’s API, this now returns a paginated iterator instead of a list.
For backwards compatibility, you can still retrieve a list of pinned messages by using await
on the returned object. This is however deprecated.
Note
Due to a limitation with the Discord API, the Message
object returned by this method does not contain complete Message.reactions
data.
Examples
Usage
counter = 0 async for message in channel.pins(limit=250): counter += 1
Flattening into a list:
messages = [message async for message in channel.pins(limit=50)] # messages is now a list of Message...
All parameters are optional.
limit (Optional[int]) –
The number of pinned messages to retrieve. If None
, it retrieves every pinned message in the channel. Note, however, that this would make it a slow operation. Defaults to 50
.
New in version 2.6.
before (Optional[Union[datetime.datetime
, abc.Snowflake
]]) –
Retrieve pinned messages before this time or snowflake. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
New in version 2.6.
oldest_first (bool
) –
If set to True
, return messages in oldest pin->newest pin order. Defaults to False
.
New in version 2.6.
Forbidden – You do not have the permission to retrieve pinned messages.
HTTPException – Retrieving the pinned messages failed.
Message
– The pinned message with Message.pinned_at
set.
This function is a coroutine.
A shortcut method to send()
to reply to the Message
referenced by this context.
For interaction based contexts, this is the same as send()
.
New in version 1.6.
Changed in version 2.0: This function will now raise TypeError
or ValueError
instead of InvalidArgument
.
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 size
TypeError – You specified both file
and files
.
The message that was sent.
This function is a coroutine.
Defers the interaction based contexts.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
If this isn’t an interaction based context then it does nothing.
ephemeral (bool
) – Indicates whether the deferred message will eventually be ephemeral.
HTTPException – Deferring the interaction failed.
InteractionResponded – This interaction has already been responded to before.
This function is a coroutine.
Sends a message to the destination with the content given.
This works similarly to send()
for non-interaction contexts.
For interaction based contexts this does one of the following:
discord.InteractionResponse.send_message()
if no response has been given.
A followup message if a response has been given.
Regular send if the interaction has expired
Changed in version 2.0: This function will now raise TypeError
or ValueError
instead of InvalidArgument
.
content (Optional[str
]) – The content of the message to send.
tts (bool
) – Indicates if the message should be sent using text-to-speech.
embed (Embed
) – The rich embed for the content.
file (File
) – The file to upload.
files (List[File
]) – A list of files to upload. Must be a maximum of 10.
nonce (int
) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.
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.
allowed_mentions (AllowedMentions
) –
Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions
. If no object is passed at all then the defaults given by allowed_mentions
are used instead.
New in version 1.4.
reference (Union[Message
, MessageReference
, PartialMessage
]) –
A reference to the Message
to which you are replying, this can be created using to_reference()
or passed directly as a Message
. You can control whether this mentions the author of the referenced message using the replied_user
attribute of allowed_mentions
or by setting mention_author
.
This is ignored for interaction based contexts.
New in version 1.6.
mention_author (Optional[bool
]) –
If set, overrides the replied_user
attribute of allowed_mentions
. This is ignored for interaction based contexts.
New in version 1.6.
view (Union[discord.ui.View
, discord.ui.LayoutView
]) –
A Discord UI View to add to the message.
New in version 2.0.
embeds (List[Embed
]) –
A list of embeds to upload. Must be a maximum of 10.
New in version 2.0.
stickers (Sequence[Union[GuildSticker
, StickerItem
]]) –
A list of stickers to upload. Must be a maximum of 3. This is ignored for interaction based contexts.
New in version 2.0.
suppress_embeds (bool
) –
Whether to suppress embeds for the message. This sends the message without any embeds if set to True
.
New in version 2.0.
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. This is only applicable in contexts with an interaction.
New in version 2.0.
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.
poll (Optional[Poll
]) –
The poll to send with this message.
New in version 2.4.
Changed in version 2.6: This can now be None
and defaults to None
instead of MISSING
.
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 size.
TypeError – You specified both file
and files
, or you specified both embed
and embeds
, or the reference
object is not a Message
, MessageReference
or PartialMessage
.
The message that was sent.
The base class of custom converters that require the Context
to be passed to be useful.
This allows you to implement converters that function similar to the special cased discord
classes.
Classes that derive from this should override the convert()
method to do its conversion logic. This method must be a coroutine.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a Object
.
The argument must follow the valid ID or mention formats (e.g. <@80088516616269824>
).
New in version 2.0.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by member, role, or channel mention.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a Member
.
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by username#discriminator (deprecated).
Lookup by username#0 (deprecated, only gets users that migrated from their discriminator).
Lookup by user name.
Lookup by global name.
Lookup by guild nickname.
Changed in version 1.5: Raise MemberNotFound
instead of generic BadArgument
Changed in version 1.5.1: This converter now lazily fetches members from the gateway and HTTP APIs, optionally caching the result if MemberCacheFlags.joined
is enabled.
Deprecated since version 2.3: Looking up users by discriminator will be removed in a future version due to the removal of discriminators in an API change.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a User
.
All lookups are via the global user cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by username#discriminator (deprecated).
Lookup by username#0 (deprecated, only gets users that migrated from their discriminator).
Lookup by user name.
Lookup by global name.
Changed in version 1.5: Raise UserNotFound
instead of generic BadArgument
Changed in version 1.6: This converter now lazily fetches users from the HTTP APIs if an ID is passed and it’s not available in cache.
Deprecated since version 2.3: Looking up users by discriminator will be removed in a future version due to the removal of discriminators in an API change.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a discord.Message
.
New in version 1.1.
The lookup strategy is as follows (in order):
Lookup by “{channel ID}-{message ID}” (retrieved by shift-clicking on “Copy ID”)
Lookup by message ID (the message must be in the context channel)
Lookup by message URL
Changed in version 1.5: Raise ChannelNotFound
, MessageNotFound
or ChannelNotReadable
instead of generic BadArgument
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a discord.PartialMessage
.
New in version 1.7.
The creation strategy is as follows (in order):
By “{channel ID}-{message ID}” (retrieved by shift-clicking on “Copy ID”)
By message ID (The message is assumed to be in the context channel.)
By message URL
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a GuildChannel
.
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by channel URL.
Lookup by name.
New in version 2.0.
Changed in version 2.4: Add lookup by channel URL, accessed via “Copy Link” in the Discord client within channels.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a TextChannel
.
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by channel URL.
Lookup by name
Changed in version 1.5: Raise ChannelNotFound
instead of generic BadArgument
Changed in version 2.4: Add lookup by channel URL, accessed via “Copy Link” in the Discord client within channels.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a VoiceChannel
.
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by channel URL.
Lookup by name
Changed in version 1.5: Raise ChannelNotFound
instead of generic BadArgument
Changed in version 2.4: Add lookup by channel URL, accessed via “Copy Link” in the Discord client within channels.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a StageChannel
.
New in version 1.7.
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by channel URL.
Lookup by name
Changed in version 2.4: Add lookup by channel URL, accessed via “Copy Link” in the Discord client within channels.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a CategoryChannel
.
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by channel URL.
Lookup by name
Changed in version 2.4: Add lookup by channel URL, accessed via “Copy Link” in the Discord client within channels.
Changed in version 1.5: Raise ChannelNotFound
instead of generic BadArgument
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a ForumChannel
.
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by channel URL.
Lookup by name
New in version 2.0.
Changed in version 2.4: Add lookup by channel URL, accessed via “Copy Link” in the Discord client within channels.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a Invite
.
This is done via an HTTP request using Bot.fetch_invite()
.
Changed in version 1.5: Raise BadInviteArgument
instead of generic BadArgument
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a Guild
.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by name. (There is no disambiguation for Guilds with multiple matching names).
New in version 1.7.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a Role
.
All lookups are via the local guild. If in a DM context, the converter raises NoPrivateMessage
exception.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by name
Changed in version 1.5: Raise RoleNotFound
instead of generic BadArgument
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a Game
.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a Colour
.
Changed in version 1.5: Add an alias named ColorConverter
The following formats are accepted:
0x<hex>
#<hex>
0x#<hex>
rgb(<number>, <number>, <number>)
Any of the classmethod
in Colour
The
_
in the name can be optionally replaced with spaces.
Like CSS, <number>
can be either 0-255 or 0-100% and <hex>
can be either a 6 digit hex number or a 3 digit hex shortcut (e.g. #fff).
Changed in version 1.5: Raise BadColourArgument
instead of generic BadArgument
Changed in version 1.7: Added support for rgb
function and 3-digit hex shortcuts
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a Emoji
.
All lookups are done for the local guild first, if available. If that lookup fails, then it checks the client’s global cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by extracting ID from the emoji.
Lookup by name
Changed in version 1.5: Raise EmojiNotFound
instead of generic BadArgument
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a PartialEmoji
.
This is done by extracting the animated flag, name and ID from the emoji.
Changed in version 1.5: Raise PartialEmojiConversionFailure
instead of generic BadArgument
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a Thread
.
All lookups are via the local guild.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by channel URL.
Lookup by name.
Changed in version 2.4: Add lookup by channel URL, accessed via “Copy Link” in the Discord client within channels.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a GuildSticker
.
All lookups are done for the local guild first, if available. If that lookup fails, then it checks the client’s global cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by name.
New in version 2.0.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a ScheduledEvent
.
Lookups are done for the local guild if available. Otherwise, for a DM context, lookup is done by the global cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by url.
Lookup by name.
New in version 2.0.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts to a SoundboardSound
.
Lookups are done for the local guild if available. Otherwise, for a DM context, lookup is done by the global cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by name.
New in version 2.5.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
Converts the argument to mention scrubbed version of said content.
This behaves similarly to clean_content
.
Whether to clean channel mentions.
Whether to use nicknames when transforming mentions.
Whether to also escape special markdown characters.
Whether to also remove special markdown characters. This option is not supported with escape_markdown
New in version 1.7.
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a CommandError
derived exception as it will properly propagate to the error handlers.
Note that if this method is called manually, Exception
should be caught to handle the cases where a subclass does not explicitly inherit from CommandError
.
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.
For example, in the following code:
@commands.command() async def test(ctx, numbers: Greedy[int], reason: str): await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
An invocation of [p]test 1 2 3 4 5 6 hello
would pass numbers
with [1, 2, 3, 4, 5, 6]
and reason
with hello
.
For more information, check Special Converters.
Note
For interaction based contexts the conversion error is propagated rather than swallowed due to the difference in user experience with application commands.
A special converter 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.
Inside a HybridCommand
this functions equivalently to discord.app_commands.Range
.
If the value cannot be converted to the provided type or is outside the given range, BadArgument
or RangeError
is raised to the appropriate error handlers respectively.
New in version 2.0.
Examples
@bot.command() async def range(ctx: commands.Context, value: commands.Range[int, 10, 12]): await ctx.send(f'Your value is {value}')
This function is a coroutine.
Runs converters for a given converter, argument, and parameter.
This function does the same work that the library does under the hood.
New in version 2.0.
CommandError – The converter failed to convert.
The resulting conversion.
Any
A converter that allows for a user-friendly flag syntax.
The flags are defined using PEP 526 type annotations similar to the dataclasses
Python module. For more information on how this converter works, check the appropriate documentation.
Returns an iterator of (flag_name, flag_value)
pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
case_insensitive (bool
) – A class parameter to toggle case insensitivity of the flag parsing. If True
then flags are parsed in a case insensitive manner. Defaults to False
.
prefix (str
) – The prefix that all flags must be prefixed with. By default there is no prefix.
delimiter (str
) – The delimiter that separates a flag’s argument from the flag’s name. By default this is :
.
Represents a flag parameter for FlagConverter
.
The flag()
function helps create these flag objects, but it is not necessary to do so. These cannot be constructed manually.
The name of the flag.
The aliases of the flag name.
List[str
]
The attribute in the class that corresponds to this flag.
The default value of the flag, if available.
Any
The underlying evaluated annotation of the flag.
Any
The maximum number of arguments the flag can accept. A negative value indicates an unlimited amount of arguments.
Whether multiple given values overrides the previous value.
The description of the flag. Shown for hybrid commands when they’re used as application commands.
Whether the flag is positional or not. There can only be one positional flag.
New in version 2.4.
Whether the flag is required.
A required flag has no default value.
Override default functionality and parameters of the underlying FlagConverter
class attributes.
name (str
) – The flag name. If not given, defaults to the attribute name.
aliases (List[str
]) – Aliases to the flag name. If not given no aliases are set.
default (Any) – The default parameter. This could be either a value or a callable that takes Context
as its sole parameter. If not given then it defaults to the default value given to the attribute.
max_args (int
) – The maximum number of arguments the flag can accept. A negative value indicates an unlimited amount of arguments. The default value depends on the annotation given.
override (bool
) – Whether multiple given values overrides the previous value. The default value depends on the annotation given.
converter (Any) – The converter to use for this flag. This replaces the annotation at runtime which is transparent to type checkers.
description (str
) – The description of the flag. Shown for hybrid commands when they’re used as application commands.
positional (bool
) –
Whether the flag is positional or not. There can only be one positional flag.
New in version 2.4.
A class that stores information on a Command
's parameter.
This is a subclass of inspect.Parameter
.
New in version 2.0.
Creates a customized copy of the Parameter.
The parameter’s name.
The parameter’s kind.
The parameter’s default.
The parameter’s annotation.
Whether this parameter is required.
The converter that should be used for this parameter.
The description of this parameter.
Optional[str
]
The displayed default in Command.signature
.
Optional[str
]
The name that is displayed to the user.
New in version 2.3.
Optional[str
]
A way to assign custom metadata for a Command
's parameter.
New in version 2.0.
Examples
A custom default can be used to have late binding behaviour.
@bot.command() async def wave(ctx, to: discord.User = commands.parameter(default=lambda ctx: ctx.author)): await ctx.send(f'Hello {to.mention} :wave:')
converter (Any) – The converter to use for this parameter, this replaces the annotation at runtime which is transparent to type checkers.
default (Any) – The default value for the parameter, if this is a callable or a coroutine it is called with a positional Context
argument.
description (str
) – The description of this parameter.
displayed_default (str
) – The displayed default in Command.signature
.
displayed_name (str
) –
The name that is displayed to the user.
New in version 2.3.
param(*, converter=…, default=…, description=…, displayed_default=…, displayed_name=…)
An alias for parameter()
.
New in version 2.0.
A default Parameter
which returns the author
for this context.
New in version 2.0.
A default Parameter
which returns the channel
for this context.
New in version 2.0.
A default Parameter
which returns the guild
for this context. This will never be None
. If the command is called in a DM context then NoPrivateMessage
is raised to the error handlers.
New in version 2.0.
The base exception type for all 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 a special event from Bot
, on_command_error()
.
Exception raised when a Converter class raises non-CommandError.
This inherits from CommandError
.
The converter that failed.
The original exception that was raised. You can also get this via the __cause__
attribute.
Exception raised when parsing a command and a parameter that is required is not encountered.
This inherits from UserInputError
The argument that is missing.
Exception raised when parsing a command and a parameter that requires an attachment is not given.
This inherits from UserInputError
New in version 2.0.
The argument that is missing an attachment.
An exception raised when the parser fails to parse a user’s input.
This inherits from UserInputError
.
There are child classes that implement more granular parsing errors for i18n purposes.
An exception raised when the parser encounters a quote mark inside a non-quoted string.
This inherits from ArgumentParsingError
.
The quote mark that was found inside the non-quoted string.
An exception raised when a space is expected after the closing quote in a string but a different character is found.
This inherits from ArgumentParsingError
.
The character found instead of the expected string.
An exception raised when a quote character is expected but not found.
This inherits from ArgumentParsingError
.
The quote character expected.
Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command.
This inherits from UserInputError
Exception raised when a typing.Union
converter fails for all its associated types.
This inherits from UserInputError
The parameter that failed being converted.
A tuple of converters attempted in conversion, in order of failure.
Tuple[Type, ...
]
A list of errors that were caught from failing the conversion.
List[CommandError
]
Exception raised when a typing.Literal
converter fails for all its associated values.
This inherits from UserInputError
New in version 2.0.
The parameter that failed being converted.
A tuple of values compared against in conversion, in order of failure.
Tuple[Any, ...
]
A list of errors that were caught from failing the conversion.
List[CommandError
]
The argument’s value that failed to be converted. Defaults to an empty string.
New in version 2.3.
Exception raised when an operation does not work outside of private message contexts.
This inherits from CheckFailure
Exception raised when an operation does not work in private message contexts.
This inherits from CheckFailure
Exception raised when the predicates in Command.checks
have failed.
This inherits from CommandError
Exception raised when all predicates in check_any()
fail.
This inherits from CheckFailure
.
New in version 1.3.
A list of errors that were caught during execution.
List[CheckFailure
]
Exception raised when a command is attempted to be invoked but no command under that name is found.
This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.
This inherits from CommandError
.
Exception raised when the command being invoked is disabled.
This inherits from CommandError
Exception raised when the command being invoked raised an exception.
This inherits from CommandError
The original exception that was raised. You can also get this via the __cause__
attribute.
Exception raised when the command was passed too many arguments and its Command.ignore_extra
attribute was not set to True
.
This inherits from UserInputError
The base exception type for errors that involve errors regarding user input.
This inherits from CommandError
.
Exception raised when the command being invoked is on cooldown.
This inherits from CommandError
A class with attributes rate
and per
similar to the cooldown()
decorator.
The type associated with the cooldown.
The amount of seconds to wait before you can retry again.
Exception raised when the command being invoked has reached its maximum concurrency.
This inherits from CommandError
.
The maximum number of concurrent invokers allowed.
The bucket type passed to the max_concurrency()
decorator.
Exception raised when the message author is not the owner of the bot.
This inherits from CheckFailure
Exception raised when the message provided was not found in the channel.
This inherits from BadArgument
New in version 1.5.
The message supplied by the caller that was not found
Exception raised when the member provided was not found in the bot’s cache.
This inherits from BadArgument
New in version 1.5.
The member supplied by the caller that was not found
Exception raised when the guild provided was not found in the bot’s cache.
This inherits from BadArgument
New in version 1.7.
The guild supplied by the called that was not found
Exception raised when the user provided was not found in the bot’s cache.
This inherits from BadArgument
New in version 1.5.
The user supplied by the caller that was not found
Exception raised when the bot can not find the channel.
This inherits from BadArgument
New in version 1.5.
Exception raised when the bot does not have permission to read messages in the channel.
This inherits from BadArgument
New in version 1.5.
The channel supplied by the caller that was not readable
Union[abc.GuildChannel
, Thread
]
Exception raised when the bot can not find the thread.
This inherits from BadArgument
New in version 2.0.
The thread supplied by the caller that was not found
Exception raised when the colour is not valid.
This inherits from BadArgument
New in version 1.5.
The colour supplied by the caller that was not valid
Exception raised when the bot can not find the role.
This inherits from BadArgument
New in version 1.5.
The role supplied by the caller that was not found
Exception raised when the invite is invalid or expired.
This inherits from BadArgument
New in version 1.5.
The invite supplied by the caller that was not valid
Exception raised when the bot can not find the emoji.
This inherits from BadArgument
New in version 1.5.
The emoji supplied by the caller that was not found
Exception raised when the emoji provided does not match the correct format.
This inherits from BadArgument
New in version 1.5.
The emoji supplied by the caller that did not match the regex
Exception raised when the bot can not find the sticker.
This inherits from BadArgument
New in version 2.0.
The sticker supplied by the caller that was not found
Exception raised when the bot can not find the scheduled event.
This inherits from BadArgument
New in version 2.0.
The event supplied by the caller that was not found
Exception raised when the bot can not find the soundboard sound.
This inherits from BadArgument
New in version 2.5.
The sound supplied by the caller that was not found
Exception raised when a boolean argument was not convertable.
This inherits from BadArgument
New in version 1.5.
The boolean argument supplied by the caller that is not in the predefined list
Exception raised when an argument is out of range.
This inherits from BadArgument
New in version 2.0.
Exception raised when the command invoker lacks permissions to run a command.
This inherits from CheckFailure
The required permissions that are missing.
List[str
]
Exception raised when the bot’s member lacks permissions to run a command.
This inherits from CheckFailure
The required permissions that are missing.
List[str
]
Exception raised when the command invoker lacks a role to run a command.
This inherits from CheckFailure
New in version 1.1.
The required role that is missing. This is the parameter passed to has_role()
.
Exception raised when the bot’s member lacks a role to run a command.
This inherits from CheckFailure
New in version 1.1.
The required role that is missing. This is the parameter passed to has_role()
.
Exception raised when the command invoker lacks any of the roles specified to run a command.
This inherits from CheckFailure
New in version 1.1.
The roles that the invoker is missing. These are the parameters passed to has_any_role()
.
Exception raised when the bot’s member lacks any of the roles specified to run a command.
This inherits from CheckFailure
New in version 1.1.
The roles that the bot’s member is missing. These are the parameters passed to has_any_role()
.
Exception raised when a channel does not have the required NSFW setting.
This inherits from CheckFailure
.
New in version 1.1.
The channel that does not have NSFW enabled.
Union[abc.GuildChannel
, Thread
]
The base exception type for all flag parsing related errors.
This inherits from BadArgument
.
New in version 2.0.
An exception raised when a flag failed to convert a value.
This inherits from FlagError
New in version 2.0.
The flag that failed to convert.
The argument supplied by the caller that was not able to be converted.
The original exception that was raised. You can also get this via the __cause__
attribute.
An exception raised when a flag did not get a value.
This inherits from FlagError
New in version 2.0.
The flag that did not get a value.
An exception raised when a flag has received too many values.
This inherits from FlagError
.
New in version 2.0.
The flag that received too many values.
The values that were passed.
List[str
]
An exception raised when a required flag was not given.
This inherits from FlagError
New in version 2.0.
The required flag that was not found.
Base exception for extension related errors.
This inherits from DiscordException
.
The extension that had an error.
An exception raised when an extension has already been loaded.
This inherits from ExtensionError
An exception raised when an extension was not loaded.
This inherits from ExtensionError
An exception raised when an extension does not have a setup
entry point function.
This inherits from ExtensionError
An exception raised when an extension failed to load during execution of the module or setup
entry point.
This inherits from ExtensionError
The extension that had the error.
The original exception that was raised. You can also get this via the __cause__
attribute.
An exception raised when an extension is not found.
This inherits from ExtensionError
Changed in version 1.3: Made the original
attribute always None.
The extension that had the error.
An exception raised when the command can’t be added because the name is already taken by a different command.
This inherits from discord.ClientException
New in version 1.4.
The command name that had the error.
Whether the name that conflicts is an alias of the command we try to add.
An exception raised when a HybridCommand
raises an AppCommandError
derived exception that could not be sufficiently converted to an equivalent CommandError
exception.
New in version 2.0.
The original exception that was raised. You can also get this via the __cause__
attribute.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4