The following section outlines the API of discord.py’s command extension module.
Bots¶
Bot¶
Attributes
- activity
- allowed_mentions
- application
- application_flags
- application_id
- cached_messages
- case_insensitive
- cogs
- command_prefix
- commands
- description
- emojis
- extensions
- guilds
- help_command
- intents
- latency
- owner_id
- owner_ids
- persistent_views
- private_channels
- status
- stickers
- strip_after_prefix
- tree
- tree_cls
- user
- users
- voice_clients
Methods
-
defadd_check -
asyncadd_cog -
defadd_command -
defadd_listener -
defadd_view -
@after_invoke -
asyncapplication_info -
asyncbefore_identify_hook -
@before_invoke -
asyncchange_presence -
@check -
@check_once -
defclear -
asyncclose -
@command -
asyncconnect -
asynccreate_dm -
asynccreate_guild -
asyncdelete_invite -
@event -
asyncfetch_channel -
asyncfetch_guild -
async forfetch_guilds -
asyncfetch_invite -
asyncfetch_premium_sticker_packs -
asyncfetch_stage_instance -
asyncfetch_sticker -
asyncfetch_template -
asyncfetch_user -
asyncfetch_webhook -
asyncfetch_widget -
defget_all_channels -
defget_all_members -
defget_channel -
defget_cog -
defget_command -
asyncget_context -
defget_emoji -
defget_guild -
defget_partial_messageable -
asyncget_prefix -
defget_stage_instance -
defget_sticker -
defget_user -
@group -
@hybrid_command -
@hybrid_group -
asyncinvoke -
defis_closed -
asyncis_owner -
defis_ready -
defis_ws_ratelimited -
@listen -
asyncload_extension -
asynclogin -
asyncon_command_error -
asyncon_error -
asyncprocess_commands -
asyncreload_extension -
defremove_check -
asyncremove_cog -
defremove_command -
defremove_listener -
defrun -
asyncsetup_hook -
asyncstart -
asyncunload_extension -
asyncwait_for -
asyncwait_until_ready -
defwalk_commands
- class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class ‘discord.app_commands.tree.CommandTree’>, description=None, intents, **options)¶
-
Represents a Discord bot.
This class is a subclass of
discord.Client
and as a result
anything that you can do with adiscord.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
aCommandTree
and is automatically set upon
instantiating the class.- async with x
-
Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
- command_prefix¶
-
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 anddiscord.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.
- case_insensitive¶
-
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.- Type
-
bool
- description¶
-
The content prefixed into the default help message.
- Type
-
str
- help_command¶
-
The help command implementation to use. This can be dynamically
set at runtime. To remove the help command passNone
. For more
information on implementing a help command, see Help Commands.- Type
-
Optional[
HelpCommand
]
- owner_id¶
-
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()
.- Type
-
Optional[
int
]
- owner_ids¶
-
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 usingapplication_info()
.
For performance reasons it is recommended to use aset
for the collection. You cannot set bothowner_id
andowner_ids
.New in version 1.3.
- Type
-
Optional[Collection[
int
]]
- strip_after_prefix¶
-
Whether to strip whitespace characters after encountering the command
prefix. This allows for! hello
and!hello
to both work if
thecommand_prefix
is set to!
. Defaults toFalse
.New in version 1.7.
- Type
-
bool
- tree_cls¶
-
The type of application command tree to use. Defaults to
CommandTree
.New in version 2.0.
- Type
-
Type[
CommandTree
]
- @after_invoke¶
-
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.- Parameters
-
coro (coroutine) – The coroutine to register as the post-invoke hook.
- Raises
-
TypeError – The coroutine passed is not actually a coroutine.
- @before_invoke¶
-
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()
andafter_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.- Parameters
-
coro (coroutine) – The coroutine to register as the pre-invoke hook.
- Raises
-
TypeError – The coroutine passed is not actually a coroutine.
- @check¶
-
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 typeContext
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.
- @check_once¶
-
A decorator that adds a “call once” global check to the bot.
Unlike regular global checks, this one is called only once
perinvoke()
call.Regular global checks are called whenever a command is called
orCommand.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 perBot.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 typeContext
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.
- @command(*args, **kwargs)¶
-
A shortcut decorator that invokes
command()
and adds it to
the internal command list viaadd_command()
.- Returns
-
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
- Return type
-
Callable[…,
Command
]
- @event¶
-
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.- Raises
-
TypeError – The coroutine passed is not actually a coroutine.
- @group(*args, **kwargs)¶
-
A shortcut decorator that invokes
group()
and adds it to
the internal command list viaadd_command()
.- Returns
-
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
- Return type
-
Callable[…,
Group
]
- @hybrid_command(name=…, with_app_command=True, *args, **kwargs)¶
-
A shortcut decorator that invokes
hybrid_command()
and adds it to
the internal command list viaadd_command()
.- Returns
-
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
- Return type
-
Callable[…,
HybridCommand
]
- @hybrid_group(name=…, with_app_command=True, *args, **kwargs)¶
-
A shortcut decorator that invokes
hybrid_group()
and adds it to
the internal command list viaadd_command()
.- Returns
-
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
- Return type
-
Callable[…,
HybridGroup
]
- @listen(name=None)¶
-
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 ason_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.
- Raises
-
TypeError – The function being listened to is not a coroutine.
- property activity¶
-
The activity being used upon
logging in.- Type
-
Optional[
BaseActivity
]
- add_check(func, /, *, call_once=False)¶
-
Adds a global check to the bot.
This is the non-decorator interface to
check()
andcheck_once()
.Changed in version 2.0:
func
parameter is now positional-only.See also
The
check()
decorator- Parameters
-
-
func – The function that was used as a global check.
-
call_once (
bool
) – If the function should only be called once per
invoke()
call.
-
- await add_cog(cog, /, *, override=False, guild=…, guilds=…)¶
-
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’sCommandTree
as well.Note
Exceptions raised inside a
Cog
’scog_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.
- Parameters
-
-
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.
-
- Raises
-
-
TypeError – The cog does not inherit from
Cog
. -
CommandError – An error happened during loading.
-
ClientException – A cog with the same name is already loaded.
-
- add_command(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 genericClientException
Changed in version 2.0:
command
parameter is now positional-only.- Parameters
-
command (
Command
) – The command to add. - Raises
-
-
CommandRegistrationError – If the command or its alias is already registered by different command.
-
TypeError – If the command passed is not a subclass of
Command
.
-
- add_listener(func, /, name=…)¶
-
The non decorator alternative to
listen()
.Changed in version 2.0:
func
parameter is now positional-only.- Parameters
-
-
func (coroutine) – The function to call.
-
name (
str
) – The name of the event to listen for. Defaults tofunc.__name__
.
-
Example
async def on_ready(): pass async def my_message(message): pass bot.add_listener(on_ready) bot.add_listener(my_message, 'on_message')
- add_view(view, *, message_id=None)¶
-
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.
- Parameters
-
-
view (
discord.ui.View
) – 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.
-
- Raises
-
-
TypeError – A view was not passed.
-
ValueError – The view is not persistent. A persistent view has no timeout
and all their components have an explicitly provided custom_id.
-
- property allowed_mentions¶
-
The allowed mention configuration.
New in version 1.4.
- Type
-
Optional[
AllowedMentions
]
- property application¶
-
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 beforelogin()
is called.New in version 2.0.
- Type
-
Optional[
AppInfo
]
- property application_flags¶
-
The client’s application flags.
New in version 2.0.
- Type
-
ApplicationFlags
- property application_id¶
-
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
tologin()
. Usually afteron_connect()
is called.New in version 2.0.
- Type
-
Optional[
int
]
- await application_info()¶
-
This function is a coroutine.
Retrieves the bot’s application information.
- Raises
-
HTTPException – Retrieving the information failed somehow.
- Returns
-
The bot’s application information.
- Return type
-
AppInfo
- await before_identify_hook(shard_id, *, initial=False)¶
-
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.
- Parameters
-
-
shard_id (
int
) – The shard ID that requested being IDENTIFY’d -
initial (
bool
) – Whether this IDENTIFY is the first initial IDENTIFY.
-
- property cached_messages¶
-
Read-only list of messages the connected client has cached.
New in version 1.1.
- Type
-
Sequence[
Message
]
- await change_presence(*, activity=None, status=None)¶
-
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
.- Parameters
-
-
activity (Optional[
BaseActivity
]) – The activity being done.None
if no currently active activity is done. -
status (Optional[
Status
]) – Indicates what status to change to. IfNone
, then
Status.online
is used.
-
- Raises
-
TypeError – If the
activity
parameter is not the proper type.
- clear()¶
-
Clears the internal state of the bot.
After this, the bot can be considered “re-opened”, i.e.
is_closed()
andis_ready()
both returnFalse
along with the bot’s internal
cache cleared.
- await close()¶
-
This function is a coroutine.
Closes the connection to Discord.
- property cogs¶
-
A read-only mapping of cog name to cog.
- Type
-
Mapping[
str
,Cog
]
- property commands¶
-
A unique set of commands without aliases that are registered.
- Type
-
Set[
Command
]
- await connect(*, reconnect=True)¶
-
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.- Parameters
-
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). - Raises
-
-
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.
-
- await create_dm(user)¶
-
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.
- Parameters
-
user (
Snowflake
) – The user to create a DM with. - Returns
-
The channel that was created.
- Return type
-
DMChannel
- await create_guild(*, name, icon=…, code=…)¶
-
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
andicon
parameters are now keyword-only. Theregion
parameter has been removed.Changed in version 2.0: This function will now raise
ValueError
instead of
InvalidArgument
.- Parameters
-
-
name (
str
) – The name of the guild. -
icon (Optional[
bytes
]) – The bytes-like object representing the icon. SeeClientUser.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.
-
- Raises
-
-
HTTPException – Guild creation failed.
-
ValueError – Invalid icon image format given. Must be PNG or JPG.
-
- Returns
-
The guild created. This is not the same guild that is
added to cache. - Return type
-
Guild
- await delete_invite(invite, /)¶
-
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.- Parameters
-
invite (Union[
Invite
,str
]) – The invite to revoke. - Raises
-
-
Forbidden – You do not have permissions to revoke invites.
-
NotFound – The invite is invalid or expired.
-
HTTPException – Revoking the invite failed.
-
- property emojis¶
-
The emojis that the connected client has.
- Type
-
Sequence[
Emoji
]
- property extensions¶
-
A read-only mapping of extension name to extension.
- Type
-
Mapping[
str
,types.ModuleType
]
- await fetch_channel(channel_id, /)¶
-
This function is a coroutine.
Retrieves a
abc.GuildChannel
,abc.PrivateChannel
, orThread
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.- Raises
-
-
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.
-
- Returns
-
The channel from the ID.
- Return type
-
Union[
abc.GuildChannel
,abc.PrivateChannel
,Thread
]
- await fetch_guild(guild_id, /, *, with_counts=True)¶
-
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.- Parameters
-
-
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
andGuild.approximate_presence_count
attributes without needing any privileged intents. Defaults toTrue
.New in version 2.0.
-
- Raises
-
-
Forbidden – You do not have access to the guild.
-
HTTPException – Getting the guild failed.
-
- Returns
-
The guild from the ID.
- Return type
-
Guild
- async for … in fetch_guilds(*, limit=200, before=None, after=None)¶
-
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.
- Parameters
-
-
limit (Optional[
int
]) –The number of guilds to retrieve.
IfNone
, it retrieves every guild you have access to. Note, however,
that this would make it a slow operation.
Defaults to200
.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.
-
- Raises
-
HTTPException – Getting the guilds failed.
- Yields
-
Guild
– The guild with the guild data parsed.
- await fetch_invite(url, *, with_counts=True, with_expiration=True, scheduled_event_id=None)¶
-
This function is a coroutine.
Gets an
Invite
from a discord.gg URL or ID.- Parameters
-
-
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
andInvite.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.
-
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.
-
- Raises
-
-
ValueError – The url contains an
event_id
, butscheduled_event_id
has also been provided. -
NotFound – The invite has expired or is invalid.
-
HTTPException – Getting the invite failed.
-
- Returns
-
The invite from the URL/ID.
- Return type
-
Invite
- await fetch_premium_sticker_packs()¶
-
This function is a coroutine.
Retrieves all available premium sticker packs.
New in version 2.0.
- Raises
-
HTTPException – Retrieving the sticker packs failed.
- Returns
-
All available premium sticker packs.
- Return type
-
List[
StickerPack
]
- await fetch_stage_instance(channel_id, /)¶
-
This function is a coroutine.
Gets a
StageInstance
for a stage channel id.New in version 2.0.
- Parameters
-
channel_id (
int
) – The stage channel ID. - Raises
-
-
NotFound – The stage instance or channel could not be found.
-
HTTPException – Getting the stage instance failed.
-
- Returns
-
The stage instance from the stage channel ID.
- Return type
-
StageInstance
- await fetch_sticker(sticker_id, /)¶
-
This function is a coroutine.
Retrieves a
Sticker
with the specified ID.New in version 2.0.
- Raises
-
-
HTTPException – Retrieving the sticker failed.
-
NotFound – Invalid sticker ID.
-
- Returns
-
The sticker you requested.
- Return type
-
Union[
StandardSticker
,GuildSticker
]
- await fetch_template(code)¶
-
This function is a coroutine.
Gets a
Template
from a discord.new URL or code.- Parameters
-
code (Union[
Template
,str
]) – The Discord Template Code or URL (must be a discord.new URL). - Raises
-
-
NotFound – The template is invalid.
-
HTTPException – Getting the template failed.
-
- Returns
-
The template from the URL/code.
- Return type
-
Template
- await fetch_user(user_id, /)¶
-
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.- Parameters
-
user_id (
int
) – The user’s ID to fetch from. - Raises
-
-
NotFound – A user with this ID does not exist.
-
HTTPException – Fetching the user failed.
-
- Returns
-
The user you requested.
- Return type
-
User
- await fetch_webhook(webhook_id, /)¶
-
This function is a coroutine.
Retrieves a
Webhook
with the specified ID.Changed in version 2.0:
webhook_id
parameter is now positional-only.- Raises
-
-
HTTPException – Retrieving the webhook failed.
-
NotFound – Invalid webhook ID.
-
Forbidden – You do not have permission to fetch this webhook.
-
- Returns
-
The webhook you requested.
- Return type
-
Webhook
- await fetch_widget(guild_id, /)¶
-
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.- Parameters
-
guild_id (
int
) – The ID of the guild. - Raises
-
-
Forbidden – The widget for this guild is disabled.
-
HTTPException – Retrieving the widget failed.
-
- Returns
-
The guild’s widget.
- Return type
-
Widget
- for … in get_all_channels()¶
-
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
- Yields
-
abc.GuildChannel
– A channel the client can ‘access’.
- for … in get_all_members()¶
-
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
- Yields
-
Member
– A member the client can see.
- get_channel(id, /)¶
-
Returns a channel or thread with the given ID.
Changed in version 2.0:
id
parameter is now positional-only.- Parameters
-
id (
int
) – The ID to search for. - Returns
-
The returned channel or
None
if not found. - Return type
-
Optional[Union[
abc.GuildChannel
,Thread
,abc.PrivateChannel
]]
- get_cog(name, /)¶
-
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.- Parameters
-
name (
str
) – The name of the cog you are requesting.
This is equivalent to the name passed via keyword
argument in class creation or the class name if unspecified. - Returns
-
The cog that was requested. If not found, returns
None
. - Return type
-
Optional[
Cog
]
- get_command(name, /)¶
-
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 subcommandbar
of the group commandfoo
. If a
subcommand is not found thenNone
is returned just as usual.Changed in version 2.0:
name
parameter is now positional-only.- Parameters
-
name (
str
) – The name of the command to get. - Returns
-
The command that was requested. If not found, returns
None
. - Return type
-
Optional[
Command
]
- await get_context(origin, /, *, cls=…)¶
-
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 underinvoke()
.Note
In order for the custom context to be used inside an interaction-based
context (such asHybridCommand
) then this method must be
overridden to return that class.Changed in version 2.0:
message
parameter is now positional-only and renamed toorigin
.- Parameters
-
-
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 isContext
. Should a custom
class be provided, it must be similar enough toContext
‘s
interface.
-
- Returns
-
The invocation context. The type of this can change via the
cls
parameter. - Return type
-
Context
- get_emoji(id, /)¶
-
Returns an emoji with the given ID.
Changed in version 2.0:
id
parameter is now positional-only.- Parameters
-
id (
int
) – The ID to search for. - Returns
-
The custom emoji or
None
if not found. - Return type
-
Optional[
Emoji
]
- get_guild(id, /)¶
-
Returns a guild with the given ID.
Changed in version 2.0:
id
parameter is now positional-only.- Parameters
-
id (
int
) – The ID to search for. - Returns
-
The guild or
None
if not found. - Return type
-
Optional[
Guild
]
- get_partial_messageable(id, *, guild_id=None, type=None)¶
-
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.
- Parameters
-
-
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.
-
- Returns
-
The partial messageable
- Return type
-
PartialMessageable
- await get_prefix(message, /)¶
-
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.- Parameters
-
message (
discord.Message
) – The message context to get the prefix of. - Returns
-
A list of prefixes or a single prefix that the bot is
listening for. - Return type
-
Union[List[
str
],str
]
- get_stage_instance(id, /)¶
-
Returns a stage instance with the given stage channel ID.
New in version 2.0.
- Parameters
-
id (
int
) – The ID to search for. - Returns
-
The stage instance or
None
if not found. - Return type
-
Optional[
StageInstance
]
- get_sticker(id, /)¶
-
Returns a guild sticker with the given ID.
New in version 2.0.
Note
To retrieve standard stickers, use
fetch_sticker()
.
orfetch_premium_sticker_packs()
.- Returns
-
The sticker or
None
if not found. - Return type
-
Optional[
GuildSticker
]
- get_user(id, /)¶
-
Returns a user with the given ID.
Changed in version 2.0:
id
parameter is now positional-only.- Parameters
-
id (
int
) – The ID to search for. - Returns
-
The user or
None
if not found. - Return type
-
Optional[
User
]
- property guilds¶
-
The guilds that the connected client is a member of.
- Type
-
Sequence[
Guild
]
- property intents¶
-
The intents configured for this connection.
New in version 1.5.
- Type
-
Intents
- await invoke(ctx, /)¶
-
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.- Parameters
-
ctx (
Context
) – The invocation context to invoke.
- is_closed()¶
-
bool
: Indicates if the websocket connection is closed.
- await is_owner(user, /)¶
-
This function is a coroutine.
Checks if a
User
orMember
is the owner of
this bot.If an
owner_id
is not set, it is fetched automatically
through the use ofapplication_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.- Parameters
-
user (
abc.User
) – The user to check for. - Returns
-
Whether the user is the owner.
- Return type
-
bool
- is_ready()¶
-
bool
: Specifies if the client’s internal cache is ready for use.
- is_ws_ratelimited()¶
-
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.
- property latency¶
-
Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
- Type
-
float
- await load_extension(name, *, package=None)¶
-
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, thebot
.Changed in version 2.0: This method is now a coroutine.
- Parameters
-
-
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 importfoo/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 toNone
.New in version 1.7.
-
- Raises
-
-
ExtensionNotFound – The extension could not be imported.
This is also raised if the name of the extension could not
be resolved using the providedpackage
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.
-
- await login(token)¶
-
This function is a coroutine.
Logs in the client with the specified credentials and
calls thesetup_hook()
.- Parameters
-
token (
str
) – The authentication token. Do not prefix this token with
anything as the library will do it for you. - Raises
-
-
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.
-
- await on_command_error(context, exception, /)¶
-
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
andexception
parameters are now positional-only.
Instead of writing tosys.stderr
this now uses the library logger.
- await on_error(event_method, /, *args, **kwargs)¶
-
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.
Checkon_error()
for more details.Changed in version 2.0:
event_method
parameter is now positional-only
and instead of writing tosys.stderr
it logs instead.
- property persistent_views¶
-
A sequence of persistent views added to the client.
New in version 2.0.
- Type
-
Sequence[
View
]
- property private_channels¶
-
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.- Type
-
Sequence[
abc.PrivateChannel
]
- await process_commands(message, /)¶
-
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 theon_message()
event, then
you should invoke this coroutine as well.This is built using other low level tools, and is equivalent to a
call toget_context()
followed by a call toinvoke()
.This also checks if the message’s author is a bot and doesn’t
callget_context()
orinvoke()
if so.Changed in version 2.0:
message
parameter is now positional-only.- Parameters
-
message (
discord.Message
) – The message to process commands for.
- await reload_extension(name, *, package=None)¶
-
This function is a coroutine.
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is
equivalent to aunload_extension()
followed by aload_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.- Parameters
-
-
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 importfoo/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 toNone
.New in version 1.7.
-
- Raises
-
-
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 providedpackage
parameter. -
NoEntryPointError – The extension does not have a setup function.
-
ExtensionFailed – The extension setup function had an execution error.
-
- remove_check(func, /, *, call_once=False)¶
-
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.- Parameters
-
-
func – The function to remove from the global checks.
-
call_once (
bool
) – If the function was added withcall_once=True
in
theBot.add_check()
call or usingcheck_once()
.
-
- await remove_cog(name, /, *, guild=…, guilds=…)¶
-
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.
- Parameters
-
-
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.
-
- Returns
-
The cog that was removed.
None
if not found. - Return type
-
Optional[
Cog
]
- remove_command(name, /)¶
-
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.- Parameters
-
name (
str
) – The name of the command to remove. - Returns
-
The command that was removed. If the name is not valid then
None
is returned instead. - Return type
-
Optional[
Command
]
- remove_listener(func, /, name=…)¶
-
Removes a listener from the pool of listeners.
Changed in version 2.0:
func
parameter is now positional-only.- Parameters
-
-
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__
.
-
- run(token, *, reconnect=True, log_handler=…, log_formatter=…, log_level=…, root_logger=False)¶
-
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. Usestart()
coroutine
orconnect()
+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 passingNone
to
thelog_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.- Parameters
-
-
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 ifNone
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 notNone
. Defaults tologging.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 toTrue
then the root logger is set up as well.Defaults to
False
.New in version 2.0.
-
- await setup_hook()¶
-
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 theon_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
likewait_for()
andwait_until_ready()
.New in version 2.0.
- await start(token, *, reconnect=True)¶
-
This function is a coroutine.
A shorthand coroutine for
login()
+connect()
.- Parameters
-
-
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).
-
- Raises
-
TypeError – An unexpected keyword argument was received.
- property status¶
-
Status
:
The status being used upon logging on to Discord.
- property stickers¶
-
The stickers that the connected client has.
New in version 2.0.
- Type
-
Sequence[
GuildSticker
]
- property tree¶
-
The command tree responsible for handling the application commands
in this bot.New in version 2.0.
- Type
-
CommandTree
- await unload_extension(name, *, package=None)¶
-
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, thebot
, similar tosetup
from
load_extension()
.Changed in version 2.0: This method is now a coroutine.
- Parameters
-
-
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 importfoo/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 toNone
.New in version 1.7.
-
- Raises
-
-
ExtensionNotFound – The name of the extension could not
be resolved using the providedpackage
parameter. -
ExtensionNotLoaded – The extension was not loaded.
-
- property user¶
-
Represents the connected client.
None
if not logged in.- Type
-
Optional[
ClientUser
]
- property users¶
-
Returns a list of all the users the bot can see.
- Type
-
List[
User
]
- property voice_clients¶
-
Represents a list of voice connections.
These are usually
VoiceClient
instances.- Type
-
List[
VoiceProtocol
]
- wait_for(event, /, *, check=None, timeout=None)¶
-
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 ontoasyncio.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.- Parameters
-
-
event (
str
) – The event name, similar to the event reference,
but without theon_
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
.
-
- Raises
-
asyncio.TimeoutError – If a timeout is provided and it was reached.
- Returns
-
Returns no arguments, a single argument, or a
tuple
of multiple
arguments that mirrors the parameters passed in the
event reference. - Return type
-
Any
- await wait_until_ready()¶
-
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.
- for … in walk_commands()¶
-
An iterator that recursively walks through all commands and subcommands.
Changed in version 1.4: Duplicates due to aliases are no longer returned
- Yields
-
Union[
Command
,Group
] – A command or group from the internal list of commands.
AutoShardedBot¶
- class discord.ext.commands.AutoShardedBot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class ‘discord.app_commands.tree.CommandTree’>, description=None, intents, **options)¶
-
This is similar to
Bot
except that it is inherited from
discord.AutoShardedClient
instead.- async with x
-
Asynchronously initialises the bot and automatically cleans.
New in version 2.0.
Prefix Helpers¶
- discord.ext.commands.when_mentioned(bot, msg, /)¶
-
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.
- discord.ext.commands.when_mentioned_or(*prefixes)¶
-
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)
See also
when_mentioned()
Event Reference¶
These events function similar to the regular events, except they
are custom to the command extension module.
- discord.ext.commands.on_command_error(ctx, error)¶
-
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()
).- Parameters
-
-
ctx (
Context
) – The invocation context. -
error (
CommandError
derived) – The error that was raised.
-
- discord.ext.commands.on_command(ctx)¶
-
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.- Parameters
-
ctx (
Context
) – The invocation context.
- discord.ext.commands.on_command_completion(ctx)¶
-
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.- Parameters
-
ctx (
Context
) – The invocation context.
Commands¶
Decorators¶
- @discord.ext.commands.command(name=…, cls=…, **attrs)¶
-
A decorator that transforms a function into a
Command
or if called withgroup()
,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 isbytes
, then it is decoded
intostr
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.- Parameters
-
-
name (
str
) – The name to create the command with. By default this uses the
function name unchanged. -
cls – The class to construct with. By default this is
Command
.
You usually do not change this. -
attrs – Keyword arguments to pass into the construction of the class denoted
bycls
.
-
- Raises
-
TypeError – If the function is not a coroutine or is already a command.
- @discord.ext.commands.group(name=…, cls=…, **attrs)¶
-
A decorator that transforms a function into a
Group
.This is similar to the
command()
decorator but thecls
parameter is set toGroup
by default.Changed in version 1.1: The
cls
parameter can now be passed.
- @discord.ext.commands.hybrid_command(name=…, *, with_app_command=True, **attrs)¶
-
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 aapp_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 toCommand
. This means that they takeContext
as
a parameter rather thandiscord.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.
- Parameters
-
-
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.
-
- Raises
-
TypeError – If the function is not a coroutine or is already a command.
- @discord.ext.commands.hybrid_group(name=…, *, with_app_command=True, **attrs)¶
-
A decorator that transforms a function into a
HybridGroup
.This is similar to the
group()
decorator except it creates
a hybrid group instead.- Parameters
-
with_app_command (
bool
) – Whether to register the command also as an application command. - Raises
-
TypeError – If the function is not a coroutine or is already a command.
Command¶
Attributes
- aliases
- brief
- callback
- checks
- clean_params
- cog
- cog_name
- cooldown
- cooldown_after_parsing
- description
- enabled
- extras
- full_parent_name
- help
- hidden
- ignore_extra
- invoked_subcommand
- name
- parent
- parents
- qualified_name
- require_var_positional
- rest_is_raw
- root_parent
- short_doc
- signature
- usage
Methods
-
async__call__ -
defadd_check -
@after_invoke -
@before_invoke -
asynccan_run -
defcopy -
@error -
defget_cooldown_retry_after -
defhas_error_handler -
defis_on_cooldown -
defremove_check -
defreset_cooldown -
defupdate
- class discord.ext.commands.Command(*args, **kwargs)¶
-
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.- name¶
-
The name of the command.
- Type
-
str
- callback¶
-
The coroutine that is executed when the command is called.
- Type
-
coroutine
- help¶
-
The long help text for the command.
- Type
-
Optional[
str
]
- brief¶
-
The short help text for the command.
- Type
-
Optional[
str
]
- usage¶
-
A replacement for arguments in the default help text.
- Type
-
Optional[
str
]
- aliases¶
-
The list of aliases the command can be invoked under.
- Type
-
Union[List[
str
], Tuple[str
]]
- enabled¶
-
A boolean that indicates if the command is currently enabled.
If the command is invoked while it is disabled, then
DisabledCommand
is raised to theon_command_error()
event. Defaults toTrue
.- Type
-
bool
- parent¶
-
The parent group that this command belongs to.
None
if there
isn’t one.- Type
-
Optional[
Group
]
- cog¶
-
The cog that this command belongs to.
None
if there isn’t one.- Type
-
Optional[
Cog
]
- checks¶
-
A list of predicates that verifies if the command could be executed
with the givenContext
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 theon_command_error()
event.- Type
-
List[Callable[[
Context
],bool
]]
- description¶
-
The message prefixed into the default help command.
- Type
-
str
- hidden¶
-
If
True
, the default help command does not show this in the
help output.- Type
-
bool
- rest_is_raw¶
-
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 handlesMissingRequiredArgument
and default values in a
regular matter rather than passing the rest completely raw. IfTrue
then the keyword-only argument will pass in the rest of the arguments
in a completely raw matter. Defaults toFalse
.- Type
-
bool
- invoked_subcommand¶
-
The subcommand that was invoked, if any.
- Type
-
Optional[
Command
]
- require_var_positional¶
-
If
True
and a variadic positional argument is specified, requires
the user to specify at least one argument. Defaults toFalse
.New in version 1.5.
- Type
-
bool
- ignore_extra¶
-
If
True
, ignores extraneous strings passed to a command if all its
requirements are met (e.g.?foo a b c
when only expectinga
andb
). Otherwiseon_command_error()
and local error handlers
are called withTooManyArguments
. Defaults toTrue
.- Type
-
bool
- cooldown_after_parsing¶
-
If
True
, cooldown processing is done after argument parsing,
which calls converters. IfFalse
then cooldown processing is done
first and then the converters are called second. Defaults toFalse
.- Type
-
bool
- extras¶
-
A dict of user provided extras to attach to the Command.
Note
This object may be copied by the library.
- Type
-
dict
New in version 2.0.
- @after_invoke¶
-
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.- Parameters
-
coro (coroutine) – The coroutine to register as the post-invoke hook.
- Raises
-
TypeError – The coroutine passed is not actually a coroutine.
- @before_invoke¶
-
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.- Parameters
-
coro (coroutine) – The coroutine to register as the pre-invoke hook.
- Raises
-
TypeError – The coroutine passed is not actually a coroutine.
- @error¶
-
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, theon_command_error()
is still
invoked afterwards as the catch-all.Changed in version 2.0:
coro
parameter is now positional-only.- Parameters
-
coro (coroutine) – The coroutine to register as the local error handler.
- Raises
-
TypeError – The coroutine passed is not actually a coroutine.
- add_check(func, /)¶
-
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.See also
The
check()
decorator- Parameters
-
func – The function that will be used as a check.
- remove_check(func, /)¶
-
Removes a check from the command.
This function is idempotent and will not raise an exception
if the function is not in the command’s checks.New in version 1.3.
Changed in version 2.0:
func
parameter is now positional-only.- Parameters
-
func – The function to remove from the checks.
- update(**kwargs)¶
-
Updates
Command
instance with updated attribute.This works similarly to the
command()
decorator in terms
of parameters in that they are passed to theCommand
or
subclass constructors, sans the name and callback.
- await __call__(context, /, *args, **kwargs)¶
-
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.
- copy()¶
-
Creates a copy of this command.
- Returns
-
A new instance of this command.
- Return type
-
Command
- property clean_params¶
-
Dict[
str
,Parameter
]:
Retrieves the parameter dictionary without the context or self parameters.Useful for inspecting signature.
- property cooldown¶
-
The cooldown of a command when invoked
orNone
if the command doesn’t have a registered cooldown.New in version 2.0.
- Type
-
Optional[
Cooldown
]
- property full_parent_name¶
-
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 beone two
.- Type
-
str
- property parents¶
-
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.
- Type
-
List[
Group
]
- property root_parent¶
-
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 isa
.- Type
-
Optional[
Group
]
- property qualified_name¶
-
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
.- Type
-
str
- is_on_cooldown(ctx, /)¶
-
Checks whether the command is currently on cooldown.
Changed in version 2.0:
ctx
parameter is now positional-only.- Parameters
-
ctx (
Context
) – The invocation context to use when checking the commands cooldown status. - Returns
-
A boolean indicating if the command is on cooldown.
- Return type
-
bool
- reset_cooldown(ctx, /)¶
-
Resets the cooldown on this command.
Changed in version 2.0:
ctx
parameter is now positional-only.- Parameters
-
ctx (
Context
) – The invocation context to reset the cooldown under.
- get_cooldown_retry_after(ctx, /)¶
-
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.- Parameters
-
ctx (
Context
) – The invocation context to retrieve the cooldown from. - Returns
-
The amount of time left on this command’s cooldown in seconds.
If this is0.0
then the command isn’t on cooldown. - Return type
-
float
- has_error_handler()¶
-
bool
: Checks whether the command has an error handler registered.New in version 1.7.
- property cog_name¶
-
The name of the cog this command belongs to, if any.
- Type
-
Optional[
str
]
- property short_doc¶
-
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.- Type
-
str
- property signature¶
-
Returns a POSIX-like signature useful for help command output.
- Type
-
str
- await can_run(ctx, /)¶
-
This function is a coroutine.
Checks if the command can be executed by checking all the predicates
inside thechecks
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.- Parameters
-
ctx (
Context
) – The ctx of the command currently being invoked. - Raises
-
CommandError – Any command error that was raised during a check call will be propagated
by this function. - Returns
-
A boolean indicating if the command can be invoked.
- Return type
-
bool
Group¶
Attributes
- case_insensitive
- clean_params
- cog_name
- commands
- cooldown
- full_parent_name
- invoke_without_command
- parents
- qualified_name
- root_parent
- short_doc
- signature
Methods
-
defadd_check -
defadd_command -
@after_invoke -
@before_invoke -
asynccan_run -
@command -
defcopy -
@error -
defget_command -
defget_cooldown_retry_after -
@group -
defhas_error_handler -
defis_on_cooldown -
defremove_check -
defremove_command -
defreset_cooldown -
defupdate -
defwalk_commands
- class discord.ext.commands.Group(*args, **kwargs)¶
-
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 inCommand
are valid in here as well.- invoke_without_command¶
-
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 isFalse
, 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 toFalse
.- Type
-
bool
- case_insensitive¶
-
Indicates if the group’s commands should be case insensitive.
Defaults toFalse
.- Type
-
bool
- @after_invoke¶
-
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.- Parameters
-
coro (coroutine) – The coroutine to register as the post-invoke hook.
- Raises
-
TypeError – The coroutine passed is not actually a coroutine.
- @before_invoke¶
-
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.- Parameters
-
coro (coroutine) – The coroutine to register as the pre-invoke hook.
- Raises
-
TypeError – The coroutine passed is not actually a coroutine.
- @command(*args, **kwargs)¶
-
A shortcut decorator that invokes
command()
and adds it to
the internal command list viaadd_command()
.- Returns
-
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
- Return type
-
Callable[…,
Command
]
- @error¶
-
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, theon_command_error()
is still
invoked afterwards as the catch-all.Changed in version 2.0:
coro
parameter is now positional-only.- Parameters
-
coro (coroutine) – The coroutine to register as the local error handler.
- Raises
-
TypeError – The coroutine passed is not actually a coroutine.
- @group(*args, **kwargs)¶
-
A shortcut decorator that invokes
group()
and adds it to
the internal command list viaadd_command()
.- Returns
-
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
- Return type
-
Callable[…,
Group
]
- copy()¶
-
Creates a copy of this
Group
.- Returns
-
A new instance of this group.
- Return type
-
Group
- add_check(func, /)¶
-
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.See also
The
check()
decorator- Parameters
-
func – The function that will be used as a check.
- add_command(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 genericClientException
Changed in version 2.0:
command
parameter is now positional-only.- Parameters
-
command (
Command
) – The command to add. - Raises
-
-
CommandRegistrationError – If the command or its alias is already registered by different command.
-
TypeError – If the command passed is not a subclass of
Command
.
-
- await can_run(ctx, /)¶
-
This function is a coroutine.
Checks if the command can be executed by checking all the predicates
inside thechecks
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.- Parameters
-
ctx (
Context
) – The ctx of the command currently being invoked. - Raises
-
CommandError – Any command error that was raised during a check call will be propagated
by this function. - Returns
-
A boolean indicating if the command can be invoked.
- Return type
-
bool
- property clean_params¶
-
Dict[
str
,Parameter
]:
Retrieves the parameter dictionary without the context or self parameters.Useful for inspecting signature.
- property cog_name¶
-
The name of the cog this command belongs to, if any.
- Type
-
Optional[
str
]
- property commands¶
-
A unique set of commands without aliases that are registered.
- Type
-
Set[
Command
]
- property cooldown¶
-
The cooldown of a command when invoked
orNone
if the command doesn’t have a registered cooldown.New in version 2.0.
- Type
-
Optional[
Cooldown
]
- property full_parent_name¶
-
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 beone two
.- Type
-
str
- get_command(name, /)¶
-
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 subcommandbar
of the group commandfoo
. If a
subcommand is not found thenNone
is returned just as usual.Changed in version 2.0:
name
parameter is now positional-only.- Parameters
-
name (
str
) – The name of the command to get. - Returns
-
The command that was requested. If not found, returns
None
. - Return type
-
Optional[
Command
]
- get_cooldown_retry_after(ctx, /)¶
-
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.- Parameters
-
ctx (
Context
) – The invocation context to retrieve the cooldown from. - Returns
-
The amount of time left on this command’s cooldown in seconds.
If this is0.0
then the command isn’t on cooldown. - Return type
-
float
- has_error_handler()¶
-
bool
: Checks whether the command has an error handler registered.New in version 1.7.
- is_on_cooldown(ctx, /)¶
-
Checks whether the command is currently on cooldown.
Changed in version 2.0:
ctx
parameter is now positional-only.- Parameters
-
ctx (
Context
) – The invocation context to use when checking the commands cooldown status. - Returns
-
A boolean indicating if the command is on cooldown.
- Return type
-
bool
- property parents¶
-
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.
- Type
-
List[
Group
]
- property qualified_name¶
-
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
.- Type
-
str
- remove_check(func, /)¶
-
Removes a check from the command.
This function is idempotent and will not raise an exception
if the function is not in the command’s checks.New in version 1.3.
Changed in version 2.0:
func
parameter is now positional-only.- Parameters
-
func – The function to remove from the checks.
- remove_command(name, /)¶
-
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.- Parameters
-
name (
str
) – The name of the command to remove. - Returns
-
The command that was removed. If the name is not valid then
None
is returned instead. - Return type
-
Optional[
Command
]
- reset_cooldown(ctx, /)¶
-
Resets the cooldown on this command.
Changed in version 2.0:
ctx
parameter is now positional-only.- Parameters
-
ctx (
Context
) – The invocation context to reset the cooldown under.
- property root_parent¶
-
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 isa
.- Type
-
Optional[
Group
]
- property short_doc¶
-
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.- Type
-
str
- property signature¶
-
Returns a POSIX-like signature useful for help command output.
- Type
-
str
- update(**kwargs)¶
-
Updates
Command
instance with updated attribute.This works similarly to the
command()
decorator in terms
of parameters in that they are passed to theCommand
or
subclass constructors, sans the name and callback.
- for … in walk_commands()¶
-
An iterator that recursively walks through all commands and subcommands.
Changed in version 1.4: Duplicates due to aliases are no longer returned
- Yields
-
Union[
Command
,Group
] – A command or group from the internal list of commands.
GroupMixin¶
Methods
-
defadd_command -
@command -
defget_command -
@group -
defremove_command -
defwalk_commands
- class discord.ext.commands.GroupMixin(*args, **kwargs)¶
-
A mixin that implements common functionality for classes that behave
similar toGroup
and are allowed to register commands.- all_commands¶
-
A mapping of command name to
Command
objects.- Type
-
dict
- case_insensitive¶
-
Whether the commands should be case insensitive. Defaults to
False
.- Type
-
bool
- @command(*args, **kwargs)¶
-
A shortcut decorator that invokes
command()
and adds it to
the internal command list viaadd_command()
.- Returns
-
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
- Return type
-
Callable[…,
Command
]
- @group(*args, **kwargs)¶
-
A shortcut decorator that invokes
group()
and adds it to
the internal command list viaadd_command()
.- Returns
-
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
- Return type
-
Callable[…,
Group
]
- property commands¶
-
A unique set of commands without aliases that are registered.
- Type
-
Set[
Command
]
- add_command(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 genericClientException
Changed in version 2.0:
command
parameter is now positional-only.- Parameters
-
command (
Command
) – The command to add. - Raises
-
-
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_command(name, /)¶
-
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.- Parameters
-
name (
str
) – The name of the command to remove. - Returns
-
The command that was removed. If the name is not valid then
None
is returned instead. - Return type
-
Optional[
Command
]
- for … in walk_commands()¶
-
An iterator that recursively walks through all commands and subcommands.
Changed in version 1.4: Duplicates due to aliases are no longer returned
- Yields
-
Union[
Command
,Group
] – A command or group from the internal list of commands.
- get_command(name, /)¶
-
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 subcommandbar
of the group commandfoo
. If a
subcommand is not found thenNone
is returned just as usual.Changed in version 2.0:
name
parameter is now positional-only.- Parameters
-
name (
str
) – The name of the command to get. - Returns
-
The command that was requested. If not found, returns
None
. - Return type
-
Optional[
Command
]
HybridCommand¶
- class discord.ext.commands.HybridCommand(*args, **kwargs)¶
-
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 anapplication 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.
- @after_invoke¶
-
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.- Parameters
-
coro (coroutine) – The coroutine to register as the post-invoke hook.
- Raises
-
TypeError – The coroutine passed is not actually a coroutine.
- @autocomplete(name)¶
-
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.- Parameters
-
name (
str
) – The parameter name to register as autocomplete. - Raises
-
TypeError – The coroutine passed is not actually a coroutine or
the parameter is not found or of an invalid type.
- @before_invoke¶
-
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.- Parameters
-
coro (coroutine) – The coroutine to register as the pre-invoke hook.
- Raises
-
TypeError – The coroutine passed is not actually a coroutine.
- @error¶
-
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, theon_command_error()
is still
invoked afterwards as the catch-all.Changed in version 2.0:
coro
parameter is now positional-only.- Parameters
-
coro (coroutine) – The coroutine to register as the local error handler.
- Raises
-
TypeError – The coroutine passed is not actually a coroutine.
- await can_run(ctx, /)¶
-
This function is a coroutine.
Checks if the command can be executed by checking all the predicates
inside thechecks
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.- Parameters
-
ctx (
Context
) – The ctx of the command currently being invoked. - Raises
-
CommandError – Any command error that was raised during a check call will be propagated
by this function. - Returns
-
A boolean indicating if the command can be invoked.
- Return type
-
bool
HybridGroup¶
Attributes
- clean_params
- cog_name
- commands
- cooldown
- fallback
- full_parent_name
- parents
- qualified_name
- root_parent
- short_doc
- signature
Methods
-
defadd_check -
defadd_command -
@after_invoke -
@autocomplete -
@before_invoke -
asynccan_run -
@command -
defcopy -
@error -
defget_command -
defget_cooldown_retry_after -
@group -
defhas_error_handler -
defis_on_cooldown -
defremove_check -
defremove_command -
defreset_cooldown -
defupdate -
defwalk_commands
- class discord.ext.commands.HybridGroup(*args, **kwargs)¶
-
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 anapplication 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 toTrue
.These are not created manually, instead they are created via the
decorator or functional interface.New in version 2.0.
- fallback¶
-
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. IfNone
then no fallback command is given. Defaults toNone
.- Type
-
Optional[
str
]
- @after_invoke¶
-
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.- Parameters
-
coro (coroutine) – The coroutine to register as the post-invoke hook.
- Raises
-
TypeError – The coroutine passed is not actually a coroutine.
- @autocomplete(name)¶
-
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.
- Parameters
-
name (
str
) – The parameter name to register as autocomplete. - Raises
-
TypeError – The coroutine passed is not actually a coroutine or
the parameter is not found or of an invalid type.
- @before_invoke¶
-
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.- Parameters
-
coro (coroutine) – The coroutine to register as the pre-invoke hook.
- Raises
-
TypeError – The coroutine passed is not actually a coroutine.
- @command(*args, **kwargs)¶
-
A shortcut decorator that invokes
hybrid_command()
and adds it to
the internal command list viaadd_command()
.- Returns
-
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
- Return type
-
Callable[…,
HybridCommand
]
- @error¶
-
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, theon_command_error()
is still
invoked afterwards as the catch-all.Changed in version 2.0:
coro
parameter is now positional-only.- Parameters
-
coro (coroutine) – The coroutine to register as the local error handler.
- Raises
-
TypeError – The coroutine passed is not actually a coroutine.
- @group(*args, **kwargs)¶
-
A shortcut decorator that invokes
hybrid_group()
and adds it to
the internal command list viaadd_command()
.- Returns
-
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
- Return type
-
Callable[…,
HybridGroup
]
- await can_run(ctx, /)¶
-
This function is a coroutine.
Checks if the command can be executed by checking all the predicates
inside thechecks
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.- Parameters
-
ctx (
Context
) – The ctx of the command currently being invoked. - Raises
-
CommandError – Any command error that was raised during a check call will be propagated
by this function. - Returns
-
A boolean indicating if the command can be invoked.
- Return type
-
bool
- add_check(func, /)¶
-
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.See also
The
check()
decorator- Parameters
-
func – The function that will be used as a check.
- add_command(command, /)¶
-
Adds a
HybridCommand
into the internal list of commands.This is usually not called, instead the
command()
or
group()
shortcut decorators are used instead.- Parameters
-
command (
HybridCommand
) – The command to add. - Raises
-
-
CommandRegistrationError – If the command or its alias is already registered by different command.
-
TypeError – If the command passed is not a subclass of
HybridCommand
.
-
- property clean_params¶
-
Dict[
str
,Parameter
]:
Retrieves the parameter dictionary without the context or self parameters.Useful for inspecting signature.
- property cog_name¶
-
The name of the cog this command belongs to, if any.
- Type
-
Optional[
str
]
- property commands¶
-
A unique set of commands without aliases that are registered.
- Type
-
Set[
Command
]
- property cooldown¶
-
The cooldown of a command when invoked
orNone
if the command doesn’t have a registered cooldown.New in version 2.0.
- Type
-
Optional[
Cooldown
]
- copy()¶
-
Creates a copy of this
Group
.- Returns
-
A new instance of this group.
- Return type
-
Group
- property full_parent_name¶
-
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 beone two
.- Type
-
str
- get_command(name, /)¶
-
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 subcommandbar
of the group commandfoo
. If a
subcommand is not found thenNone
is returned just as usual.Changed in version 2.0:
name
parameter is now positional-only.- Parameters
-
name (
str
) – The name of the command to get. - Returns
-
The command that was requested. If not found, returns
None
. - Return type
-
Optional[
Command
]
- get_cooldown_retry_after(ctx, /)¶
-
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.- Parameters
-
ctx (
Context
) – The invocation context to retrieve the cooldown from. - Returns
-
The amount of time left on this command’s cooldown in seconds.
If this is0.0
then the command isn’t on cooldown. - Return type
-
float
- has_error_handler()¶
-
bool
: Checks whether the command has an error handler registered.New in version 1.7.
- is_on_cooldown(ctx, /)¶
-
Checks whether the command is currently on cooldown.
Changed in version 2.0:
ctx
parameter is now positional-only.- Parameters
-
ctx (
Context
) – The invocation context to use when checking the commands cooldown status. - Returns
-
A boolean indicating if the command is on cooldown.
- Return type
-
bool
- property parents¶
-
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.
- Type
-
List[
Group
]
- property qualified_name¶
-
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
.- Type
-
str
- remove_check(func, /)¶
-
Removes a check from the command.
This function is idempotent and will not raise an exception
if the function is not in the command’s checks.New in version 1.3.
Changed in version 2.0:
func
parameter is now positional-only.- Parameters
-
func – The function to remove from the checks.
- reset_cooldown(ctx, /)¶
-
Resets the cooldown on this command.
Changed in version 2.0:
ctx
parameter is now positional-only.- Parameters
-
ctx (
Context
) – The invocation context to reset the cooldown under.
- property root_parent¶
-
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 isa
.- Type
-
Optional[
Group
]
- property short_doc¶
-
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.- Type
-
str
- property signature¶
-
Returns a POSIX-like signature useful for help command output.
- Type
-
str
- update(**kwargs)¶
-
Updates
Command
instance with updated attribute.This works similarly to the
command()
decorator in terms
of parameters in that they are passed to theCommand
or
subclass constructors, sans the name and callback.
- for … in walk_commands()¶
-
An iterator that recursively walks through all commands and subcommands.
Changed in version 1.4: Duplicates due to aliases are no longer returned
- Yields
-
Union[
Command
,Group
] – A command or group from the internal list of commands.
- remove_command(name, /)¶
-
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.- Parameters
-
name (
str
) – The name of the command to remove. - Returns
-
The command that was removed. If the name is not valid then
None
is returned instead. - Return type
-
Optional[
Command
]
Cogs¶
Cog¶
Methods
-
clsCog.listener -
defbot_check -
defbot_check_once -
asynccog_after_invoke -
asynccog_app_command_error -
asynccog_before_invoke -
defcog_check -
asynccog_command_error -
asynccog_load -
asynccog_unload -
defget_app_commands -
defget_commands -
defget_listeners -
defhas_app_command_error_handler -
defhas_error_handler -
defwalk_app_commands -
defwalk_commands
- class discord.ext.commands.Cog(*args, **kwargs)¶
-
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.- get_commands()¶
-
Returns the commands that are defined inside this cog.
This does not include
discord.app_commands.Command
ordiscord.app_commands.Group
instances.- Returns
-
A
list
ofCommand
s that are
defined inside this cog, not including subcommands. - Return type
-
List[
Command
]
- get_app_commands()¶
-
Returns the app commands that are defined inside this cog.
- Returns
-
A
list
ofdiscord.app_commands.Command
s anddiscord.app_commands.Group
s that are
defined inside this cog, not including subcommands. - Return type
-
List[Union[
discord.app_commands.Command
,discord.app_commands.Group
]]
- property qualified_name¶
-
Returns the cog’s specified name, not the class name.
- Type
-
str
- property description¶
-
Returns the cog’s description, typically the cleaned docstring.
- Type
-
str
- for … in walk_commands()¶
-
An iterator that recursively walks through this cog’s commands and subcommands.
- Yields
-
Union[
Command
,Group
] – A command or group from the cog.
- for … in walk_app_commands()¶
-
An iterator that recursively walks through this cog’s app commands and subcommands.
- Yields
-
Union[
discord.app_commands.Command
,discord.app_commands.Group
] – An app command or group from the cog.
- property app_command¶
-
Returns the associated group with this cog.
This is only available if inheriting from
GroupCog
.- Type
-
Optional[
discord.app_commands.Group
]
- get_listeners()¶
-
Returns a
list
of (name, function) listener pairs that are defined in this cog.- Returns
-
The listeners defined in this cog.
- Return type
-
List[Tuple[
str
, coroutine]]
- classmethod listener(name=…)¶
-
A decorator that marks a function as a listener.
This is the cog equivalent of
Bot.listen()
.- Parameters
-
name (
str
) – The name of the event being listened to. If not provided, it
defaults to the function’s name. - Raises
-
TypeError – The function is not a coroutine function or a string was not passed as
the name.
- has_error_handler()¶
-
bool
: Checks whether the cog has an error handler.New in version 1.7.
- has_app_command_error_handler()¶
-
bool
: Checks whether the cog has an app error handler.New in version 2.1.
- await cog_load()¶
-
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.
- await cog_unload()¶
-
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.
Changed in version 2.0: This method can now be a coroutine.
- bot_check_once(ctx)¶
-
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 theContext
.
- bot_check(ctx)¶
-
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 theContext
.
- cog_check(ctx)¶
-
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 theContext
.
- await cog_command_error(ctx, error)¶
-
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.
- Parameters
-
-
ctx (
Context
) – The invocation context where the error happened. -
error (
CommandError
) – The error that happened.
-
- await cog_app_command_error(interaction, error)¶
-
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.
- Parameters
-
-
interaction (
Interaction
) – The interaction that is being handled. -
error (
AppCommandError
) – The exception that was raised.
-
- await cog_before_invoke(ctx)¶
-
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.
- Parameters
-
ctx (
Context
) – The invocation context.
- await cog_after_invoke(ctx)¶
-
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.
- Parameters
-
ctx (
Context
) – The invocation context.
GroupCog¶
- class discord.ext.commands.GroupCog(*args, **kwargs)¶
-
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 inCogMeta
also apply to this.
See theCog
documentation for methods.Decorators such as
guild_only()
,guilds()
,
anddefault_permissions()
will apply to the group if used on top of the
cog.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.
CogMeta¶
Attributes
- command_attrs
- description
- group_auto_locale_strings
- group_description
- group_extras
- group_name
- group_nsfw
- name
- class discord.ext.commands.CogMeta(*args, **kwargs)¶
-
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 theabc.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
- name¶
-
The cog name. By default, it is the name of the class with no modification.
- Type
-
str
- description¶
-
The cog description. By default, it is the cleaned docstring of the class.
New in version 1.6.
- Type
-
str
- command_attrs¶
-
A list of attributes to apply to every command inside this cog. The dictionary
is passed into theCommand
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
- Type
-
dict
- group_name¶
-
The group name of a cog. This is only applicable for
GroupCog
instances.
By default, it’s the same value asname
.New in version 2.0.
- Type
-
Union[
str
,locale_str
]
- group_description¶
-
The group description of a cog. This is only applicable for
GroupCog
instances.
By default, it’s the same value asdescription
.New in version 2.0.
- Type
-
Union[
str
,locale_str
]
- group_nsfw¶
-
Whether the application command group is NSFW. This is only applicable for
GroupCog
instances.
By default, it’sFalse
.New in version 2.0.
- Type
-
bool
- group_auto_locale_strings¶
-
If this is set to
True
, then all translatable strings will implicitly
be wrapped intolocale_str
rather
thanstr
. Defaults toTrue
.New in version 2.0.
- Type
-
bool
- group_extras¶
-
A dictionary that can be used to store extraneous data.
This is only applicable forGroupCog
instances.
The library will not touch any values or keys within this dictionary.New in version 2.1.
- Type
-
dict
Help Commands¶
HelpCommand¶
Methods
-
defadd_check -
asynccommand_callback -
defcommand_not_found -
asyncfilter_commands -
defget_bot_mapping -
defget_command_signature -
defget_destination -
defget_max_size -
asyncon_help_command_error -
asyncprepare_help_command -
defremove_check -
defremove_mentions -
asyncsend_bot_help -
asyncsend_cog_help -
asyncsend_command_help -
asyncsend_error_message -
asyncsend_group_help -
defsubcommand_not_found
- class discord.ext.commands.HelpCommand(*args, **kwargs)¶
-
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.- context¶
-
The context that invoked this help formatter. This is generally set after
the help command assigned,command_callback()
, has been called.- Type
-
Optional[
Context
]
- show_hidden¶
-
Specifies if hidden commands should be shown in the output.
Defaults toFalse
.- Type
-
bool
- verify_checks¶
-
Specifies if commands should have their
Command.checks
called
and verified. IfTrue
, always callsCommand.checks
.
IfNone
, only callsCommand.checks
in a guild setting.
IfFalse
, never callsCommand.checks
. Defaults toTrue
.Changed in version 1.7.
- Type
-
Optional[
bool
]
- command_attrs¶
-
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 theCommand
constructor.- Type
-
dict
- add_check(func, /)¶
-
Adds a check to the help command.
New in version 1.4.
Changed in version 2.0:
func
parameter is now positional-only.See also
The
check()
decorator- Parameters
-
func – The function that will be used as a check.
- remove_check(func, /)¶
-
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.- Parameters
-
func – The function to remove from the checks.
- get_bot_mapping()¶
-
Retrieves the bot mapping passed to
send_bot_help()
.
- property invoked_with¶
-
Similar to
Context.invoked_with
except properly handles
the case whereContext.send_help()
is used.If the help command was used regularly then this returns
theContext.invoked_with
attribute. Otherwise, if
it the help command was called usingContext.send_help()
then it returns the internal command name of the help command.- Returns
-
The command name that triggered this invocation.
- Return type
-
Optional[
str
]
- get_command_signature(command, /)¶
-
Retrieves the signature portion of the help page.
Changed in version 2.0:
command
parameter is now positional-only.- Parameters
-
command (
Command
) – The command to get the signature of. - Returns
-
The signature for the command.
- Return type
-
str
- remove_mentions(string, /)¶
-
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.- Returns
-
The string with mentions removed.
- Return type
-
str
- property cog¶
-
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
.- Returns
-
The cog that is currently set for the help command.
- Return type
-
Optional[
Cog
]
- command_not_found(string, /)¶
-
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.- Parameters
-
string (
str
) – The string that contains the invalid command. Note that this has
had mentions removed to prevent abuse. - Returns
-
The string to use when a command has not been found.
- Return type
-
str
- subcommand_not_found(command, string, /)¶
-
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 namedstring
.
-
Changed in version 2.0:
command
andstring
parameters are now positional-only.- Parameters
-
-
command (
Command
) – The command that did not have the subcommand requested. -
string (
str
) – The string that contains the invalid subcommand. Note that this has
had mentions removed to prevent abuse.
-
- Returns
-
The string to use when the command did not have the subcommand requested.
- Return type
-
str
-
- await filter_commands(commands, /, *, sort=False, key=None)¶
-
This function is a coroutine.
Returns a filtered list of commands and optionally sorts them.
This takes into account the
verify_checks
andshow_hidden
attributes.Changed in version 2.0:
commands
parameter is now positional-only.- Parameters
-
-
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 tosorted()
that
takes aCommand
as its sole parameter. Ifsort
is
passed asTrue
then this will default as the command name.
-
- Returns
-
A list of commands that passed the filter.
- Return type
-
List[
Command
]
- get_max_size(commands, /)¶
-
Returns the largest name length of the specified command list.
Changed in version 2.0:
commands
parameter is now positional-only.- Parameters
-
commands (Sequence[
Command
]) – A sequence of commands to check for the largest size. - Returns
-
The maximum width of the commands.
- Return type
-
int
- get_destination()¶
-
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.
- Returns
-
The destination where the help command will be output.
- Return type
-
abc.Messageable
- await send_error_message(error, /)¶
-
This function is a coroutine.
Handles the implementation when an error happens in the help command.
For example, the result ofcommand_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 byget_destination()
.Note
You can access the invocation context with
HelpCommand.context
.Changed in version 2.0:
error
parameter is now positional-only.- Parameters
-
error (
str
) – The error message to display to the user. Note that this has
had mentions removed to prevent abuse.
- await on_help_command_error(ctx, error, /)¶
-
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
anderror
parameters are now positional-only.- Parameters
-
-
ctx (
Context
) – The invocation context. -
error (
CommandError
) – The error that was raised.
-
- await send_bot_help(mapping, /)¶
-
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 useget_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 callfilter_commands()
yourself.Changed in version 2.0:
mapping
parameter is now positional-only.- Parameters
-
mapping (Mapping[Optional[
Cog
], List[Command
]]) – A mapping of cogs to commands that have been requested by the user for help.
The key of the mapping is theCog
that the command belongs to, or
None
if there isn’t one, and the value is a list of commands that belongs to that cog.
- await send_cog_help(cog, /)¶
-
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 useget_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 cog see
Cog.get_commands()
.
The commands returned not filtered. To do the filtering you will have to call
filter_commands()
yourself.Changed in version 2.0:
cog
parameter is now positional-only.- Parameters
-
cog (
Cog
) – The cog that was requested for help.
- await send_group_help(group, /)¶
-
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 useget_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 callfilter_commands()
yourself.Changed in version 2.0:
group
parameter is now positional-only.- Parameters
-
group (
Group
) – The group that was requested for help.
- await send_command_help(command, /)¶
-
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 useget_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
.Showing Help
There are certain attributes and methods that are helpful for a help command
to show such as the following:-
Command.help
-
Command.brief
-
Command.short_doc
-
Command.description
-
get_command_signature()
There are more than just these attributes but feel free to play around with
these to help you get started to get the output that you want.Changed in version 2.0:
command
parameter is now positional-only.- Parameters
-
command (
Command
) – The command that was requested for help.
-
- await prepare_help_command(ctx, command=None, /)¶
-
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
andcommand
parameters are now positional-only.- Parameters
-
-
ctx (
Context
) – The invocation context. -
command (Optional[
str
]) – The argument passed to the help command.
-
- await command_callback(ctx, /, *, command=None)¶
-
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.-
send_bot_help()
-
send_cog_help()
-
send_group_help()
-
send_command_help()
-
get_destination()
-
command_not_found()
-
subcommand_not_found()
-
send_error_message()
-
on_help_command_error()
-
prepare_help_command()
Changed in version 2.0:
ctx
parameter is now positional-only. -
DefaultHelpCommand¶
Attributes
- arguments_heading
- commands_heading
- default_argument_description
- dm_help
- dm_help_threshold
- indent
- no_category
- paginator
- show_parameter_descriptions
- sort_commands
- width
Methods
-
defadd_command_arguments -
defadd_command_formatting -
defadd_indented_commands -
defget_command_signature -
defget_destination -
defget_ending_note -
asyncsend_pages -
defshorten_text
- class discord.ext.commands.DefaultHelpCommand(*args, **kwargs)¶
-
The implementation of the default help command.
This inherits from
HelpCommand
.It extends it with the following attributes.
- width¶
-
The maximum number of characters that fit in a line.
Defaults to 80.- Type
-
int
- sort_commands¶
-
Whether to sort the commands in the output alphabetically. Defaults to
True
.- Type
-
bool
- dm_help¶
-
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. IfFalse
, none of the help
output is DM’d. IfNone
, then the bot will only DM when the help
message becomes too long (dictated by more thandm_help_threshold
characters).
Defaults toFalse
.- Type
-
Optional[
bool
]
- dm_help_threshold¶
-
The number of characters the paginator must accumulate before getting DM’d to the
user ifdm_help
is set toNone
. Defaults to 1000.- Type
-
Optional[
int
]
- indent¶
-
How much to indent the commands from a heading. Defaults to
2
.- Type
-
int
- arguments_heading¶
-
The arguments list’s heading string used when the help command is invoked with a command name.
Useful for i18n. Defaults to"Arguments:"
.
Shown whenshow_parameter_descriptions
isTrue
.New in version 2.0.
- Type
-
str
- show_parameter_descriptions¶
-
Whether to show the parameter descriptions. Defaults to
True
.
Setting this toFalse
will revert to showing thesignature
instead.New in version 2.0.
- Type
-
bool
- commands_heading¶
-
The command list’s heading string used when the help command is invoked with a category name.
Useful for i18n. Defaults to"Commands:"
- Type
-
str
- default_argument_description¶
-
The default argument description string used when the argument’s
description
isNone
.
Useful for i18n. Defaults to"No description given."
New in version 2.0.
- Type
-
str
- no_category¶
-
The string used when there is a command which does not belong to any category(cog).
Useful for i18n. Defaults to"No Category"
- Type
-
str
- paginator¶
-
The paginator used to paginate the help command output.
- Type
-
Paginator
- shorten_text(text, /)¶
-
str
: Shortens text to fit into thewidth
.Changed in version 2.0:
text
parameter is now positional-only.
- get_ending_note()¶
-
str
: Returns help command’s ending note. This is mainly useful to override for i18n purposes.
- get_command_signature(command, /)¶
-
Retrieves the signature portion of the help page.
Calls
get_command_signature()
ifshow_parameter_descriptions
isFalse
else returns a modified signature where the command parameters are not shown.New in version 2.0.
- Parameters
-
command (
Command
) – The command to get the signature of. - Returns
-
The signature for the command.
- Return type
-
str
- add_indented_commands(commands, /, *, heading, max_size=None)¶
-
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 tomax_size
followed by
the command’sCommand.short_doc
and then shortened
to fit into thewidth
.Changed in version 2.0:
commands
parameter is now positional-only.- Parameters
-
-
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, callsget_max_size()
on the
commands parameter.
-
- add_command_arguments(command, /)¶
-
Indents a list of command arguments after the
arguments_heading
.The default implementation is the argument
name
indented by
indent
spaces, padded tomax_size
usingget_max_size()
followed by the argument’sdescription
or
default_argument_description
and then shortened
to fit into thewidth
and thendisplayed_default
between () if one is present after that.New in version 2.0.
- Parameters
-
command (
Command
) – The command to list the arguments for.
- await send_pages()¶
-
This function is a coroutine.
A helper utility to send the page output from
paginator
to the destination.
- add_command_formatting(command, /)¶
-
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 ifshow_parameter_descriptions
isTrue
.- Parameters
-
command (
Command
) – The command to format.
- get_destination()¶
-
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.
- Returns
-
The destination where the help command will be output.
- Return type
-
abc.Messageable
MinimalHelpCommand¶
Methods
-
defadd_aliases_formatting -
defadd_bot_commands_formatting -
defadd_command_formatting -
defadd_subcommand_formatting -
defget_command_signature -
defget_destination -
defget_ending_note -
defget_opening_note -
asyncsend_pages
- class discord.ext.commands.MinimalHelpCommand(*args, **kwargs)¶
-
An implementation of a help command with minimal output.
This inherits from
HelpCommand
.- sort_commands¶
-
Whether to sort the commands in the output alphabetically. Defaults to
True
.- Type
-
bool
- commands_heading¶
-
The command list’s heading string used when the help command is invoked with a category name.
Useful for i18n. Defaults to"Commands"
- Type
-
str
- aliases_heading¶
-
The alias list’s heading string used to list the aliases of the command. Useful for i18n.
Defaults to"Aliases:"
.- Type
-
str
- dm_help¶
-
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. IfFalse
, none of the help
output is DM’d. IfNone
, then the bot will only DM when the help
message becomes too long (dictated by more thandm_help_threshold
characters).
Defaults toFalse
.- Type
-
Optional[
bool
]
- dm_help_threshold¶
-
The number of characters the paginator must accumulate before getting DM’d to the
user ifdm_help
is set toNone
. Defaults to 1000.- Type
-
Optional[
int
]
- no_category¶
-
The string used when there is a command which does not belong to any category(cog).
Useful for i18n. Defaults to"No Category"
- Type
-
str
- paginator¶
-
The paginator used to paginate the help command output.
- Type
-
Paginator
- await send_pages()¶
-
This function is a coroutine.
A helper utility to send the page output from
paginator
to the destination.
- get_opening_note()¶
-
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.
- Returns
-
The help command opening note.
- Return type
-
str
- get_command_signature(command, /)¶
-
Retrieves the signature portion of the help page.
Changed in version 2.0:
command
parameter is now positional-only.- Parameters
-
command (
Command
) – The command to get the signature of. - Returns
-
The signature for the command.
- Return type
-
str
- get_ending_note()¶
-
Return the help command’s ending note. This is mainly useful to override for i18n purposes.
The default implementation does nothing.
- Returns
-
The help command ending note.
- Return type
-
str
- add_bot_commands_formatting(commands, heading, /)¶
-
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
andheading
parameters are now positional-only.- Parameters
-
-
commands (Sequence[
Command
]) – A list of commands that belong to the heading. -
heading (
str
) – The heading to add to the line.
-
- add_subcommand_formatting(command, /)¶
-
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’sCommand.short_doc
.Changed in version 2.0:
command
parameter is now positional-only.- Parameters
-
command (
Command
) – The command to show information of.
- add_aliases_formatting(aliases, /)¶
-
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.- Parameters
-
aliases (Sequence[
str
]) – A list of aliases to format.
- add_command_formatting(command, /)¶
-
A utility function to format commands and groups.
Changed in version 2.0:
command
parameter is now positional-only.- Parameters
-
command (
Command
) – The command to format.
- get_destination()¶
-
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.
- Returns
-
The destination where the help command will be output.
- Return type
-
abc.Messageable
Paginator¶
Methods
-
defadd_line -
defclear -
defclose_page
- class discord.ext.commands.Paginator(prefix=‘«`’, suffix=‘«`’, max_size=2000, linesep=‘n’)¶
-
A class that aids in paginating code blocks for Discord messages.
- len(x)
-
Returns the total number of characters in the paginator.
- prefix¶
-
The prefix inserted to every page. e.g. three backticks, if any.
- Type
-
Optional[
str
]
- suffix¶
-
The suffix appended at the end of every page. e.g. three backticks, if any.
- Type
-
Optional[
str
]
- max_size¶
-
The maximum amount of codepoints allowed in a page.
- Type
-
int
- linesep¶
-
- The character string inserted between lines. e.g. a newline character.
-
New in version 1.7.
- Type
-
str
- clear()¶
-
Clears the paginator to have no pages.
- add_line(line=», *, empty=False)¶
-
Adds a line to the current page.
If the line exceeds the
max_size
then an exception
is raised.- Parameters
-
-
line (
str
) – The line to add. -
empty (
bool
) – Indicates if another empty line should be added.
-
- Raises
-
RuntimeError – The line was too big for the current
max_size
.
- close_page()¶
-
Prematurely terminate a page.
- property pages¶
-
Returns the rendered list of pages.
- Type
-
List[
str
]
Enums¶
- class discord.ext.commands.BucketType¶
-
Specifies a type of bucket for, e.g. a cooldown.
- default¶
-
The default bucket operates on a global basis.
- user¶
-
The user bucket operates on a per-user basis.
- guild¶
-
The guild bucket operates on a per-guild basis.
- channel¶
-
The channel bucket operates on a per-channel basis.
- member¶
-
The member bucket operates on a per-member basis.
- category¶
-
The category bucket operates on a per-category basis.
- role¶
-
The role bucket operates on a per-role basis.
New in version 1.3.
Checks¶
- @discord.ext.commands.check(predicate)¶
-
A decorator that adds a check to the
Command
or its
subclasses. These checks could be accessed viaCommand.checks
.These checks should be predicates that take in a single parameter taking
aContext
. If the check returns aFalse
-like value then
during invocation aCheckFailure
exception is raised and sent to
theon_command_error()
event.If an exception should be thrown in the predicate then it should be a
subclass ofCommandError
. 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.- Parameters
-
predicate (Callable[[
Context
],bool
]) – The predicate to check if the command should be invoked.
- @discord.ext.commands.check_any(*checks)¶
-
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 fromCheckFailure
.Note
The
predicate
attribute for this function is a coroutine.New in version 1.3.
- Parameters
-
*checks (Callable[[
Context
],bool
]) – An argument list of checks that have been decorated with
thecheck()
decorator. - Raises
-
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!')
- @discord.ext.commands.has_role(item)¶
-
A
check()
that is added that checks if the member invoking the
command has the role specified via the name or ID specified.If a string is specified, you must give the exact name of the role, including
caps and spelling.If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will
returnFalse
.This check raises one of two special exceptions,
MissingRole
if the user
is missing a role, orNoPrivateMessage
if it is used in a private message.
Both inherit fromCheckFailure
.Changed in version 1.1: Raise
MissingRole
orNoPrivateMessage
instead of genericCheckFailure
Changed in version 2.0:
item
parameter is now positional-only.- Parameters
-
item (Union[
int
,str
]) – The name or ID of the role to check.
- @discord.ext.commands.has_permissions(**perms)¶
-
A
check()
that is added that checks if the member has all of
the permissions necessary.Note that this check operates on the 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 fromCheckFailure
.- Parameters
-
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.')
- @discord.ext.commands.has_guild_permissions(**perms)¶
-
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.
- @discord.ext.commands.has_any_role(*items)¶
-
A
check()
that is added that checks if the member invoking the
command has any of the roles specified. This means that if they have
one out of the three roles specified, then this check will returnTrue
.Similar to
has_role()
, the names or IDs passed in must be exact.This check raises one of two special exceptions,
MissingAnyRole
if the user
is missing all roles, orNoPrivateMessage
if it is used in a private message.
Both inherit fromCheckFailure
.Changed in version 1.1: Raise
MissingAnyRole
orNoPrivateMessage
instead of genericCheckFailure
- Parameters
-
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')
- @discord.ext.commands.bot_has_role(item)¶
-
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, orNoPrivateMessage
if it is used in a private message.
Both inherit fromCheckFailure
.Changed in version 1.1: Raise
BotMissingRole
orNoPrivateMessage
instead of genericCheckFailure
Changed in version 2.0:
item
parameter is now positional-only.
- @discord.ext.commands.bot_has_permissions(**perms)¶
-
Similar to
has_permissions()
except checks if the bot itself has
the permissions listed.This check raises a special exception,
BotMissingPermissions
that is inherited fromCheckFailure
.
- @discord.ext.commands.bot_has_guild_permissions(**perms)¶
-
Similar to
has_guild_permissions()
, but checks the bot
members guild permissions.New in version 1.3.
- @discord.ext.commands.bot_has_any_role(*items)¶
-
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, orNoPrivateMessage
if it is used in a private message.
Both inherit fromCheckFailure
.Changed in version 1.1: Raise
BotMissingAnyRole
orNoPrivateMessage
instead of generic checkfailure
- @discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)¶
-
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 oftype
which must be of enum
typeBucketType
.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.
- Parameters
-
-
rate (
int
) – The number of times a command can be used before triggering a cooldown. -
per (
float
) – The amount of seconds to wait for a cooldown when it’s been triggered. -
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 thanMessage
as its only argument.
-
- @discord.ext.commands.dynamic_cooldown(cooldown, type)¶
-
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 typeContext
and must
return aCooldown
orNone
.
IfNone
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 oftype
which must be of enum
typeBucketType
.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.
- Parameters
-
-
cooldown (Callable[[
Context
], Optional[Cooldown
]]) – A function that takes a message and returns a cooldown that will
apply to this invocation orNone
if the cooldown should be bypassed. -
type (
BucketType
) – The type of cooldown to have.
-
- @discord.ext.commands.max_concurrency(number, per=discord.ext.commands.BucketType.default, *, wait=False)¶
-
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.
- Parameters
-
-
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 tonumber
times per guild. -
wait (
bool
) – Whether the command should wait for the queue to be over. If this is set toFalse
then instead of waiting until the command can run again, the command raises
MaxConcurrencyReached
to its error handler. If this is set toTrue
then the command waits until it can be executed.
-
- @discord.ext.commands.before_invoke(coro)¶
-
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')
- @discord.ext.commands.after_invoke(coro)¶
-
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.
- @discord.ext.commands.guild_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 fromCheckFailure
.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.
- @discord.ext.commands.dm_only()¶
-
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 fromCheckFailure
.New in version 1.1.
- @discord.ext.commands.is_owner()¶
-
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
fromCheckFailure
.
- @discord.ext.commands.is_nsfw()¶
-
A
check()
that checks if the channel is a NSFW channel.This check raises a special exception,
NSFWChannelRequired
that is derived fromCheckFailure
.If used on hybrid commands, this will be equivalent to setting the
application command’snsfw
attribute toTrue
. 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 genericCheckFailure
.
DM channels will also now pass this check.
Context¶
Attributes
- args
- author
- bot
- bot_permissions
- channel
- clean_prefix
- cog
- command
- command_failed
- current_argument
- current_parameter
- guild
- interaction
- invoked_parents
- invoked_subcommand
- invoked_with
- kwargs
- me
- message
- permissions
- prefix
- subcommand_passed
- valid
- voice_client
Methods
-
clsContext.from_interaction -
asyncdefer -
asyncfetch_message -
async forhistory -
asyncinvoke -
asyncpins -
asyncreinvoke -
asyncreply -
asyncsend -
asyncsend_help -
deftyping
- class discord.ext.commands.Context(*, message, bot, view, args=…, kwargs=…, prefix=None, command=None, invoked_with=None, invoked_parents=…, invoked_subcommand=None, subcommand_passed=None, command_failed=False, current_parameter=None, current_argument=None, interaction=None)¶
-
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.- message¶
-
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.- Type
-
Message
- bot¶
-
The bot that contains the command being executed.
- Type
-
Bot
- args¶
-
The list of transformed arguments that were passed into the command.
If this is accessed during theon_command_error()
event
then this list could be incomplete.- Type
-
list
- kwargs¶
-
A dictionary of transformed arguments that were passed into the command.
Similar toargs
, if this is accessed in the
on_command_error()
event then this dict could be incomplete.- Type
-
dict
- current_parameter¶
-
The parameter that is currently being inspected and converted.
This is only of use for within converters.New in version 2.0.
- Type
-
Optional[
Parameter
]
- current_argument¶
-
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.
- Type
-
Optional[
str
]
- interaction¶
-
The interaction associated with this context.
New in version 2.0.
- Type
-
Optional[
Interaction
]
- prefix¶
-
The prefix that was used to invoke the command. For interaction based contexts,
this is/
for slash commands andu200b
for context menu commands.- Type
-
Optional[
str
]
- command¶
-
The command that is being invoked currently.
- Type
-
Optional[
Command
]
- invoked_with¶
-
The command name that triggered this invocation. Useful for finding out
which alias called the command.- Type
-
Optional[
str
]
- invoked_parents¶
-
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.
- Type
-
List[
str
]
- invoked_subcommand¶
-
The subcommand that was invoked.
If no valid subcommand was invoked then this is equal toNone
.- Type
-
Optional[
Command
]
- subcommand_passed¶
-
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 toNone
.- Type
-
Optional[
str
]
- command_failed¶
-
A boolean that indicates if the command failed to be parsed, checked,
or invoked.- Type
-
bool
- async with typing(*, ephemeral=False)¶
-
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 usingawait
.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.- Parameters
-
ephemeral (
bool
) –Indicates whether the deferred message will eventually be ephemeral.
Only valid for interaction based contexts.New in version 2.0.
- classmethod await from_interaction(interaction, /)¶
-
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
thatContext.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 thatContext.author
returns the author of the message being targetted. To get the member that invoked
the command thendiscord.Interaction.user
should be used instead.New in version 2.0.
- Parameters
-
interaction (
discord.Interaction
) – The interaction to create a context with. - Raises
-
-
ValueError – The interaction does not have a valid command.
-
TypeError – The interaction client is not derived from
Bot
orAutoShardedBot
.
-
- await invoke(command, /, *args, **kwargs)¶
-
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.- Parameters
-
-
command (
Command
) – The command that is going to be called. -
*args – The arguments to use.
-
**kwargs – The keyword arguments to use.
-
- Raises
-
TypeError – The command argument to invoke is missing.
- await reinvoke(*, call_hooks=False, restart=True)¶
-
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 regularinvoke()
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.- Parameters
-
-
call_hooks (
bool
) – Whether to call the before and after invoke hooks. -
restart (
bool
) – Whether to start the call chain from the very beginning
or where we left off (i.e. the command that caused the error).
The default is to start where we left off.
-
- Raises
-
ValueError – The context to reinvoke is not valid.
- property valid¶
-
Checks if the invocation context is valid to be invoked with.
- Type
-
bool
- property clean_prefix¶
-
The cleaned up invoke prefix. i.e. mentions are
@name
instead of<@id>
.New in version 2.0.
- Type
-
str
- property cog¶
-
Returns the cog associated with this context’s command. None if it does not exist.
- Type
-
Optional[
Cog
]
- guild¶
-
Returns the guild associated with this context’s command. None if not available.
- Type
-
Optional[
Guild
]
- channel¶
-
Returns the channel associated with this context’s command.
Shorthand forMessage.channel
.- Type
-
Union[
abc.Messageable
]
-
Union[
User
,Member
]:
Returns the author associated with this context’s command. Shorthand forMessage.author
- me¶
-
Union[
Member
,ClientUser
]:
Similar toGuild.me
except it may return theClientUser
in private message contexts.
- permissions¶
-
Returns the resolved permissions for the invoking user in this channel.
Shorthand forabc.GuildChannel.permissions_for()
orInteraction.permissions
.New in version 2.0.
- Type
-
Permissions
- bot_permissions¶
-
Returns the resolved permissions for the bot in this channel.
Shorthand forabc.GuildChannel.permissions_for()
orInteraction.app_permissions
.For interaction-based commands, this will reflect the effective permissions
forContext
calls, which may differ from calls through
otherabc.Messageable
endpoints, likechannel
.Notably, sending messages, embedding links, and attaching files are always
permitted, while reading messages might not be.New in version 2.0.
- Type
-
Permissions
- property voice_client¶
-
A shortcut to
Guild.voice_client
, if applicable.- Type
-
Optional[
VoiceProtocol
]
- await send_help(entity=<bot>)¶
-
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 aCommand
.Note
Due to the way this function works, instead of returning
something similar tocommand_not_found()
this returnsNone
on bad input or no help command.- Parameters
-
entity (Optional[Union[
Command
,Cog
,str
]]) – The entity to show help for. - Returns
-
The result of the help command, if any.
- Return type
-
Any
- await reply(content=None, **kwargs)¶
-
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 ofInvalidArgument
.- Raises
-
-
HTTPException – Sending the message failed.
-
Forbidden – You do not have the proper permissions to send the message.
-
ValueError – The
files
list is not of the appropriate size -
TypeError – You specified both
file
andfiles
.
-
- Returns
-
The message that was sent.
- Return type
-
Message
- await defer(*, ephemeral=False)¶
-
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.
- Parameters
-
ephemeral (
bool
) – Indicates whether the deferred message will eventually be ephemeral. - Raises
-
-
HTTPException – Deferring the interaction failed.
-
InteractionResponded – This interaction has already been responded to before.
-
- await fetch_message(id, /)¶
-
This function is a coroutine.
Retrieves a single
Message
from the destination.- Parameters
-
id (
int
) – The message ID to look for. - Raises
-
-
NotFound – The specified message was not found.
-
Forbidden – You do not have the permissions required to get a message.
-
HTTPException – Retrieving the message failed.
-
- Returns
-
The message asked for.
- Return type
-
Message
- async for … in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
-
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.
- Parameters
-
-
limit (Optional[
int
]) – The number of messages to retrieve.
IfNone
, 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 toTrue
, return messages in oldest->newest order. Defaults toTrue
if
after
is specified, otherwiseFalse
.
-
- Raises
-
-
Forbidden – You do not have permissions to get channel message history.
-
HTTPException – The request to get message history failed.
-
- Yields
-
Message
– The message with the message data parsed.
- await pins()¶
-
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Message
objects returned by this method do not contain complete
Message.reactions
data.- Raises
-
-
Forbidden – You do not have the permission to retrieve pinned messages.
-
HTTPException – Retrieving the pinned messages failed.
-
- Returns
-
The messages that are currently pinned.
- Return type
-
List[
Message
]
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, suppress_embeds=False, ephemeral=False)¶
-
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 ofInvalidArgument
.- Parameters
-
-
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 withallowed_mentions
.
The merging behaviour only overrides attributes that have been explicitly passed
to the object, otherwise it uses the attributes set inallowed_mentions
.
If no object is passed at all then the defaults given byallowed_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 aMessage
. You can control
whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.This is ignored for interaction based contexts.
New in version 1.6.
-
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.
This is ignored for interaction based contexts.New in version 1.6.
-
view (
discord.ui.View
) –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.
-
- Raises
-
-
HTTPException – Sending the message failed.
-
Forbidden – You do not have the proper permissions to send the message.
-
ValueError – The
files
list is not of the appropriate size. -
TypeError – You specified both
file
andfiles
,
or you specified bothembed
andembeds
,
or thereference
object is not aMessage
,
MessageReference
orPartialMessage
.
-
- Returns
-
The message that was sent.
- Return type
-
Message
-
Converters¶
- class discord.ext.commands.Converter(*args, **kwargs)¶
-
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 caseddiscord
classes.Classes that derive from this should override the
convert()
method to do its conversion logic. This method must be a coroutine.- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
- class discord.ext.commands.ObjectConverter(*args, **kwargs)¶
-
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.
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.MemberConverter(*args, **kwargs)¶
-
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 name#discrim
-
Lookup by name
-
Lookup by nickname
Changed in version 1.5: Raise
MemberNotFound
instead of genericBadArgument
Changed in version 1.5.1: This converter now lazily fetches members from the gateway and HTTP APIs,
optionally caching the result ifMemberCacheFlags.joined
is enabled.- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.UserConverter(*args, **kwargs)¶
-
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 name#discrim
-
Lookup by name
Changed in version 1.5: Raise
UserNotFound
instead of genericBadArgument
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.- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.MessageConverter(*args, **kwargs)¶
-
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
orChannelNotReadable
instead of genericBadArgument
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.PartialMessageConverter(*args, **kwargs)¶
-
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
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.GuildChannelConverter(*args, **kwargs)¶
-
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 name.
New in version 2.0.
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.TextChannelConverter(*args, **kwargs)¶
-
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 name
Changed in version 1.5: Raise
ChannelNotFound
instead of genericBadArgument
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.VoiceChannelConverter(*args, **kwargs)¶
-
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 name
Changed in version 1.5: Raise
ChannelNotFound
instead of genericBadArgument
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.StageChannelConverter(*args, **kwargs)¶
-
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 name
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.CategoryChannelConverter(*args, **kwargs)¶
-
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 name
Changed in version 1.5: Raise
ChannelNotFound
instead of genericBadArgument
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.ForumChannelConverter(*args, **kwargs)¶
-
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 name
New in version 2.0.
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.InviteConverter(*args, **kwargs)¶
-
Converts to a
Invite
.This is done via an HTTP request using
Bot.fetch_invite()
.Changed in version 1.5: Raise
BadInviteArgument
instead of genericBadArgument
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
- class discord.ext.commands.GuildConverter(*args, **kwargs)¶
-
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.
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.RoleConverter(*args, **kwargs)¶
-
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 genericBadArgument
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.GameConverter(*args, **kwargs)¶
-
Converts to a
Game
.- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
- class discord.ext.commands.ColourConverter(*args, **kwargs)¶
-
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
inColour
-
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 genericBadArgument
Changed in version 1.7: Added support for
rgb
function and 3-digit hex shortcuts- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.EmojiConverter(*args, **kwargs)¶
-
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 genericBadArgument
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.PartialEmojiConverter(*args, **kwargs)¶
-
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 genericBadArgument
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
- class discord.ext.commands.ThreadConverter(*args, **kwargs)¶
-
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 name.
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.GuildStickerConverter(*args, **kwargs)¶
-
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.
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.ScheduledEventConverter(*args, **kwargs)¶
-
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.
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.clean_content(*, fix_channel_mentions=False, use_nicknames=True, escape_markdown=False, remove_markdown=False)¶
-
Converts the argument to mention scrubbed version of
said content.This behaves similarly to
clean_content
.- fix_channel_mentions¶
-
Whether to clean channel mentions.
- Type
-
bool
- use_nicknames¶
-
Whether to use nicknames when transforming mentions.
- Type
-
bool
- escape_markdown¶
-
Whether to also escape special markdown characters.
- Type
-
bool
- remove_markdown¶
-
Whether to also remove special markdown characters. This option is not supported with
escape_markdown
New in version 1.7.
- Type
-
bool
- await convert(ctx, argument)¶
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises
-
-
CommandError – A generic exception occurred when converting the argument.
-
BadArgument – The converter failed to convert the argument.
-
- class discord.ext.commands.Greedy¶
-
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 passnumbers
with
[1, 2, 3, 4, 5, 6]
andreason
withhello
.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.
- class discord.ext.commands.Range¶
-
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.
Inside a
HybridCommand
this functions equivalently todiscord.app_commands.Range
.If the value cannot be converted to the provided type or is outside the given range,
BadArgument
orRangeError
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}')
-
- await discord.ext.commands.run_converters(ctx, converter, argument, param)¶
-
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.
- Parameters
-
-
ctx (
Context
) – The invocation context to run the converters under. -
converter (Any) – The converter to run, this corresponds to the annotation in the function.
-
argument (
str
) – The argument to convert to. -
param (
Parameter
) – The parameter being converted. This is mainly for error reporting.
-
- Raises
-
CommandError – The converter failed to convert.
- Returns
-
The resulting conversion.
- Return type
-
Any
Flag Converter¶
- class discord.ext.commands.FlagConverter¶
-
A converter that allows for a user-friendly flag syntax.
The flags are defined using PEP 526 type annotations similar
to thedataclasses
Python module. For more information on
how this converter works, check the appropriate
documentation.- iter(x)
-
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.
- Parameters
-
-
case_insensitive (
bool
) – A class parameter to toggle case insensitivity of the flag parsing.
IfTrue
then flags are parsed in a case insensitive manner.
Defaults toFalse
. -
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:
.
-
- classmethod get_flags()¶
-
Dict[
str
,Flag
]: A mapping of flag name to flag object this converter has.
- classmethod await convert(ctx, argument)¶
-
This function is a coroutine.
The method that actually converters an argument to the flag mapping.
- Parameters
-
-
ctx (
Context
) – The invocation context. -
argument (
str
) – The argument to convert from.
-
- Raises
-
FlagError – A flag related parsing error.
- Returns
-
The flag converter instance with all flags parsed.
- Return type
-
FlagConverter
- class discord.ext.commands.Flag¶
-
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.- name¶
-
The name of the flag.
- Type
-
str
- aliases¶
-
The aliases of the flag name.
- Type
-
List[
str
]
- attribute¶
-
The attribute in the class that corresponds to this flag.
- Type
-
str
- default¶
-
The default value of the flag, if available.
- Type
-
Any
- annotation¶
-
The underlying evaluated annotation of the flag.
- Type
-
Any
- max_args¶
-
The maximum number of arguments the flag can accept.
A negative value indicates an unlimited amount of arguments.- Type
-
int
- override¶
-
Whether multiple given values overrides the previous value.
- Type
-
bool
- description¶
-
The description of the flag. Shown for hybrid commands when they’re
used as application commands.- Type
-
str
- property required¶
-
Whether the flag is required.
A required flag has no default value.
- Type
-
bool
- discord.ext.commands.flag(*, name=…, aliases=…, default=…, max_args=…, override=…, converter=…, description=…)¶
-
Override default functionality and parameters of the underlying
FlagConverter
class attributes.- Parameters
-
-
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.
-
Defaults¶
Methods
-
asyncget_default -
defreplace
- class discord.ext.commands.Parameter¶
-
A class that stores information on a
Command
‘s parameter.This is a subclass of
inspect.Parameter
.New in version 2.0.
- replace(*, name=…, kind=…, default=…, annotation=…, description=…, displayed_default=…)¶
-
Creates a customized copy of the Parameter.
- property name¶
-
The parameter’s name.
- property kind¶
-
The parameter’s kind.
- property default¶
-
The parameter’s default.
- property annotation¶
-
The parameter’s annotation.
- property required¶
-
Whether this parameter is required.
- Type
-
bool
- property converter¶
-
The converter that should be used for this parameter.
- property description¶
-
The description of this parameter.
- Type
-
Optional[
str
]
- property displayed_default¶
-
The displayed default in
Command.signature
.- Type
-
Optional[
str
]
- await get_default(ctx)¶
-
This function is a coroutine.
Gets this parameter’s default value.
- Parameters
-
ctx (
Context
) – The invocation context that is used to get the default argument.
- discord.ext.commands.parameter(*, converter=…, default=…, description=…, displayed_default=…)¶
-
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:')
- Parameters
-
-
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
positionalContext
argument. -
description (
str
) – The description of this parameter. -
displayed_default (
str
) – The displayed default inCommand.signature
.
-
- discord.ext.commands.param(*, converter, default, description, displayed_default)¶
-
param(*, converter=…, default=…, description=…, displayed_default=…)
An alias for
parameter()
.New in version 2.0.
- discord.ext.commands.Author¶
-
A default
Parameter
which returns theauthor
for this context.New in version 2.0.
- discord.ext.commands.CurrentChannel¶
-
A default
Parameter
which returns thechannel
for this context.New in version 2.0.
- discord.ext.commands.CurrentGuild¶
-
A default
Parameter
which returns theguild
for this context. This will never beNone
. If the command is called in a DM context thenNoPrivateMessage
is raised to the error handlers.New in version 2.0.
Exceptions¶
- exception discord.ext.commands.CommandError(message=None, *args)¶
-
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
fromBot
,on_command_error()
.
- exception discord.ext.commands.ConversionError(converter, original)¶
-
Exception raised when a Converter class raises non-CommandError.
This inherits from
CommandError
.- converter¶
-
The converter that failed.
- Type
-
discord.ext.commands.Converter
- original¶
-
The original exception that was raised. You can also get this via
the__cause__
attribute.- Type
-
Exception
- exception discord.ext.commands.MissingRequiredArgument(param)¶
-
Exception raised when parsing a command and a parameter
that is required is not encountered.This inherits from
UserInputError
- param¶
-
The argument that is missing.
- Type
-
Parameter
- exception discord.ext.commands.MissingRequiredAttachment(param)¶
-
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.
- param¶
-
The argument that is missing an attachment.
- Type
-
Parameter
- exception discord.ext.commands.ArgumentParsingError(message=None, *args)¶
-
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.
- exception discord.ext.commands.UnexpectedQuoteError(quote)¶
-
An exception raised when the parser encounters a quote mark inside a non-quoted string.
This inherits from
ArgumentParsingError
.- quote¶
-
The quote mark that was found inside the non-quoted string.
- Type
-
str
- exception discord.ext.commands.InvalidEndOfQuotedStringError(char)¶
-
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
.- char¶
-
The character found instead of the expected string.
- Type
-
str
- exception discord.ext.commands.ExpectedClosingQuoteError(close_quote)¶
-
An exception raised when a quote character is expected but not found.
This inherits from
ArgumentParsingError
.- close_quote¶
-
The quote character expected.
- Type
-
str
- exception discord.ext.commands.BadArgument(message=None, *args)¶
-
Exception raised when a parsing or conversion failure is encountered
on an argument to pass into a command.This inherits from
UserInputError
- exception discord.ext.commands.BadUnionArgument(param, converters, errors)¶
-
Exception raised when a
typing.Union
converter fails for all
its associated types.This inherits from
UserInputError
- param¶
-
The parameter that failed being converted.
- Type
-
inspect.Parameter
- converters¶
-
A tuple of converters attempted in conversion, in order of failure.
- Type
-
Tuple[Type,
...
]
- errors¶
-
A list of errors that were caught from failing the conversion.
- Type
-
List[
CommandError
]
- exception discord.ext.commands.BadLiteralArgument(param, literals, errors)¶
-
Exception raised when a
typing.Literal
converter fails for all
its associated values.This inherits from
UserInputError
New in version 2.0.
- param¶
-
The parameter that failed being converted.
- Type
-
inspect.Parameter
- literals¶
-
A tuple of values compared against in conversion, in order of failure.
- Type
-
Tuple[Any,
...
]
- errors¶
-
A list of errors that were caught from failing the conversion.
- Type
-
List[
CommandError
]
- exception discord.ext.commands.PrivateMessageOnly(message=None)¶
-
Exception raised when an operation does not work outside of private
message contexts.This inherits from
CheckFailure
- exception discord.ext.commands.NoPrivateMessage(message=None)¶
-
Exception raised when an operation does not work in private message
contexts.This inherits from
CheckFailure
- exception discord.ext.commands.CheckFailure(message=None, *args)¶
-
Exception raised when the predicates in
Command.checks
have failed.This inherits from
CommandError
- exception discord.ext.commands.CheckAnyFailure(checks, errors)¶
-
Exception raised when all predicates in
check_any()
fail.This inherits from
CheckFailure
.New in version 1.3.
- errors¶
-
A list of errors that were caught during execution.
- Type
-
List[
CheckFailure
]
- checks¶
-
A list of check predicates that failed.
- Type
-
List[Callable[[
Context
],bool
]]
- exception discord.ext.commands.CommandNotFound(message=None, *args)¶
-
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 discord.ext.commands.DisabledCommand(message=None, *args)¶
-
Exception raised when the command being invoked is disabled.
This inherits from
CommandError
- exception discord.ext.commands.CommandInvokeError(e)¶
-
Exception raised when the command being invoked raised an exception.
This inherits from
CommandError
- original¶
-
The original exception that was raised. You can also get this via
the__cause__
attribute.- Type
-
Exception
- exception discord.ext.commands.TooManyArguments(message=None, *args)¶
-
Exception raised when the command was passed too many arguments and its
Command.ignore_extra
attribute was not set toTrue
.This inherits from
UserInputError
- exception discord.ext.commands.UserInputError(message=None, *args)¶
-
The base exception type for errors that involve errors
regarding user input.This inherits from
CommandError
.
- exception discord.ext.commands.CommandOnCooldown(cooldown, retry_after, type)¶
-
Exception raised when the command being invoked is on cooldown.
This inherits from
CommandError
- cooldown¶
-
A class with attributes
rate
andper
similar to the
cooldown()
decorator.- Type
-
Cooldown
- type¶
-
The type associated with the cooldown.
- Type
-
BucketType
- retry_after¶
-
The amount of seconds to wait before you can retry again.
- Type
-
float
- exception discord.ext.commands.MaxConcurrencyReached(number, per)¶
-
Exception raised when the command being invoked has reached its maximum concurrency.
This inherits from
CommandError
.- number¶
-
The maximum number of concurrent invokers allowed.
- Type
-
int
- per¶
-
The bucket type passed to the
max_concurrency()
decorator.- Type
-
BucketType
- exception discord.ext.commands.NotOwner(message=None, *args)¶
-
Exception raised when the message author is not the owner of the bot.
This inherits from
CheckFailure
- exception discord.ext.commands.MessageNotFound(argument)¶
-
Exception raised when the message provided was not found in the channel.
This inherits from
BadArgument
New in version 1.5.
- argument¶
-
The message supplied by the caller that was not found
- Type
-
str
- exception discord.ext.commands.MemberNotFound(argument)¶
-
Exception raised when the member provided was not found in the bot’s
cache.This inherits from
BadArgument
New in version 1.5.
- argument¶
-
The member supplied by the caller that was not found
- Type
-
str
- exception discord.ext.commands.GuildNotFound(argument)¶
-
Exception raised when the guild provided was not found in the bot’s cache.
This inherits from
BadArgument
New in version 1.7.
- argument¶
-
The guild supplied by the called that was not found
- Type
-
str
- exception discord.ext.commands.UserNotFound(argument)¶
-
Exception raised when the user provided was not found in the bot’s
cache.This inherits from
BadArgument
New in version 1.5.
- argument¶
-
The user supplied by the caller that was not found
- Type
-
str
- exception discord.ext.commands.ChannelNotFound(argument)¶
-
Exception raised when the bot can not find the channel.
This inherits from
BadArgument
New in version 1.5.
- argument¶
-
The channel supplied by the caller that was not found
- Type
-
Union[
int
,str
]
- exception discord.ext.commands.ChannelNotReadable(argument)¶
-
Exception raised when the bot does not have permission to read messages
in the channel.This inherits from
BadArgument
New in version 1.5.
- argument¶
-
The channel supplied by the caller that was not readable
- Type
-
Union[
abc.GuildChannel
,Thread
]
- exception discord.ext.commands.ThreadNotFound(argument)¶
-
Exception raised when the bot can not find the thread.
This inherits from
BadArgument
New in version 2.0.
- argument¶
-
The thread supplied by the caller that was not found
- Type
-
str
- exception discord.ext.commands.BadColourArgument(argument)¶
-
Exception raised when the colour is not valid.
This inherits from
BadArgument
New in version 1.5.
- argument¶
-
The colour supplied by the caller that was not valid
- Type
-
str
- exception discord.ext.commands.RoleNotFound(argument)¶
-
Exception raised when the bot can not find the role.
This inherits from
BadArgument
New in version 1.5.
- argument¶
-
The role supplied by the caller that was not found
- Type
-
str
- exception discord.ext.commands.BadInviteArgument(argument)¶
-
Exception raised when the invite is invalid or expired.
This inherits from
BadArgument
New in version 1.5.
- argument¶
-
The invite supplied by the caller that was not valid
- Type
-
str
- exception discord.ext.commands.EmojiNotFound(argument)¶
-
Exception raised when the bot can not find the emoji.
This inherits from
BadArgument
New in version 1.5.
- argument¶
-
The emoji supplied by the caller that was not found
- Type
-
str
- exception discord.ext.commands.PartialEmojiConversionFailure(argument)¶
-
Exception raised when the emoji provided does not match the correct
format.This inherits from
BadArgument
New in version 1.5.
- argument¶
-
The emoji supplied by the caller that did not match the regex
- Type
-
str
- exception discord.ext.commands.GuildStickerNotFound(argument)¶
-
Exception raised when the bot can not find the sticker.
This inherits from
BadArgument
New in version 2.0.
- argument¶
-
The sticker supplied by the caller that was not found
- Type
-
str
- exception discord.ext.commands.ScheduledEventNotFound(argument)¶
-
Exception raised when the bot can not find the scheduled event.
This inherits from
BadArgument
New in version 2.0.
- argument¶
-
The event supplied by the caller that was not found
- Type
-
str
- exception discord.ext.commands.BadBoolArgument(argument)¶
-
Exception raised when a boolean argument was not convertable.
This inherits from
BadArgument
New in version 1.5.
- argument¶
-
The boolean argument supplied by the caller that is not in the predefined list
- Type
-
str
- exception discord.ext.commands.RangeError(value, minimum, maximum)¶
-
Exception raised when an argument is out of range.
This inherits from
BadArgument
New in version 2.0.
- minimum¶
-
The minimum value expected or
None
if there wasn’t one- Type
-
Optional[Union[
int
,float
]]
- maximum¶
-
The maximum value expected or
None
if there wasn’t one- Type
-
Optional[Union[
int
,float
]]
- value¶
-
The value that was out of range.
- Type
-
Union[
int
,float
,str
]
- exception discord.ext.commands.MissingPermissions(missing_permissions, *args)¶
-
Exception raised when the command invoker lacks permissions to run a
command.This inherits from
CheckFailure
- missing_permissions¶
-
The required permissions that are missing.
- Type
-
List[
str
]
- exception discord.ext.commands.BotMissingPermissions(missing_permissions, *args)¶
-
Exception raised when the bot’s member lacks permissions to run a
command.This inherits from
CheckFailure
- missing_permissions¶
-
The required permissions that are missing.
- Type
-
List[
str
]
- exception discord.ext.commands.MissingRole(missing_role)¶
-
Exception raised when the command invoker lacks a role to run a command.
This inherits from
CheckFailure
New in version 1.1.
- missing_role¶
-
The required role that is missing.
This is the parameter passed tohas_role()
.- Type
-
Union[
str
,int
]
- exception discord.ext.commands.BotMissingRole(missing_role)¶
-
Exception raised when the bot’s member lacks a role to run a command.
This inherits from
CheckFailure
New in version 1.1.
- missing_role¶
-
The required role that is missing.
This is the parameter passed tohas_role()
.- Type
-
Union[
str
,int
]
- exception discord.ext.commands.MissingAnyRole(missing_roles)¶
-
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.
- missing_roles¶
-
The roles that the invoker is missing.
These are the parameters passed tohas_any_role()
.- Type
-
List[Union[
str
,int
]]
- exception discord.ext.commands.BotMissingAnyRole(missing_roles)¶
-
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.
- missing_roles¶
-
The roles that the bot’s member is missing.
These are the parameters passed tohas_any_role()
.- Type
-
List[Union[
str
,int
]]
- exception discord.ext.commands.NSFWChannelRequired(channel)¶
-
Exception raised when a channel does not have the required NSFW setting.
This inherits from
CheckFailure
.New in version 1.1.
- channel¶
-
The channel that does not have NSFW enabled.
- Type
-
Union[
abc.GuildChannel
,Thread
]
- exception discord.ext.commands.FlagError(message=None, *args)¶
-
The base exception type for all flag parsing related errors.
This inherits from
BadArgument
.New in version 2.0.
- exception discord.ext.commands.BadFlagArgument(flag, argument, original)¶
-
An exception raised when a flag failed to convert a value.
This inherits from
FlagError
New in version 2.0.
- flag¶
-
The flag that failed to convert.
- Type
-
Flag
- argument¶
-
The argument supplied by the caller that was not able to be converted.
- Type
-
str
- original¶
-
The original exception that was raised. You can also get this via
the__cause__
attribute.- Type
-
Exception
- exception discord.ext.commands.MissingFlagArgument(flag)¶
-
An exception raised when a flag did not get a value.
This inherits from
FlagError
New in version 2.0.
- flag¶
-
The flag that did not get a value.
- Type
-
Flag
- exception discord.ext.commands.TooManyFlags(flag, values)¶
-
An exception raised when a flag has received too many values.
This inherits from
FlagError
.New in version 2.0.
- flag¶
-
The flag that received too many values.
- Type
-
Flag
- values¶
-
The values that were passed.
- Type
-
List[
str
]
- exception discord.ext.commands.MissingRequiredFlag(flag)¶
-
An exception raised when a required flag was not given.
This inherits from
FlagError
New in version 2.0.
- flag¶
-
The required flag that was not found.
- Type
-
Flag
- exception discord.ext.commands.ExtensionError(message=None, *args, name)¶
-
Base exception for extension related errors.
This inherits from
DiscordException
.- name¶
-
The extension that had an error.
- Type
-
str
- exception discord.ext.commands.ExtensionAlreadyLoaded(name)¶
-
An exception raised when an extension has already been loaded.
This inherits from
ExtensionError
- exception discord.ext.commands.ExtensionNotLoaded(name)¶
-
An exception raised when an extension was not loaded.
This inherits from
ExtensionError
- exception discord.ext.commands.NoEntryPointError(name)¶
-
An exception raised when an extension does not have a
setup
entry point function.This inherits from
ExtensionError
- exception discord.ext.commands.ExtensionFailed(name, original)¶
-
An exception raised when an extension failed to load during execution of the module or
setup
entry point.This inherits from
ExtensionError
- name¶
-
The extension that had the error.
- Type
-
str
- original¶
-
The original exception that was raised. You can also get this via
the__cause__
attribute.- Type
-
Exception
- exception discord.ext.commands.ExtensionNotFound(name)¶
-
An exception raised when an extension is not found.
This inherits from
ExtensionError
Changed in version 1.3: Made the
original
attribute always None.- name¶
-
The extension that had the error.
- Type
-
str
- exception discord.ext.commands.CommandRegistrationError(name, *, alias_conflict=False)¶
-
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.
- name¶
-
The command name that had the error.
- Type
-
str
- alias_conflict¶
-
Whether the name that conflicts is an alias of the command we try to add.
- Type
-
bool
- exception discord.ext.commands.HybridCommandError(original)¶
-
An exception raised when a
HybridCommand
raises
anAppCommandError
derived exception that could not be
sufficiently converted to an equivalentCommandError
exception.New in version 2.0.
- original¶
-
The original exception that was raised. You can also get this via
the__cause__
attribute.- Type
-
AppCommandError
Exception Hierarchy¶
-
DiscordException
-
-
CommandError
-
-
ConversionError
-
UserInputError
-
-
MissingRequiredArgument
-
MissingRequiredAttachment
-
TooManyArguments
-
BadArgument
-
-
MessageNotFound
-
MemberNotFound
-
GuildNotFound
-
UserNotFound
-
ChannelNotFound
-
ChannelNotReadable
-
BadColourArgument
-
RoleNotFound
-
BadInviteArgument
-
EmojiNotFound
-
GuildStickerNotFound
-
ScheduledEventNotFound
-
PartialEmojiConversionFailure
-
BadBoolArgument
-
RangeError
-
ThreadNotFound
-
FlagError
-
-
BadFlagArgument
-
MissingFlagArgument
-
TooManyFlags
-
MissingRequiredFlag
-
-
-
BadUnionArgument
-
BadLiteralArgument
-
ArgumentParsingError
-
-
UnexpectedQuoteError
-
InvalidEndOfQuotedStringError
-
ExpectedClosingQuoteError
-
-
-
CommandNotFound
-
CheckFailure
-
-
CheckAnyFailure
-
PrivateMessageOnly
-
NoPrivateMessage
-
NotOwner
-
MissingPermissions
-
BotMissingPermissions
-
MissingRole
-
BotMissingRole
-
MissingAnyRole
-
BotMissingAnyRole
-
NSFWChannelRequired
-
-
DisabledCommand
-
CommandInvokeError
-
CommandOnCooldown
-
MaxConcurrencyReached
-
HybridCommandError
-
-
ExtensionError
-
-
ExtensionAlreadyLoaded
-
ExtensionNotLoaded
-
NoEntryPointError
-
ExtensionFailed
-
ExtensionNotFound
-
-
-
ClientException
-
-
CommandRegistrationError
-
I am trying to send a message when a command is not found but it is not working:
@client.event
async def on_ready():
change_status.start()
print("----------------------")
print("Logged In As")
print("Username: %s" % client.user.name)
print("ID: %s" % client.user.id)
print("----------------------")
async def on_message(ctx, error):
if isinstance(error, commands.CommandNotFound):
text = ('Sorry {}, this command does not exist check $help for a more detailed list of').format(ctx.author.mention)
msg = await ctx.send(text)
await ctx.message.delete()
await asyncio.sleep(5)
await msg.delete()
else:
pass
raise error
asked Nov 25, 2020 at 14:49
You’re looking for on_command_error
event
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send("Command does not exist.")
Reference:
- on_command_error
answered Nov 25, 2020 at 15:10
4
I have found an answer to my issue instead of running it through a client.event decorator, I have ran it through a client.listen, decorator:
@client.event
async def on_ready():
change_status.start()
print("----------------------")
print("Logged In As")
print("Username: %s" % client.user.name)
print("ID: %s" % client.user.id)
print("----------------------")
@client.listen()
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
text = ('Sorry {}, this command does not exist check $help for a more detailed list of').format(ctx.author.mention)
msg = await ctx.send(text)
await ctx.message.delete()
await asyncio.sleep(5)
await msg.delete()
answered Nov 25, 2020 at 16:49
LucasLucas
412 silver badges9 bronze badges
The on_command_error
event is called when an error happens on any command.
and inside the on_command_error
event you can check whether the error is an instance of CommandNotFound
, which is thrown when the typed command is not found, or it doesn’t exist. And if so, you can send a message to the channel, where the command was used.
@client.event
async def on_command_error(ctx, error):
"""Command error handler"""
embed = discord.Embed(color=discord.Color.red())
if isinstance(error, commands.CommandNotFound):
embed.title = "Command not Found"
embed.description = "Recheck what you've typed."
#await ctx.send(embed=embed)
answered Nov 26, 2020 at 6:31
BillyBilly
1,1211 gold badge8 silver badges18 bronze badges
Содержание
- CommandsВ¶
- ParametersВ¶
- PositionalВ¶
- VariableВ¶
- Keyword-Only ArgumentsВ¶
- Invocation ContextВ¶
- ConvertersВ¶
- Basic ConvertersВ¶
- boolВ¶
- Advanced ConvertersВ¶
- Inline Advanced ConvertersВ¶
- Discord ConvertersВ¶
- Special ConvertersВ¶
- typing.UnionВ¶
- typing.OptionalВ¶
- typing.LiteralВ¶
- typing.AnnotatedВ¶
- GreedyВ¶
- discord.AttachmentВ¶
- FlagConverterВ¶
- typing.ListВ¶
- typing.TupleВ¶
- typing.DictВ¶
- Hybrid Command InteractionВ¶
- Parameter MetadataВ¶
- Error HandlingВ¶
- ChecksВ¶
- Global ChecksВ¶
- Hybrid CommandsВ¶
CommandsВ¶
One of the most appealing aspects of the command extension is how easy it is to define commands and how you can arbitrarily nest groups and commands to have a rich sub-command system.
Commands are defined by attaching it to a regular Python function. The command is then invoked by the user using a similar signature to the Python function.
You must have access to the message_content intent for the commands extension to function. This must be set both in the developer portal and within your code.
Failure to do this will result in your bot not responding to any of your commands.
For example, in the given command definition:
With the following prefix ( $ ), it would be invoked by the user via:
A command must always have at least one parameter, ctx , which is the Context as the first one.
There are two ways of registering a command. The first one is by using Bot.command() decorator, as seen in the example above. The second is using the command() decorator followed by Bot.add_command() on the instance.
Essentially, these two are equivalent:
Since the Bot.command() decorator is shorter and easier to comprehend, it will be the one used throughout the documentation here.
Any parameter that is accepted by the Command constructor can be passed into the decorator. For example, to change the name to something other than the function would be as simple as doing this:
ParametersВ¶
Since we define commands by making Python functions, we also define the argument passing behaviour by the function parameters.
Certain parameter types do different things in the user side and most forms of parameter types are supported.
PositionalВ¶
The most basic form of parameter passing is the positional parameter. This is where we pass a parameter as-is:
On the bot using side, you can provide positional arguments by just passing a regular string:
To make use of a word with spaces in between, you should quote it:
As a note of warning, if you omit the quotes, you will only get the first word:
Since positional arguments are just regular Python arguments, you can have as many as you want:
VariableВ¶
Sometimes you want users to pass in an undetermined number of parameters. The library supports this similar to how variable list parameters are done in Python:
This allows our user to accept either one or many arguments as they please. This works similar to positional arguments, so multi-word parameters should be quoted.
For example, on the bot side:
If the user wants to input a multi-word argument, they have to quote it like earlier:
Do note that similar to the Python function behaviour, a user can technically pass no arguments at all:
Since the args variable is a tuple , you can do anything you would usually do with one.
Keyword-Only ArgumentsВ¶
When you want to handle parsing of the argument yourself or do not feel like you want to wrap multi-word user input into quotes, you can ask the library to give you the rest as a single argument. We do this by using a keyword-only argument, seen below:
You can only have one keyword-only argument due to parsing ambiguities.
On the bot side, we do not need to quote input with spaces:
Do keep in mind that wrapping it in quotes leaves it as-is:
By default, the keyword-only arguments are stripped of white space to make it easier to work with. This behaviour can be toggled by the Command.rest_is_raw argument in the decorator.
Invocation ContextВ¶
As seen earlier, every command must take at least a single parameter, called the Context .
This parameter gives you access to something called the “invocation context”. Essentially all the information you need to know how the command was executed. It contains a lot of useful information:
Context.guild returns the Guild of the command, if any.
Context.message returns the Message of the command.
Context.author returns the Member or User that called the command.
Context.send() to send a message to the channel the command was used in.
The context implements the abc.Messageable interface, so anything you can do on a abc.Messageable you can do on the Context .
ConvertersВ¶
Adding bot arguments with function parameters is only the first step in defining your bot’s command interface. To actually make use of the arguments, we usually want to convert the data into a target type. We call these Converters .
Converters come in a few flavours:
A regular callable object that takes an argument as a sole parameter and returns a different type.
These range from your own function, to something like bool or int .
A custom class that inherits from Converter .
Basic ConvertersВ¶
At its core, a basic converter is a callable that takes in an argument and turns it into something else.
For example, if we wanted to add two numbers together, we could request that they are turned into integers for us by specifying the converter:
We specify converters by using something called a function annotation. This is a Python 3 exclusive feature that was introduced in PEP 3107.
This works with any callable, such as a function that would convert a string to all upper-case:
boolВ¶
Unlike the other basic converters, the bool converter is treated slightly different. Instead of casting directly to the bool type, which would result in any non-empty argument returning True , it instead evaluates the argument as True or False based on its given content:
Advanced ConvertersВ¶
Sometimes a basic converter doesn’t have enough information that we need. For example, sometimes we want to get some information from the Message that called the command or we want to do some asynchronous processing.
For this, the library provides the Converter interface. This allows you to have access to the Context and have the callable be asynchronous. Defining a custom converter using this interface requires overriding a single method, Converter.convert() .
An example converter:
The converter provided can either be constructed or not. Essentially these two are equivalent:
Having the possibility of the converter be constructed allows you to set up some state in the converter’s __init__ for fine tuning the converter. An example of this is actually in the library, clean_content .
If a converter fails to convert an argument to its designated target type, the BadArgument exception must be raised.
Inline Advanced ConvertersВ¶
If we don’t want to inherit from Converter , we can still provide a converter that has the advanced functionalities of an advanced converter and save us from specifying two types.
For example, a common idiom would be to have a class and a converter for that class:
This can get tedious, so an inline advanced converter is possible through a classmethod() inside the type:
Discord ConvertersВ¶
Working with Discord Models is a fairly common thing when defining commands, as a result the library makes working with them easy.
For example, to receive a Member you can just pass it as a converter:
When this command is executed, it attempts to convert the string given into a Member and then passes it as a parameter for the function. This works by checking if the string is a mention, an ID, a nickname, a username + discriminator, or just a regular username. The default set of converters have been written to be as easy to use as possible.
A lot of discord models work out of the gate as a parameter:
Having any of these set as the converter will intelligently convert the argument to the appropriate target type you specify.
Under the hood, these are implemented by the Advanced Converters interface. A table of the equivalent converter is given below:
By providing the converter it allows us to use them as building blocks for another converter:
Special ConvertersВ¶
The command extension also has support for certain converters to allow for more advanced and intricate use cases that go beyond the generic linear parsing. These converters allow you to introduce some more relaxed and dynamic grammar to your commands in an easy to use manner.
typing.UnionВ¶
A typing.Union is a special type hint that allows for the command to take in any of the specific types instead of a singular type. For example, given the following:
The what parameter would either take a discord.TextChannel converter or a discord.Member converter. The way this works is through a left-to-right order. It first attempts to convert the input to a discord.TextChannel , and if it fails it tries to convert it to a discord.Member . If all converters fail, then a special error is raised, BadUnionArgument .
Note that any valid converter discussed above can be passed in to the argument list of a typing.Union .
typing.OptionalВ¶
A typing.Optional is a special type hint that allows for “back-referencing” behaviour. If the converter fails to parse into the specified type, the parser will skip the parameter and then either None or the specified default will be passed into the parameter instead. The parser will then continue on to the next parameters and converters, if any.
Consider the following example:
In this example, since the argument could not be converted into an int , the default of 99 is passed and the parser resumes handling, which in this case would be to pass it into the liquid parameter.
This converter only works in regular positional parameters, not variable parameters or keyword-only parameters.
typing.LiteralВ¶
New in version 2.0.
A typing.Literal is a special type hint that requires the passed parameter to be equal to one of the listed values after being converted to the same type. For example, given the following:
The buy_sell parameter must be either the literal string «buy» or «sell» and amount must convert to the int 1 or 2 . If buy_sell or amount don’t match any value, then a special error is raised, BadLiteralArgument . Any literal values can be mixed and matched within the same typing.Literal converter.
Note that typing.Literal[True] and typing.Literal[False] still follow the bool converter rules.
typing.AnnotatedВ¶
New in version 2.0.
A typing.Annotated is a special type introduced in Python 3.9 that allows the type checker to see one type, but allows the library to see another type. This is useful for appeasing the type checker for complicated converters. The second parameter of Annotated must be the converter that the library should use.
For example, given the following:
The type checker will see arg as a regular str but the library will know you wanted to change the input into all upper-case.
For Python versions below 3.9, it is recommended to install the typing_extensions library and import Annotated from there.
GreedyВ¶
The Greedy converter is a generalisation of the typing.Optional converter, except applied to a list of arguments. In simple terms, this means that it tries to convert as much as it can until it can’t convert any further.
Consider the following example:
When invoked, it allows for any number of members to be passed in:
The type passed when using this converter depends on the parameter type that it is being attached to:
Positional parameter types will receive either the default parameter or a list of the converted values.
Variable parameter types will be a tuple as usual.
Keyword-only parameter types will be the same as if Greedy was not passed at all.
Greedy parameters can also be made optional by specifying an optional value.
When mixed with the typing.Optional converter you can provide simple and expressive command invocation syntaxes:
This command can be invoked any of the following ways:
The usage of Greedy and typing.Optional are powerful and useful, however as a price, they open you up to some parsing ambiguities that might surprise some people.
For example, a signature expecting a typing.Optional of a discord.Member followed by a int could catch a member named after a number due to the different ways a MemberConverter decides to fetch members. You should take care to not introduce unintended parsing ambiguities in your code. One technique would be to clamp down the expected syntaxes allowed through custom converters or reordering the parameters to minimise clashes.
To help aid with some parsing ambiguities, str , None , typing.Optional and Greedy are forbidden as parameters for the Greedy converter.
discord.AttachmentВ¶
New in version 2.0.
The discord.Attachment converter is a special converter that retrieves an attachment from the uploaded attachments on a message. This converter does not look at the message content at all and just the uploaded attachments.
Consider the following example:
When this command is invoked, the user must directly upload a file for the command body to be executed. When combined with the typing.Optional converter, the user does not have to provide an attachment.
This also works with multiple attachments:
In this example the user must provide at least one file but the second one is optional.
As a special case, using Greedy will return the remaining attachments in the message, if any.
Note that using a discord.Attachment converter after a Greedy of discord.Attachment will always fail since the greedy had already consumed the remaining attachments.
If an attachment is expected but not given, then MissingRequiredAttachment is raised to the error handlers.
FlagConverterВ¶
New in version 2.0.
A FlagConverter allows the user to specify user-friendly “flags” using PEP 526 type annotations or a syntax more reminiscent of the dataclasses module.
For example, the following code:
Allows the user to invoke the command using a simple flag-like syntax:
Flags use a syntax that allows the user to not require quotes when passing in values to the flag. The goal of the flag syntax is to be as user-friendly as possible. This makes flags a good choice for complicated commands that can have multiple knobs to turn or simulating keyword-only parameters in your external command interface. It is recommended to use keyword-only parameters with the flag converter. This ensures proper parsing and behaviour with quoting.
Internally, the FlagConverter class examines the class to find flags. A flag can either be a class variable with a type annotation or a class variable that’s been assigned the result of the flag() function. These flags are then used to define the interface that your users will use. The annotations correspond to the converters that the flag arguments must adhere to.
For most use cases, no extra work is required to define flags. However, if customisation is needed to control the flag name or the default value then the flag() function can come in handy:
This tells the parser that the members attribute is mapped to a flag named member and that the default value is an empty list. For greater customisability, the default can either be a value or a callable that takes the Context as a sole parameter. This callable can either be a function or a coroutine.
In order to customise the flag syntax we also have a few options that can be passed to the class parameter list:
Despite the similarities in these examples to command like arguments, the syntax and parser is not a command line parser. The syntax is mainly inspired by Discord’s search bar input and as a result all flags need a corresponding value.
Flag converters will only raise FlagError derived exceptions. If an error is raised while converting a flag, BadFlagArgument is raised instead and the original exception can be accessed with the original attribute.
The flag converter is similar to regular commands and allows you to use most types of converters (with the exception of Greedy ) as the type annotation. Some extra support is added for specific annotations as described below.
typing.ListВ¶
If a list is given as a flag annotation it tells the parser that the argument can be passed multiple times.
For example, augmenting the example above:
This is called by repeatedly specifying the flag:
typing.TupleВ¶
Since the above syntax can be a bit repetitive when specifying a flag many times, the tuple type annotation allows for “greedy-like” semantics using a variadic tuple:
This allows the previous ban command to be called like this:
The tuple annotation also allows for parsing of pairs. For example, given the following code:
Due to potential parsing ambiguities, the parser expects tuple arguments to be quoted if they require spaces. So if one of the inner types is str and the argument requires spaces then quotes should be used to disambiguate it from the other element of the tuple.
typing.DictВ¶
A dict annotation is functionally equivalent to List[Tuple[K, V]] except with the return type given as a dict rather than a list .
Hybrid Command InteractionВ¶
When used as a hybrid command, the parameters are flattened into different parameters for the application command. For example, the following converter:
Would be equivalent to an application command defined as this:
This means that decorators that refer to a parameter by name will use the flag name instead:
For ease of use, the flag() function accepts a description keyword argument to allow you to pass descriptions inline:
Likewise, use of the name keyword argument allows you to pass renames for the parameter, similar to the rename() decorator.
Note that in hybrid command form, a few annotations are unsupported due to Discord limitations:
Only one flag converter is supported per hybrid command. Due to the flag converter’s way of working, it is unlikely for a user to have two of them in one signature.
parameter() assigns custom metadata to a Command ’s parameter.
This is useful for:
Custom converters as annotating a parameter with a custom converter works at runtime, type checkers don’t like it because they can’t understand what’s going on.
However, fear not we can use parameter() to tell type checkers what’s going on.
Late binding behaviour
Because this is such a common use-case, the library provides Author , CurrentChannel and CurrentGuild , armed with this we can simplify wave to:
Author and co also have other benefits like having the displayed default being filled.
Error HandlingВ¶
When our commands fail to parse we will, by default, receive a noisy error in stderr of our console that tells us that an error has happened and has been silently ignored.
In order to handle our errors, we must use something called an error handler. There is a global error handler, called on_command_error() which works like any other event in the Event Reference . This global error handler is called for every error reached.
Most of the time however, we want to handle an error local to the command itself. Luckily, commands come with local error handlers that allow us to do just that. First we decorate an error handler function with error() :
The first parameter of the error handler is the Context while the second one is an exception that is derived from CommandError . A list of errors is found in the Exceptions page of the documentation.
ChecksВ¶
There are cases when we don’t want a user to use our commands. They don’t have permissions to do so or maybe we blocked them from using our bot earlier. The commands extension comes with full support for these things in a concept called a Checks .
A check is a basic predicate that can take in a Context as its sole parameter. Within it, you have the following options:
Return True to signal that the person can run the command.
Return False to signal that the person cannot run the command.
Raise a CommandError derived exception to signal the person cannot run the command.
This allows you to have custom error messages for you to handle in the error handlers .
To register a check for a command, we would have two ways of doing so. The first is using the check() decorator. For example:
This would only evaluate the command if the function is_owner returns True . Sometimes we re-use a check often and want to split it into its own decorator. To do that we can just add another level of depth:
Since an owner check is so common, the library provides it for you ( is_owner() ):
When multiple checks are specified, all of them must be True :
If any of those checks fail in the example above, then the command will not be run.
When an error happens, the error is propagated to the error handlers . If you do not raise a custom CommandError derived exception, then it will get wrapped up into a CheckFailure exception as so:
If you want a more robust error system, you can derive from the exception and raise it instead of returning False :
Since having a guild_only decorator is pretty common, it comes built-in via guild_only() .
Global ChecksВ¶
Sometimes we want to apply a check to every command, not just certain commands. The library supports this as well using the global check concept.
Global checks work similarly to regular checks except they are registered with the Bot.check() decorator.
For example, to block all DMs we could do the following:
Be careful on how you write your global checks, as it could also lock you out of your own bot.
Hybrid CommandsВ¶
New in version 2.0.
commands.HybridCommand is a command that can be invoked as both a text and a slash command. This allows you to define a command as both slash and text command without writing separate code for both counterparts.
In order to define a hybrid command, The command callback should be decorated with Bot.hybrid_command() decorator.
The above command can be invoked as both text and slash command. Note that you have to manually sync your CommandTree by calling sync in order for slash commands to appear.
You can create hybrid command groups and sub-commands using the Bot.hybrid_group() decorator.
Due to a Discord limitation, slash command groups cannot be invoked directly so the fallback parameter allows you to create a sub-command that will be bound to callback of parent group.
Due to certain limitations on slash commands, some features of text commands are not supported on hybrid commands. You can define a hybrid command as long as it meets the same subset that is supported for slash commands.
Following are currently not supported by hybrid commands:
Variable number of arguments. e.g. *arg: int
Group commands with a depth greater than 1.
Unions of channel types are allowed
Unions of user types are allowed
Unions of user types with roles are allowed
Apart from that, all other features such as converters, checks, autocomplete, flags etc. are supported on hybrid commands. Note that due to a design constraint, decorators related to application commands such as discord.app_commands.autocomplete() should be placed below the hybrid_command() decorator.
For convenience and ease in writing code, The Context class implements some behavioural changes for various methods and attributes:
Context.interaction can be used to retrieve the slash command interaction.
Since interaction can only be responded to once, The Context.send() automatically determines whether to send an interaction response or a followup response.
Context.defer() defers the interaction response for slash commands but shows typing indicator for text commands.
© Copyright 2015-present, Rapptz. Created using Sphinx 4.4.0.
Источник
The following section outlines the API of discord.py’s command extension module.
Bots
Bot
Attributes
- activity
- allowed_mentions
- application_commands
- cached_messages
- case_insensitive
- cogs
- command_prefix
- commands
- delete_not_existing_commands
- description
- emojis
- extensions
- global_application_commands
- guilds
- help_command
- intents
- latency
- owner_id
- owner_ids
- private_channels
- self_bot
- stickers
- strip_after_prefix
- sync_commands
- sync_commands_on_cog_reload
- user
- users
- voice_clients
Methods
-
defadd_application_cmds_from_cog -
defadd_check -
defadd_cog -
defadd_command -
defadd_commands -
defadd_interaction_listener -
defadd_listener -
@after_invoke -
asyncapplication_info -
asyncbefore_identify_hook -
@before_invoke -
asyncchange_presence -
@check -
@check_once -
defclear -
asyncclose -
@command -
asyncconnect -
asynccreate_guild -
asyncdelete_invite -
@event -
asyncfetch_all_nitro_stickers -
asyncfetch_channel -
asyncfetch_guild -
deffetch_guilds -
asyncfetch_invite -
asyncfetch_template -
asyncfetch_user -
asyncfetch_webhook -
asyncfetch_widget -
defget_all_channels -
defget_all_members -
defget_channel -
defget_cog -
defget_command -
asyncget_context -
defget_emoji -
defget_guild -
defget_message -
defget_partial_messageable -
asyncget_prefix -
defget_user -
@group -
asyncinvoke -
defis_closed -
asyncis_owner -
defis_ready -
defis_ws_ratelimited -
@listen -
defload_extension -
asynclogin -
asynclogout -
@message_command -
asyncon_application_command_error -
@on_click -
asyncon_command_error -
asyncon_error -
@on_select -
@on_submit -
asyncprocess_commands -
defreload_extension -
defreload_extensions -
defremove_application_cmds_from_cog -
defremove_check -
defremove_cog -
defremove_command -
defremove_interaction_listener -
defremove_listener -
asyncrequest_offline_members -
defrun -
@slash_command -
asyncstart -
defunload_extension -
@user_command -
asyncwait_for -
asyncwait_until_ready -
defwalk_commands
- class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)
-
Represents a discord bot.
This class is a subclass of
discord.Client
and as a result
anything that you can do with adiscord.Client
you can do with
this bot.This class also subclasses
GroupMixin
to provide the functionality
to manage commands.- command_prefix
-
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 anddiscord.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
. To avoid confusion empty iterables are not
allowed.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.
- case_insensitive
-
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.- Type:
-
bool
- description
-
The content prefixed into the default help message.
- Type:
-
str
- self_bot
-
If
True
, the bot will only listen to commands invoked by itself rather
than ignoring itself. IfFalse
(the default) then the bot will ignore
itself. This cannot be changed once initialised.- Type:
-
bool
- help_command
-
The help command implementation to use. This can be dynamically
set at runtime. To remove the help command passNone
. For more
information on implementing a help command, see Help Commands.- Type:
-
Optional[
HelpCommand
]
- owner_id
-
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()
.- Type:
-
Optional[
int
]
- owner_ids
-
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 usingapplication_info()
.
For performance reasons it is recommended to use aset
for the collection. You cannot set bothowner_id
andowner_ids
.New in version 1.3.
- Type:
-
Optional[Collection[
int
]]
- strip_after_prefix
-
Whether to strip whitespace characters after encountering the command
prefix. This allows for! hello
and!hello
to both work if
thecommand_prefix
is set to!
. Defaults toFalse
.New in version 1.7.
- Type:
-
bool
- sync_commands
-
Whether to sync application-commands on startup, default
False
.This will register global and guild application-commands(slash-, user- and message-commands)
that are not registered yet, update changes and remove application-commands that could not be found
in the code anymore ifdelete_not_existing_commands
is set toTrue
what it is by default.- Type:
-
bool
- delete_not_existing_commands
-
Whether to remove global and guild-only application-commands that are not in the code anymore, default
True
.- Type:
-
bool
- sync_commands_on_cog_reload
-
Whether to sync global and guild-only application-commands when reloading an extension, default
False
.- Type:
-
bool
- property activity
-
The activity being used upon
logging in.- Type:
-
Optional[
BaseActivity
]
- add_application_cmds_from_cog(cog)
-
Add all application-commands in the given cog to the internal list of application-commands.
- Parameters:
-
cog (
Cog
) – The cog wich application-commands should be added to the internal list of application-commands.
- add_check(func, *, call_once=False)
-
Adds a global check to the bot.
This is the non-decorator interface to
check()
andcheck_once()
.- Parameters:
-
-
func – The function that was used as a global check.
-
call_once (
bool
) – If the function should only be called once per
Command.invoke()
call.
-
- add_cog(cog)
-
Adds a “cog” to the bot.
A cog is a class that has its own event listeners and commands.
- Parameters:
-
cog (
Cog
) – The cog to register to the bot. - Raises:
-
-
TypeError – The cog does not inherit from
Cog
. -
CommandError – An error happened during loading.
-
- add_command(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 genericClientException
- Parameters:
-
command (
Command
) – The command to add. - Raises:
-
-
.CommandRegistrationError – If the command or its alias is already registered by different command.
-
TypeError – If the command passed is not a subclass of
Command
.
-
- add_commands(*commands)
-
Similar to
add_command()
but you can pass multiple commands at once.- Parameters:
-
-
commands (Tuple[
Command
]) – The commands to add -
command (
Command
) – The command to add.
-
- Raises:
-
-
.CommandRegistrationError – If any of the commands or its alias is already registered by different command.
-
TypeError – If any of the commands passed is not a subclass of
Command
.
-
- add_interaction_listener(_type, func, custom_id)
-
This adds an interaction(decorator) like
on_click()
oron_select()
to the client listeners.Note
This should not use directly; only cogs use this to register them.
- add_listener(func, name=None)
-
The non decorator alternative to
listen()
.- Parameters:
-
-
func (coroutine) – The function to call.
-
name (Optional[
str
]) – The name of the event to listen for. Defaults tofunc.__name__
.
-
Example
async def on_ready(): pass async def my_message(message): pass bot.add_listener(on_ready) bot.add_listener(my_message, 'on_message')
- after_invoke(coro)
-
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.- Parameters:
-
coro (coroutine) – The coroutine to register as the post-invoke hook.
- Raises:
-
TypeError – The coroutine passed is not actually a coroutine.
- property allowed_mentions
-
The allowed mention configuration.
New in version 1.4.
- Type:
-
Optional[
AllowedMentions
]
- property application_commands
-
Returns a list of any application command that is registered for the bot`
- Type:
-
List[
ApplicationCommand
]
- await application_info()
-
This function is a coroutine.
Retrieves the bot’s application information.
- Raises:
-
.HTTPException – Retrieving the information failed somehow.
- Returns:
-
The bot’s application information.
- Return type:
-
AppInfo
- await before_identify_hook(shard_id, *, initial=False)
-
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.
- Parameters:
-
-
shard_id (
int
) – The shard ID that requested being IDENTIFY’d -
initial (
bool
) – Whether this IDENTIFY is the first initial IDENTIFY.
-
- before_invoke(coro)
-
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()
andafter_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.- Parameters:
-
coro (coroutine) – The coroutine to register as the pre-invoke hook.
- Raises:
-
TypeError – The coroutine passed is not actually a coroutine.
- property cached_messages
-
Read-only list of messages the connected client has cached.
New in version 1.1.
- Type:
-
Sequence[
Message
]
- await change_presence(*, activity=None, status=‘online’)
-
This function is a coroutine.
Changes the client’s presence.
Changed in version 2.0: Removed the
afk
parameterExample
game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game)
- Parameters:
-
-
activity (Optional[
BaseActivity
]) – The activity being done.None
if no currently active activity is done. -
status (Optional[
Status
]) – Indicates what status to change to. IfNone
, then
Status.online
is used.
-
- Raises:
-
.InvalidArgument – If the
activity
parameter is not the proper type.
- check(func)
-
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 typeContext
and can only raise exceptions inherited from
CommandError
.Example
@bot.check def check_commands(ctx): return ctx.command.qualified_name in allowed_commands
- check_once(func)
-
A decorator that adds a “call once” global check to the bot.
Unlike regular global checks, this one is called only once
perCommand.invoke()
call.Regular global checks are called whenever a command is called
orCommand.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 perBot.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 typeContext
and can only raise exceptions inherited from
CommandError
.Example
@bot.check_once def whitelist(ctx): return ctx.message.author.id in my_whitelist
- clear()
-
Clears the internal state of the bot.
After this, the bot can be considered “re-opened”, i.e.
is_closed()
andis_ready()
both returnFalse
along with the bot’s internal
cache cleared.
- await close()
-
This function is a coroutine.
This has the same behaviour as
discord.Client.close()
except that it unload all extensions and cogs first.
- property cogs
-
A read-only mapping of cog name to cog.
- Type:
-
Mapping[
str
,Cog
]
- command(*args, **kwargs)
-
A shortcut decorator that invokes
command()
and adds it to
the internal command list viaadd_command()
.- Returns:
-
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
- Return type:
-
Callable[…,
Command
]
- property commands
-
A unique set of commands without aliases that are registered.
- Type:
-
Set[
Command
]
- await connect(*, reconnect=True)
-
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.- Parameters:
-
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). - Raises:
-
-
.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.
-
- await create_guild(name, region=None, icon=None, *, code=None)
-
This function is a coroutine.
Creates a
Guild
.Bot accounts in more than 10 guilds are not allowed to create guilds.
- Parameters:
-
-
name (
str
) – The name of the guild. -
region (
VoiceRegion
) – The region for the voice communication server.
Defaults toVoiceRegion.us_west
. -
icon (
bytes
) – The bytes-like object representing the icon. SeeClientUser.edit()
for more details on what is expected. -
code (Optional[
str
]) –The code for a template to create the guild with.
New in version 1.4.
-
- Raises:
-
-
.HTTPException – Guild creation failed.
-
.InvalidArgument – Invalid icon image format given. Must be PNG or JPG.
-
- Returns:
-
The guild created. This is not the same guild that is
added to cache. - Return type:
-
Guild
- await delete_invite(invite)
-
This function is a coroutine.
Revokes an
Invite
, URL, or ID to an invite.You must have the
manage_channels
permission in
the associated guild to do this.- Parameters:
-
invite (Union[
Invite
,str
]) – The invite to revoke. - Raises:
-
-
.Forbidden – You do not have permissions to revoke invites.
-
.NotFound – The invite is invalid or expired.
-
.HTTPException – Revoking the invite failed.
-
- property emojis
-
The emojis that the connected client has.
- Type:
-
List[
Emoji
]
- event(coro)
-
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!')
- Raises:
-
TypeError – The coroutine passed is not actually a coroutine.
- property extensions
-
A read-only mapping of extension name to extension.
- Type:
-
Mapping[
str
,types.ModuleType
]
- await fetch_all_nitro_stickers()
-
Retrieves a
list
with all build-inStickerPack
‘s.- Returns:
-
A list containing all build-in sticker-packs.
- Return type:
-
StickerPack
- await fetch_channel(channel_id)
-
This function is a coroutine.
Retrieves a
abc.GuildChannel
orabc.PrivateChannel
with the specified ID.Note
This method is an API call. For general usage, consider
get_channel()
instead.New in version 1.2.
- Raises:
-
-
.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.
-
- Returns:
-
The channel from the ID.
- Return type:
-
Union[
abc.GuildChannel
,abc.PrivateChannel
]
- await fetch_guild(guild_id)
-
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.- Parameters:
-
guild_id (
int
) – The guild’s ID to fetch from. - Raises:
-
-
.Forbidden – You do not have access to the guild.
-
.HTTPException – Getting the guild failed.
-
- Returns:
-
The guild from the ID.
- Return type:
-
Guild
- fetch_guilds(*, limit=100, before=None, after=None)
-
Retrieves an
AsyncIterator
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 = await client.fetch_guilds(limit=150).flatten() # guilds is now a list of Guild...
All parameters are optional.
- Parameters:
-
-
limit (Optional[
int
]) – The number of guilds to retrieve.
IfNone
, it retrieves every guild you have access to. Note, however,
that this would make it a slow operation.
Defaults to100
. -
before (Union[
abc.Snowflake
,datetime.datetime
]) – Retrieves guilds before this date or object.
If a date is provided it must be a timezone-naive datetime representing UTC time. -
after (Union[
abc.Snowflake
,datetime.datetime
]) – Retrieve guilds after this date or object.
If a date is provided it must be a timezone-naive datetime representing UTC time.
-
- Raises:
-
.HTTPException – Getting the guilds failed.
- Yields:
-
Guild
– The guild with the guild data parsed.
- await fetch_invite(url, *, with_counts=True)
-
This function is a coroutine.
Gets an
Invite
from a discord.gg URL or ID.- Parameters:
-
-
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
andInvite.approximate_presence_count
fields.
-
- Raises:
-
-
.NotFound – The invite has expired or is invalid.
-
.HTTPException – Getting the invite failed.
-
- Returns:
-
The invite from the URL/ID.
- Return type:
-
Invite
- await fetch_template(code)
-
This function is a coroutine.
Gets a
Template
from a discord.new URL or code.- Parameters:
-
code (Union[
Template
,str
]) – The Discord Template Code or URL (must be a discord.new URL). - Raises:
-
-
.NotFound – The template is invalid.
-
.HTTPException – Getting the template failed.
-
- Returns:
-
The template from the URL/code.
- Return type:
-
Template
- await fetch_user(user_id)
-
This function is a coroutine.
Retrieves a
User
based on their ID. This can only
be used by bot accounts. You do not have to share any guilds
with the user to get this information, however many operations
do require that you do.Note
This method is an API call. If you have
Intents.members
and member cache enabled, considerget_user()
instead.- Parameters:
-
user_id (
int
) – The user’s ID to fetch from. - Raises:
-
-
.NotFound – A user with this ID does not exist.
-
.HTTPException – Fetching the user failed.
-
- Returns:
-
The user you requested.
- Return type:
-
User
- await fetch_webhook(webhook_id)
-
This function is a coroutine.
Retrieves a
Webhook
with the specified ID.- Raises:
-
-
.HTTPException – Retrieving the webhook failed.
-
.NotFound – Invalid webhook ID.
-
.Forbidden – You do not have permission to fetch this webhook.
-
- Returns:
-
The webhook you requested.
- Return type:
-
Webhook
- await fetch_widget(guild_id)
-
This function is a coroutine.
Gets a
Widget
from a guild ID.Note
The guild must have the widget enabled to get this information.
- Parameters:
-
guild_id (
int
) – The ID of the guild. - Raises:
-
-
.Forbidden – The widget for this guild is disabled.
-
.HTTPException – Retrieving the widget failed.
-
- Returns:
-
The guild’s widget.
- Return type:
-
Widget
- for … in get_all_channels()
-
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
- Yields:
-
abc.GuildChannel
– A channel the client can ‘access’.
- for … in get_all_members()
-
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
- Yields:
-
Member
– A member the client can see.
- get_channel(id)
-
Returns a channel with the given ID.
- Parameters:
-
id (
int
) – The ID to search for. - Returns:
-
The returned channel or
None
if not found. - Return type:
-
Optional[Union[
abc.GuildChannel
,abc.PrivateChannel
]]
- get_cog(name)
-
Gets the cog instance requested.
If the cog is not found,
None
is returned instead.- Parameters:
-
name (
str
) – The name of the cog you are requesting.
This is equivalent to the name passed via keyword
argument in class creation or the class name if unspecified. - Returns:
-
The cog that was requested. If not found, returns
None
. - Return type:
-
Optional[
Cog
]
- get_command(name)
-
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 subcommandbar
of the group commandfoo
. If a
subcommand is not found thenNone
is returned just as usual.- Parameters:
-
name (
str
) – The name of the command to get. - Returns:
-
The command that was requested. If not found, returns
None
. - Return type:
-
Optional[
Command
]
- await get_context(message, *, cls=<class ‘discord.ext.commands.context.Context’>)
-
This function is a coroutine.
Returns the invocation context from the message.
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 underinvoke()
.- Parameters:
-
-
message (
discord.Message
) – The message to get the invocation context from. -
cls – The factory class that will be used to create the context.
By default, this isContext
. Should a custom
class be provided, it must be similar enough toContext
‘s
interface.
-
- Returns:
-
The invocation context. The type of this can change via the
cls
parameter. - Return type:
-
Context
- get_emoji(id)
-
Returns an emoji with the given ID.
- Parameters:
-
id (
int
) – The ID to search for. - Returns:
-
The custom emoji or
None
if not found. - Return type:
-
Optional[
Emoji
]
- get_guild(id)
-
Returns a guild with the given ID.
- Parameters:
-
id (
int
) – The ID to search for. - Returns:
-
The guild or
None
if not found. - Return type:
-
Optional[
Guild
]
- get_message(id)
-
Returns a
Message
with the given ID if it exists in the cache, elseNone
- get_partial_messageable(id, *, guild_id=None, type=None)
-
Returns a
PartialMessageable
with the given channel ID.
This is useful if you have the ID of a channel but don’t want to do an API call
to send messages to it.- Parameters:
-
-
id (
int
) – The channel ID to create aPartialMessageable
for. -
guild_id (Optional[
int
]) – The optional guild ID to create aPartialMessageable
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 thePartialMessageable
.
-
- Returns:
-
The partial messageable created
- Return type:
-
PartialMessageable
- await get_prefix(message)
-
This function is a coroutine.
Retrieves the prefix the bot is listening to
with the message as a context.- Parameters:
-
message (
discord.Message
) – The message context to get the prefix of. - Returns:
-
A list of prefixes or a single prefix that the bot is
listening for. - Return type:
-
Union[List[
str
],str
]
- get_user(id)
-
Returns a user with the given ID.
- Parameters:
-
id (
int
) – The ID to search for. - Returns:
-
The user or
None
if not found. - Return type:
-
Optional[
User
]
- property global_application_commands
-
Returns a list of all global application commands that are registered for the bot
Note
This requires the bot running and all commands cached, otherwise the list will be empty
- Returns:
-
A list of registered global application commands for the bot
- Return type:
-
List[
ApplicationCommand
]
- group(*args, **kwargs)
-
A shortcut decorator that invokes
group()
and adds it to
the internal command list viaadd_command()
.- Returns:
-
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
- Return type:
-
Callable[…,
Group
]
- property guilds
-
The guilds that the connected client is a member of.
- Type:
-
List[
Guild
]
- property intents
-
The intents configured for this connection.
New in version 1.5.
- Type:
-
Intents
- await invoke(ctx)
-
This function is a coroutine.
Invokes the command given under the invocation context and
handles all the internal event dispatch mechanisms.- Parameters:
-
ctx (
Context
) – The invocation context to invoke.
- is_closed()
-
bool
: Indicates if the websocket connection is closed.
- await is_owner(user)
-
This function is a coroutine.
Checks if a
User
orMember
is the owner of
this bot.If an
owner_id
is not set, it is fetched automatically
through the use ofapplication_info()
.Changed in version 1.3: The function also checks if the application is team-owned if
owner_ids
is not set.- Parameters:
-
user (
abc.User
) – The user to check for. - Returns:
-
Whether the user is the owner.
- Return type:
-
bool
- is_ready()
-
bool
: Specifies if the client’s internal cache is ready for use.
- is_ws_ratelimited()
-
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.
- property latency
-
Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
- Type:
-
float
- listen(name=None)
-
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 ason_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.
- Raises:
-
TypeError – The function being listened to is not a coroutine.
- load_extension(name, *, package=None)
-
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, thebot
.- Parameters:
-
-
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 importfoo/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 toNone
.New in version 1.7.
-
- Raises:
-
-
ExtensionNotFound – The extension could not be imported.
This is also raised if the name of the extension could not
be resolved using the providedpackage
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.
-
- await login(token)
-
This function is a coroutine.
Logs in the client with the specified credentials.
This function can be used in two different ways.
- Parameters:
-
token (
str
) – The authentication token. Do not prefix this token with
anything as the library will do it for you. - Raises:
-
-
.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.
-
- await logout()
-
This function is a coroutine.
Logs out of Discord and closes all connections.
Deprecated since version 1.7.
Note
This is just an alias to
close()
. If you want
to do extraneous cleanup when subclassing, it is suggested
to overrideclose()
instead.
- message_command(name=None, name_localizations=<Localizations: None>, default_required_permissions=None, allow_dm=True, is_nsfw=False, guild_ids=None)
-
A decorator that registers a
MessageCommand
(shows up underApps
when right-clicking on a message)
to the client. The function this is attached to must be a coroutine.Note
sync_commands
of theClient
instance must be set toTrue
to register a command if it does not already exit and update it if changes where made.- Parameters:
-
-
name (Optional[
str
]) – The name of the message-command, default to the functions name.
Must be between 1-32 characters long. -
name_localizations (
Localizations
) – Localizedname
’s. -
default_required_permissions (Optional[
Permissions
]) – Permissions that a member needs by default to execute(see) the command. -
allow_dm (
bool
) – Indicates whether the command is available in DMs with the app, only for globally-scoped commands.
By default, commands are visible. -
is_nsfw (
bool
) – Whether this command is an NSFW command, defaultFalse
. -
guild_ids (Optional[List[
int
]]) – ID’s of guilds this command should be registered in. If empty, the command will be global.
-
- Returns:
-
The message-command registered.
- Return type:
-
MessageCommand
- Raises:
-
TypeError – The function the decorator is attached to is not actual a coroutine.
- await on_application_command_error(cmd, interaction, exception)
-
This function is a coroutine.
The default error handler when an Exception was raised when invoking an application-command.
By default this prints to
sys.stderr
however it could be
overridden to have a different implementation.
Checkon_application_command_error()
for more details.
- on_click(custom_id=None)
-
A decorator with wich you can assign a function to a specific
Button
(or its custom_id).Important
The function this is attached to must take the same parameters as a
on_raw_button_click()
event.Warning
The func must be a coroutine, if not,
TypeError
is raised.- Parameters:
-
custom_id (Optional[Union[Pattern[AnyStr], AnyStr]]) –
If the
custom_id
of theButton
could not be used as a function name,
or you want to give the function a different name then the custom_id use this one to set the custom_id.
You can also specify a regex and if the custom_id matches it, the function will be executed.Note
As the
custom_id
is converted to a Pattern
put^
in front and$
at the end
of thecustom_id
if you want that the custom_id must exactly match the specified value.
Otherwise, something like ‘cool blue Button is blue’ will let the function bee invoked too.
Example
# the button Button(label='Hey im a cool blue Button', custom_id='cool blue Button', style=ButtonStyle.blurple) # function that's called when the button pressed @client.on_click(custom_id='^cool blue Button$') async def cool_blue_button(i: discord.ComponentInteraction, button: Button): await i.respond(f'Hey you pressed a {button.custom_id}!', hidden=True)
- Return type:
-
The decorator for the function called when the button clicked
- Raises:
-
TypeError – The coroutine passed is not actually a coroutine.
- await on_command_error(context, exception)
-
This function is a coroutine.
The default command error handler provided by the bot.
By default this prints to
sys.stderr
however it could be
overridden to have a different implementation.This only fires if you do not specify any listeners for command error.
- await on_error(event_method, *args, **kwargs)
-
This function is a coroutine.
The default error handler provided by the client.
By default, this prints to
sys.stderr
however it could be
overridden to have a different implementation.
Checkon_error()
for more details.
- on_select(custom_id=None)
-
A decorator with which you can assign a function to a specific
SelectMenu
(or its custom_id).Warning
The func must be a coroutine, if not,
TypeError
is raised.- Parameters:
-
custom_id (Optional[Union[Pattern[AnyStr], AnyStr]] = None) –
If the custom_id of the
SelectMenu
could not be used as a function name,
or you want to give the function a different name then the custom_id use this one to set the custom_id.
You can also specify a regex and if the custom_id matches it, the function will be executed.Note
As the
custom_id
is converted to a Pattern
put^
in front and$
at the end
of thecustom_id
if you want that the custom_id must exactly match the specified value.
Otherwise, something like ‘choose_your_gender later’ will let the function bee invoked too.
Example
# the SelectMenu SelectMenu(custom_id='choose_your_gender', options=[ SelectOption(label='Female', value='Female', emoji='♀️'), SelectOption(label='Male', value='Male', emoji='♂️'), SelectOption(label='Trans/Non Binary', value='Trans/Non Binary', emoji='⚧') ], placeholder='Choose your Gender') # function that's called when the SelectMenu is used @client.on_select() async def choose_your_gender(i: discord.Interaction, select_menu): await i.respond(f'You selected `{select_menu.values[0]}`!', hidden=True)
- Raises:
-
TypeError – The coroutine passed is not actually a coroutine.
- on_submit(custom_id=None)
-
A decorator with wich you can assign a function to a specific
Modal
(or its custom_id).Important
The function this is attached to must take the same parameters as a
on_modal_submit()
event.Warning
The func must be a coroutine, if not,
TypeError
is raised.- Parameters:
-
custom_id (Optional[Union[Pattern[AnyStr], AnyStr]]) –
If the custom_id of the
Modal
could not be used as a function name,
or you want to give the function a different name then the custom_id use this one to set the custom_id.
You can also specify a regex and if the custom_id matches it, the function will be executed.Note
As the
custom_id
is converted to a Pattern
put^
in front and$
at the end of thecustom_id
if you want that the custom_id must
exactly match the specified value.
Otherwise, something like ‘suggestions_modal_submit_private’ will let the function bee invoked too.
Example
# the Modal Modal(title='Create a new suggestion', custom_id='suggestions_modal', components=[...]) # function that's called when the Modal is submitted @client.on_submit(custom_id='^suggestions_modal$') async def suggestions_modal_callback(i: discord.ModalSubmitInteraction): ...
- Raises:
-
TypeError – The coroutine passed is not actually a coroutine.
- property private_channels
-
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.- Type:
-
List[
abc.PrivateChannel
]
- await process_commands(message)
-
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 theon_message()
event, then
you should invoke this coroutine as well.This is built using other low level tools, and is equivalent to a
call toget_context()
followed by a call toinvoke()
.This also checks if the message’s author is a bot and doesn’t
callget_context()
orinvoke()
if so.- Parameters:
-
message (
discord.Message
) – The message to process commands for.
- reload_extension(name, *, package=None)
-
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is
equivalent to aunload_extension()
followed by aload_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.- Parameters:
-
-
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 importfoo/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 toNone
.New in version 1.7.
-
- Raises:
-
-
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 providedpackage
parameter. -
NoEntryPointError – The extension does not have a setup function.
-
ExtensionFailed – The extension setup function had an execution error.
-
- reload_extensions(*names, package=None)
-
Same behaviour as
reload_extension()
excepts that it reloads multiple extensions
and triggers application commands syncing after all has been reloaded
- remove_application_cmds_from_cog(cog)
-
Removes all application-commands in the given cog from the internal list of application-commands.
- Parameters:
-
cog (
Cog
) – The cog wich application-commands should be removed from the internal list of application-commands.
- remove_check(func, *, call_once=False)
-
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.- Parameters:
-
-
func – The function to remove from the global checks.
-
call_once (
bool
) – If the function was added withcall_once=True
in
theBot.add_check()
call or usingcheck_once()
.
-
- remove_cog(name)
-
Removes a cog from the bot.
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.
- Parameters:
-
name (
str
) – The name of the cog to remove.
- remove_command(name)
-
Remove a
Command
from the internal list
of commands.This could also be used as a way to remove aliases.
- Parameters:
-
name (
str
) – The name of the command to remove. - Returns:
-
The command that was removed. If the name is not valid then
None
is returned instead. - Return type:
-
Optional[
Command
]
- remove_interaction_listener(_type, func, custom_id)
-
This removes an interaction(decorator) like
on_click()
oron_select()
from the client listeners.Note
This should not use directly; only cogs use this to remove them.
- remove_listener(func, name=None)
-
Removes a listener from the pool of listeners.
- Parameters:
-
-
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__
.
-
- await request_offline_members(*guilds)
-
This function is a coroutine.
Requests previously offline members from the guild to be filled up
into theGuild.members
cache. This function is usually not
called. It should only be used if you have thefetch_offline_members
parameter set toFalse
.When the client logs on and connects to the websocket, Discord does
not provide the library with offline members if the number of members
in the guild is larger than 250. You can check if a guild is large
ifGuild.large
isTrue
.Warning
This method is deprecated. Use
Guild.chunk()
instead.- Parameters:
-
*guilds (
Guild
) – An argument list of guilds to request offline members for. - Raises:
-
.InvalidArgument – If any guild is unavailable in the collection.
- run(token, reconnect=True, *, log_handler=MISSING, log_formatter=MISSING, log_level=MISSING, root_logger=False)
-
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. Usestart()
coroutine
orconnect()
+login()
.Roughly Equivalent to:
try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(close()) # cancel all tasks lingering finally: loop.close()
This function also sets up the :mod:`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 passingNone
to
thelog_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.- Parameters:
-
-
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 isNone
then the library will not set up anything logging related. Logging
will still work ifNone
is passed, though it is your responsibility
to set it up.
The default log handler if not provided islogging.StreamHandler
. -
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). -
log_level (
int
) – The default log level for the library’s logger. This is only applied if the
log_handler
parameter is notNone
. Defaults tologging.INFO
. -
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 toTrue
then the root logger is set up as well.
Defaults toFalse
.
-
- slash_command(name=None, name_localizations=<Localizations: None>, description=None, description_localizations=<Localizations: None>, allow_dm=MISSING, is_nsfw=MISSING, default_required_permissions=None, options=[], guild_ids=None, connector={}, option_descriptions={}, option_descriptions_localizations={}, base_name=None, base_name_localizations=<Localizations: None>, base_desc=None, base_desc_localizations=<Localizations: None>, group_name=None, group_name_localizations=<Localizations: None>, group_desc=None, group_desc_localizations=<Localizations: None>)
-
A decorator that adds a slash-command to the client. The function this is attached to must be a coroutine.
Warning
sync_commands
of theClient
instance must be set toTrue
to register a command if it does not already exist and update it if changes where made.Note
Any of the following parameters are only needed when the corresponding target was not used before
(e.g. there is already a command in the code that has these parameters set) — otherwise it will replace the previous value:-
allow_dm
-
is_nsfw
-
base_name_localizations
-
base_desc
-
base_desc_localizations
-
group_name_localizations
-
group_desc
-
group_desc_localizations
- Parameters:
-
-
name (Optional[
str
]) – The name of the command. Must only contain a-z, _ and — and be 1-32 characters long.
Default to the functions name. -
name_localizations (Optional[
Localizations
]) – Localizations object for name field. Values follow the same restrictions asname
-
description (Optional[
str
]) – The description of the command shows up in the client. Must be between 1-100 characters long.
Default to the functions docstring or “No Description”. -
description_localizations (Optional[
Localizations
]) – Localizations object for description field. Values follow the same restrictions asdescription
-
allow_dm (Optional[
bool
]) – Indicates whether the command is available in DMs with the app, only for globally-scoped commands.
By default, commands are visible. -
is_nsfw (
bool
) –Whether this command is an NSFW command, default
False
Note
Currently all sub-commands of a command that is marked as NSFW are NSFW too.
-
default_required_permissions (Optional[
Permissions
]) – Permissions that a Member needs by default to execute(see) the command. -
options (Optional[List[
SlashCommandOption
]]) – A list of max. 25 options for the command. If not provided the options will be generated
usinggenerate_options()
that creates the options out of the function parameters.
Required options must be listed before optional ones.
Useoptions
to connect non-ascii option names with the parameter of the function. -
guild_ids (Optional[List[
int
]]) – ID’s of guilds this command should be registered in. If empty, the command will be global. -
connector (Optional[Dict[
str
,str
]]) – A dictionary containing the name of function-parameters as keys and the name of the option as values.
Useful for using non-ascii Letters in your option names without getting ide-errors. -
option_descriptions (Optional[Dict[
str
,str
]]) –Descriptions the
generate_options()
should take for the Options that will be generated.
The keys are thename
of the option and the value thedescription
.Note
This will only be used if
options
is not set. -
option_descriptions_localizations (Optional[Dict[
str
,Localizations
]]) – Localizeddescription
for the options.
In the format{'option_name': Localizations(...)}
-
base_name (Optional[
str
]) – The name of the base-command(a-z, _ and -, 1-32 characters) if you want the command
to be in a command-/sub-command-group.
If the base-command does not exist yet, it will be added. -
base_name_localizations (Optional[
Localizations
]) – Localizedbase_name
’s for the command. -
base_desc (Optional[
str
]) – The description of the base-command(1-100 characters). -
base_desc_localizations (Optional[
Localizations
]) – Localizedbase_description
’s for the command. -
group_name (Optional[
str
]) – The name of the command-group(a-z, _ and -, 1-32 characters) if you want the command to be in a sub-command-group. -
group_name_localizations (Optional[
Localizations
]) – Localizedgroup_name
’s for the command. -
group_desc (Optional[
str
]) – The description of the sub-command-group(1-100 characters). -
group_desc_localizations (Optional[
Localizations
]) – Localizedgroup_desc
’s for the command.
-
- Raises:
-
-
TypeError – The function the decorator is attached to is not actual a coroutine
or a parameter passed toSlashCommandOption
is invalid for theoption_type
or theoption_type
itself is invalid. -
InvalidArgument – You passed
group_name
but nobase_name
. -
ValueError – Any of
name
,description
,options
,base_name
,base_desc
,group_name
orgroup_desc
is not valid.
-
- Returns:
-
-
If neither
guild_ids
norbase_name
passed: An instance ofSlashCommand
. -
If
guild_ids
and nobase_name
where passed: An instance ofGuildOnlySlashCommand
representing the guild-only slash-commands. -
If
base_name
and noguild_ids
where passed: An instance ofSubCommand
. -
If
base_name
andguild_ids
passed: instance ofGuildOnlySubCommand
representing the guild-only sub-commands.
-
- Return type:
-
Union[
SlashCommand
,GuildOnlySlashCommand
,SubCommand
,GuildOnlySubCommand
]
-
- await start(token, reconnect=True)
-
This function is a coroutine.
A shorthand coroutine for
login()
+connect()
.- Raises:
-
TypeError – An unexpected keyword argument was received.
- property stickers
-
The stickers that the connected client has.
- Type:
-
List[
Sticker
]
- unload_extension(name, *, package=None)
-
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, thebot
, similar tosetup
from
load_extension()
.- Parameters:
-
-
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 importfoo/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 toNone
.New in version 1.7.
-
- Raises:
-
-
ExtensionNotFound – The name of the extension could not
be resolved using the providedpackage
parameter. -
ExtensionNotLoaded – The extension was not loaded.
-
- property user
-
Represents the connected client.
None
if not logged in.- Type:
-
Optional[
ClientUser
]
- user_command(name=None, name_localizations=<Localizations: None>, default_required_permissions=None, allow_dm=True, is_nsfw=False, guild_ids=None)
-
A decorator that registers a
UserCommand
(shows up underApps
when right-clicking on a user) to the client.
The function this is attached to must be a coroutine.Note
sync_commands
of theClient
instance must be set toTrue
to register a command if it does not already exist and update it if changes where made.- Parameters:
-
-
name (Optional[
str
]) – The name of the user-command, default to the functions name.
Must be between 1-32 characters long. -
name_localizations (
Localizations
) – Localizedname
’s. -
default_required_permissions (Optional[
Permissions
]) – Permissions that a member needs by default to execute(see) the command. -
allow_dm (
bool
) – Indicates whether the command is available in DMs with the app, only for globally-scoped commands.
By default, commands are visible. -
is_nsfw (
bool
) –Whether this command is an NSFW command, default
False
. -
guild_ids (Optional[List[
int
]]) – ID’s of guilds this command should be registered in. If empty, the command will be global.
-
- Returns:
-
The user-command registered.
- Return type:
-
UserCommand
- Raises:
-
TypeError – The function the decorator is attached to is not actual a coroutine.
- property users
-
Returns a list of all the users the bot can see.
- Type:
-
List[
User
]
- property voice_clients
-
Represents a list of voice connections.
These are usually
VoiceClient
instances.- Type:
-
List[
VoiceProtocol
]
- wait_for(event, *, check=None, timeout=None)
-
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 ontoasyncio.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('Hello {.author}!'.format(msg))
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('👍')
- Parameters:
-
-
event (
str
) – The event name, similar to the event reference,
but without theon_
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
.
-
- Raises:
-
asyncio.TimeoutError – If a timeout is provided, and it was reached.
- Returns:
-
Returns no arguments, a single argument, or a
tuple
of multiple
arguments that mirrors the parameters passed in the
event reference. - Return type:
-
Any
- await wait_until_ready()
-
This function is a coroutine.
Waits until the client’s internal cache is all ready.
- for … in walk_commands()
-
An iterator that recursively walks through all commands and subcommands.
Changed in version 1.4: Duplicates due to aliases are no longer returned
- Yields:
-
Union[
Command
,Group
] – A command or group from the internal list of commands.
AutoShardedBot
- class discord.ext.commands.AutoShardedBot(command_prefix, help_command=<default-help-command>, description=None, **options)
-
This is similar to
Bot
except that it is inherited from
discord.AutoShardedClient
instead.
Prefix Helpers
- discord.ext.commands.when_mentioned(bot, msg)
-
A callable that implements a command prefix equivalent to being mentioned.
These are meant to be passed into the
Bot.command_prefix
attribute.
- discord.ext.commands.when_mentioned_or(*prefixes)
-
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)
See also
when_mentioned()
Event Reference
These events function similar to the regular events, except they
are custom to the command extension module.
- discord.on_command_error(ctx, error)
-
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()
).- Parameters:
-
-
ctx (
Context
) – The invocation context. -
error (
CommandError
derived) – The error that was raised.
-
- discord.on_command(ctx)
-
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.- Parameters:
-
ctx (
Context
) – The invocation context.
- discord.on_command_completion(ctx)
-
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.- Parameters:
-
ctx (
Context
) – The invocation context.
Commands
Decorators
- discord.ext.commands.command(name=None, cls=None, **attrs)
-
A decorator that transforms a function into a
Command
or if called withgroup()
,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 isbytes
, then it is decoded
intostr
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.- Parameters:
-
-
name (
str
) – The name to create the command with. By default this uses the
function name unchanged. -
cls – The class to construct with. By default this is
Command
.
You usually do not change this. -
attrs – Keyword arguments to pass into the construction of the class denoted
bycls
.
-
- Raises:
-
TypeError – If the function is not a coroutine or is already a command.
- discord.ext.commands.group(name=None, **attrs)
-
A decorator that transforms a function into a
Group
.This is similar to the
command()
decorator but thecls
parameter is set toGroup
by default.Changed in version 1.1: The
cls
parameter can now be passed.
Command
Attributes
- aliases
- brief
- callback
- checks
- clean_params
- cog
- cog_name
- cooldown_after_parsing
- description
- enabled
- full_parent_name
- help
- hidden
- ignore_extra
- invoked_subcommand
- name
- parent
- parents
- qualified_name
- require_var_positional
- rest_is_raw
- root_parent
- short_doc
- signature
- usage
Methods
-
async__call__ -
defadd_check -
@after_invoke -
@before_invoke -
asynccan_run -
defcopy -
@error -
defget_cooldown_retry_after -
defhas_error_handler -
defis_on_cooldown -
defremove_check -
defreset_cooldown -
defupdate
- class discord.ext.commands.Command(*args, **kwargs)
-
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.- name
-
The name of the command.
- Type:
-
str
- callback
-
The coroutine that is executed when the command is called.
- Type:
-
coroutine
- help
-
The long help text for the command.
- Type:
-
str
- brief
-
The short help text for the command.
- Type:
-
Optional[
str
]
- usage
-
A replacement for arguments in the default help text.
- Type:
-
Optional[
str
]
- aliases
-
The list of aliases the command can be invoked under.
- Type:
-
Union[List[
str
], Tuple[str
]]
- enabled
-
A boolean that indicates if the command is currently enabled.
If the command is invoked while it is disabled, then
DisabledCommand
is raised to theon_command_error()
event. Defaults toTrue
.- Type:
-
bool
- parent
-
The parent command that this command belongs to.
None
if there
isn’t one.- Type:
-
Optional[
Command
]
- cog
-
The cog that this command belongs to.
None
if there isn’t one.- Type:
-
Optional[
Cog
]
- checks
-
A list of predicates that verifies if the command could be executed
with the givenContext
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 theon_command_error()
event.- Type:
-
List[Callable[[
Context
],bool
]]
- description
-
The message prefixed into the default help command.
- Type:
-
str
- hidden
-
If
True
, the default help command does not show this in the
help output.- Type:
-
bool
- rest_is_raw
-
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 handlesMissingRequiredArgument
and default values in a
regular matter rather than passing the rest completely raw. IfTrue
then the keyword-only argument will pass in the rest of the arguments
in a completely raw matter. Defaults toFalse
.- Type:
-
bool
- invoked_subcommand
-
The subcommand that was invoked, if any.
- Type:
-
Optional[
Command
]
- require_var_positional
-
If
True
and a variadic positional argument is specified, requires
the user to specify at least one argument. Defaults toFalse
.New in version 1.5.
- Type:
-
bool
- ignore_extra
-
If
True
, ignores extraneous strings passed to a command if all its
requirements are met (e.g.?foo a b c
when only expectinga
andb
). Otherwiseon_command_error()
and local error handlers
are called withTooManyArguments
. Defaults toTrue
.- Type:
-
bool
- cooldown_after_parsing
-
If
True
, cooldown processing is done after argument parsing,
which calls converters. IfFalse
then cooldown processing is done
first and then the converters are called second. Defaults toFalse
.- Type:
-
bool
- add_check(func)
-
Adds a check to the command.
This is the non-decorator interface to
check()
.New in version 1.3.
- Parameters:
-
func – The function that will be used as a check.
- remove_check(func)
-
Removes a check from the command.
This function is idempotent and will not raise an exception
if the function is not in the command’s checks.New in version 1.3.
- Parameters:
-
func – The function to remove from the checks.
- update(**kwargs)
-
Updates
Command
instance with updated attribute.This works similarly to the
command()
decorator in terms
of parameters in that they are passed to theCommand
or
subclass constructors, sans the name and callback.
- await __call__(*args, **kwargs)
-
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.
- copy()
-
Creates a copy of this command.
- Returns:
-
A new instance of this command.
- Return type:
-
Command
- property clean_params
-
OrderedDict[
str
,inspect.Parameter
]:
Retrieves the parameter OrderedDict without the context or self parameters.Useful for inspecting signature.
- property full_parent_name
-
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 beone two
.- Type:
-
str
- property parents
-
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.
- Type:
-
List[
Command
]
- property root_parent
-
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 isa
.- Type:
-
Optional[
Command
]
- property qualified_name
-
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
.- Type:
-
str
- is_on_cooldown(ctx)
-
Checks whether the command is currently on cooldown.
- Parameters:
-
ctx (
Context
) – The invocation context to use when checking the commands cooldown status. - Returns:
-
A boolean indicating if the command is on cooldown.
- Return type:
-
bool
- reset_cooldown(ctx)
-
Resets the cooldown on this command.
- Parameters:
-
ctx (
Context
) – The invocation context to reset the cooldown under.
- get_cooldown_retry_after(ctx)
-
Retrieves the amount of seconds before this command can be tried again.
New in version 1.4.
- Parameters:
-
ctx (
Context
) – The invocation context to retrieve the cooldown from. - Returns:
-
The amount of time left on this command’s cooldown in seconds.
If this is0.0
then the command isn’t on cooldown. - Return type:
-
float
- error(coro)
-
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, theon_command_error()
is still
invoked afterwards as the catch-all.- Parameters:
-
coro (coroutine) – The coroutine to register as the local error handler.
- Raises:
-
TypeError – The coroutine passed is not actually a coroutine.
- has_error_handler()
-
bool
: Checks whether the command has an error handler registered.New in version 1.7.
- before_invoke(coro)
-
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.- Parameters:
-
coro (coroutine) – The coroutine to register as the pre-invoke hook.
- Raises:
-
TypeError – The coroutine passed is not actually a coroutine.
- after_invoke(coro)
-
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.- Parameters:
-
coro (coroutine) – The coroutine to register as the post-invoke hook.
- Raises:
-
TypeError – The coroutine passed is not actually a coroutine.
- property cog_name
-
The name of the cog this command belongs to, if any.
- Type:
-
Optional[
str
]
- property short_doc
-
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.- Type:
-
str
- property signature
-
Returns a POSIX-like signature useful for help command output.
- Type:
-
str
- await can_run(ctx)
-
This function is a coroutine.
Checks if the command can be executed by checking all the predicates
inside thechecks
attribute. This also checks whether the
command is disabled.Changed in version 1.3: Checks whether the command is disabled or not
- Parameters:
-
ctx (
Context
) – The ctx of the command currently being invoked. - Raises:
-
CommandError – Any command error that was raised during a check call will be propagated
by this function. - Returns:
-
A boolean indicating if the command can be invoked.
- Return type:
-
bool
Group
Attributes
- case_insensitive
- clean_params
- cog_name
- commands
- full_parent_name
- invoke_without_command
- parents
- qualified_name
- root_parent
- short_doc
- signature
Methods
-
defadd_check -
defadd_command -
defadd_commands -
@after_invoke -
@before_invoke -
asynccan_run -
@command -
defcopy -
@error -
defget_command -
defget_cooldown_retry_after -
@group -
defhas_error_handler -
defis_on_cooldown -
defremove_check -
defremove_command -
defreset_cooldown -
defupdate -
defwalk_commands
- class discord.ext.commands.Group(*args, **kwargs)
-
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 inCommand
are valid in here as well.- invoke_without_command
-
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 isFalse
, 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 toFalse
.- Type:
-
bool
- case_insensitive
-
Indicates if the group’s commands should be case insensitive.
Defaults toFalse
.- Type:
-
bool
- copy()
-
Creates a copy of this
Group
.- Returns:
-
A new instance of this group.
- Return type:
-
Group
- add_check(func)
-
Adds a check to the command.
This is the non-decorator interface to
check()
.New in version 1.3.
- Parameters:
-
func – The function that will be used as a check.
- add_command(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 genericClientException
- Parameters:
-
command (
Command
) – The command to add. - Raises:
-
-
.CommandRegistrationError – If the command or its alias is already registered by different command.
-
TypeError – If the command passed is not a subclass of
Command
.
-
- add_commands(*commands)
-
Similar to
add_command()
but you can pass multiple commands at once.- Parameters:
-
-
commands (Tuple[
Command
]) – The commands to add -
command (
Command
) – The command to add.
-
- Raises:
-
-
.CommandRegistrationError – If any of the commands or its alias is already registered by different command.
-
TypeError – If any of the commands passed is not a subclass of
Command
.
-
- after_invoke(coro)
-
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.- Parameters:
-
coro (coroutine) – The coroutine to register as the post-invoke hook.
- Raises:
-
TypeError – The coroutine passed is not actually a coroutine.
- before_invoke(coro)
-
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.- Parameters:
-
coro (coroutine) – The coroutine to register as the pre-invoke hook.
- Raises:
-
TypeError – The coroutine passed is not actually a coroutine.
- await can_run(ctx)
-
This function is a coroutine.
Checks if the command can be executed by checking all the predicates
inside thechecks
attribute. This also checks whether the
command is disabled.Changed in version 1.3: Checks whether the command is disabled or not
- Parameters:
-
ctx (
Context
) – The ctx of the command currently being invoked. - Raises:
-
CommandError – Any command error that was raised during a check call will be propagated
by this function. - Returns:
-
A boolean indicating if the command can be invoked.
- Return type:
-
bool
- property clean_params
-
OrderedDict[
str
,inspect.Parameter
]:
Retrieves the parameter OrderedDict without the context or self parameters.Useful for inspecting signature.
- property cog_name
-
The name of the cog this command belongs to, if any.
- Type:
-
Optional[
str
]
- command(*args, **kwargs)
-
A shortcut decorator that invokes
command()
and adds it to
the internal command list viaadd_command()
.- Returns:
-
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
- Return type:
-
Callable[…,
Command
]
- property commands
-
A unique set of commands without aliases that are registered.
- Type:
-
Set[
Command
]
- error(coro)
-
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, theon_command_error()
is still
invoked afterwards as the catch-all.- Parameters:
-
coro (coroutine) – The coroutine to register as the local error handler.
- Raises:
-
TypeError – The coroutine passed is not actually a coroutine.
- property full_parent_name
-
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 beone two
.- Type:
-
str
- get_command(name)
-
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 subcommandbar
of the group commandfoo
. If a
subcommand is not found thenNone
is returned just as usual.- Parameters:
-
name (
str
) – The name of the command to get. - Returns:
-
The command that was requested. If not found, returns
None
. - Return type:
-
Optional[
Command
]
- get_cooldown_retry_after(ctx)
-
Retrieves the amount of seconds before this command can be tried again.
New in version 1.4.
- Parameters:
-
ctx (
Context
) – The invocation context to retrieve the cooldown from. - Returns:
-
The amount of time left on this command’s cooldown in seconds.
If this is0.0
then the command isn’t on cooldown. - Return type:
-
float
- group(*args, **kwargs)
-
A shortcut decorator that invokes
group()
and adds it to
the internal command list viaadd_command()
.- Returns:
-
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
- Return type:
-
Callable[…,
Group
]
- has_error_handler()
-
bool
: Checks whether the command has an error handler registered.New in version 1.7.
- is_on_cooldown(ctx)
-
Checks whether the command is currently on cooldown.
- Parameters:
-
ctx (
Context
) – The invocation context to use when checking the commands cooldown status. - Returns:
-
A boolean indicating if the command is on cooldown.
- Return type:
-
bool
- property parents
-
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.
- Type:
-
List[
Command
]
- property qualified_name
-
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
.- Type:
-
str
- remove_check(func)
-
Removes a check from the command.
This function is idempotent and will not raise an exception
if the function is not in the command’s checks.New in version 1.3.
- Parameters:
-
func – The function to remove from the checks.
- remove_command(name)
-
Remove a
Command
from the internal list
of commands.This could also be used as a way to remove aliases.
- Parameters:
-
name (
str
) – The name of the command to remove. - Returns:
-
The command that was removed. If the name is not valid then
None
is returned instead. - Return type:
-
Optional[
Command
]
- reset_cooldown(ctx)
-
Resets the cooldown on this command.
- Parameters:
-
ctx (
Context
) – The invocation context to reset the cooldown under.
- property root_parent
-
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 isa
.- Type:
-
Optional[
Command
]
- property short_doc
-
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.- Type:
-
str
- property signature
-
Returns a POSIX-like signature useful for help command output.
- Type:
-
str
- update(**kwargs)
-
Updates
Command
instance with updated attribute.This works similarly to the
command()
decorator in terms
of parameters in that they are passed to theCommand
or
subclass constructors, sans the name and callback.
- for … in walk_commands()
-
An iterator that recursively walks through all commands and subcommands.
Changed in version 1.4: Duplicates due to aliases are no longer returned
- Yields:
-
Union[
Command
,Group
] – A command or group from the internal list of commands.
GroupMixin
Methods
-
defadd_command -
defadd_commands -
@command -
defget_command -
@group -
defremove_command -
defwalk_commands
- class discord.ext.commands.GroupMixin(*args, **kwargs)
-
A mixin that implements common functionality for classes that behave
similar toGroup
and are allowed to register commands.- all_commands
-
A mapping of command name to
Command
objects.- Type:
-
dict
- case_insensitive
-
Whether the commands should be case insensitive. Defaults to
False
.- Type:
-
bool
- property commands
-
A unique set of commands without aliases that are registered.
- Type:
-
Set[
Command
]
- add_command(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 genericClientException
- Parameters:
-
command (
Command
) – The command to add. - Raises:
-
-
.CommandRegistrationError – If the command or its alias is already registered by different command.
-
TypeError – If the command passed is not a subclass of
Command
.
-
- add_commands(*commands)
-
Similar to
add_command()
but you can pass multiple commands at once.- Parameters:
-
-
commands (Tuple[
Command
]) – The commands to add -
command (
Command
) – The command to add.
-
- Raises:
-
-
.CommandRegistrationError – If any of the commands or its alias is already registered by different command.
-
TypeError – If any of the commands passed is not a subclass of
Command
.
-
- remove_command(name)
-
Remove a
Command
from the internal list
of commands.This could also be used as a way to remove aliases.
- Parameters:
-
name (
str
) – The name of the command to remove. - Returns:
-
The command that was removed. If the name is not valid then
None
is returned instead. - Return type:
-
Optional[
Command
]
- for … in walk_commands()
-
An iterator that recursively walks through all commands and subcommands.
Changed in version 1.4: Duplicates due to aliases are no longer returned
- Yields:
-
Union[
Command
,Group
] – A command or group from the internal list of commands.
- get_command(name)
-
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 subcommandbar
of the group commandfoo
. If a
subcommand is not found thenNone
is returned just as usual.- Parameters:
-
name (
str
) – The name of the command to get. - Returns:
-
The command that was requested. If not found, returns
None
. - Return type:
-
Optional[
Command
]
- command(*args, **kwargs)
-
A shortcut decorator that invokes
command()
and adds it to
the internal command list viaadd_command()
.- Returns:
-
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
- Return type:
-
Callable[…,
Command
]
- group(*args, **kwargs)
-
A shortcut decorator that invokes
group()
and adds it to
the internal command list viaadd_command()
.- Returns:
-
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
- Return type:
-
Callable[…,
Group
]
Cogs
Cog
Methods
-
clsCog.listener -
clsCog.message_command -
clsCog.on_click -
clsCog.on_select -
clsCog.on_submit -
clsCog.slash_command -
clsCog.user_command -
defbot_check -
defbot_check_once -
asynccog_after_invoke -
asynccog_application_command_error -
asynccog_before_invoke -
defcog_check -
asynccog_command_error -
defcog_unload -
defget_commands -
defget_listeners -
defhas_error_handler -
defwalk_commands
- class discord.ext.commands.Cog(*args, **kwargs)
-
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.- get_commands()
-
- Returns:
-
A
list
ofCommand
s that are
defined inside this cog.Note
This does not include subcommands.
- Return type:
-
List[
Command
]
- property qualified_name
-
Returns the cog’s specified name, not the class name.
- Type:
-
str
- property description
-
Returns the cog’s description, typically the cleaned docstring.
- Type:
-
str
- for … in walk_commands()
-
An iterator that recursively walks through this cog’s commands and subcommands.
- Yields:
-
Union[
Command
,Group
] – A command or group from the cog.
- get_listeners()
-
Returns a
list
of (name, function) listener pairs that are defined in this cog.- Returns:
-
The listeners defined in this cog.
- Return type:
-
List[Tuple[
str
, coroutine]]
- classmethod listener(name=None)
-
A decorator that marks a function as a listener.
This is the cog equivalent of
Bot.listen()
.- Parameters:
-
name (
str
) – The name of the event being listened to. If not provided, it
defaults to the function’s name. - Raises:
-
TypeError – The function is not a coroutine function or a string was not passed as
the name.
- classmethod on_click(custom_id=None)
-
A decorator with wich you can assign a function to a specific
Button
(or its custom_id).Important
The function this is attached to must take the same parameters as a
on_raw_button_click()
event.Warning
The func must be a coroutine, if not,
TypeError
is raised.- Parameters:
-
custom_id (Optional[Union[Pattern[AnyStr], AnyStr]]) –
If the
custom_id
of thediscord.Button
could not use as a function name,
or you want to give the function a different name then the custom_id use this one to set the custom_id.
You can also specify a regex and if the custom_id matches it, the function will be executed.Note
As the
custom_id
is converted to a Pattern
put^
in front and$
at the end
of thecustom_id
if you want that the custom_id must exactly match the specified value.
Otherwise, something like ‘cool blue Button is blue’ will let the function bee invoked too.
Example
# the button Button(label='Hey im a cool blue Button', custom_id='cool blue Button', style=ButtonStyle.blurple) # function that's called when the button pressed @command.Cog.on_click(custom_id='cool blue Button') async def cool_blue_button(self, i: discord.ComponentInteraction, button): await i.respond(f'Hey you pressed a `{button.custom_id}`!', hidden=True)
- Raises:
-
TypeError – The coroutine passed is not actually a coroutine.
- classmethod on_select(custom_id=None)
-
A decorator with which you can assign a function to a specific
SelectMenu
(or its custom_id).Warning
The func must be a coroutine, if not,
TypeError
is raised.- Parameters:
-
custom_id (Optional[Union[Pattern[AnyStr], AnyStr]]) –
If the
custom_id
of theSelectMenu
could not use as a function name,
or you want to give the function a different name then the custom_id use this one to set the custom_id.
You can also specify a regex and if the custom_id matches it, the function will be executed.Note
As the
custom_id
is converted to a Pattern
put^
in front and$
at the end
of thecustom_id
if you want that the custom_id must exactly match the specified value.
Otherwise, something like ‘choose_your_gender later’ will let the function bee invoked too.
Example
# the SelectMenu SelectMenu(custom_id='choose_your_gender', options=[ select_option(label='Female', value='Female', emoji='♀️'), select_option(label='Male', value='Male', emoji='♂️'), select_option(label='Trans/Non Binary', value='Trans/Non Binary', emoji='⚧') ], placeholder='Choose your Gender') # function that's called when the SelectMenu is used @commands.Cog.on_select() async def choose_your_gender(self, i: discord.ComponentInteraction, select_menu): await i.respond(f'You selected `{select_menu.values[0]}`!', hidden=True)
- Raises:
-
TypeError – The coroutine passed is not actually a coroutine.
- classmethod on_submit(custom_id=None)
-
A decorator with wich you can assign a function to a specific
Modal
(or its custom_id).Important
The function this is attached to must take the same parameters as a
on_modal_submit()
event.Warning
The func must be a coroutine, if not,
TypeError
is raised.- Parameters:
-
custom_id (Optional[Union[Pattern[AnyStr], AnyStr]]) –
If the
custom_id
of theModal
could not use as a function name,
or you want to give the function a different name then the custom_id use this one to set the custom_id.
You can also specify a regex and if the custom_id matches it, the function will be executed.Note
As the
custom_id
is converted to a Pattern
put^
in front and$
at the end
of thecustom_id
if you want that the custom_id must exactly match the specified value.
Otherwise, something like ‘suggestions_modal_submit_private’ will let the function bee invoked too.
Example
# the Modal Modal(title='Create a new suggestion', custom_id='suggestions_modal', components=[...]) # function that's called when the Modal is submitted @commands.Cog.on_submit(custom_id='suggestions_modal') async def suggestions_modal_callback(self, i: discord.ModalSubmitInteraction): ...
- Raises:
-
TypeError – The coroutine passed is not actually a coroutine.
- classmethod slash_command(name=None, name_localizations=<Localizations: None>, description=None, description_localizations=<Localizations: None>, allow_dm=True, is_nsfw=MISSING, default_required_permissions=None, options=[], guild_ids=None, connector={}, option_descriptions={}, option_descriptions_localizations={}, base_name=None, base_name_localizations=<Localizations: None>, base_desc=None, base_desc_localizations=<Localizations: None>, group_name=None, group_name_localizations=<Localizations: None>, group_desc=None, group_desc_localizations=<Localizations: None>)
-
A decorator that adds a slash-command to the client. The method this is attached to must be a coroutine.
Note
sync_commands
of theBot
instance must be set toTrue
to register a command if it does not already exist and update it if changes where made.Note
Any of the following parameters are only needed when the corresponding target was not used before
(e.g. there is already a command in the code that has these parameters set) — otherwise it will replace the previous value:-
allow_dm
-
is_nsfw
-
base_name_localizations
-
base_desc
-
base_desc_localizations
-
group_name_localizations
-
group_desc
-
group_desc_localizations
- Parameters:
-
-
name (Optional[
str
]) – The name of the command. Must only contain a-z, _ and — and be 1-32 characters long.
Default to the functions name. -
name_localizations (Optional[
Localizations
]) – Localizations object for name field. Values follow the same restrictions asname
-
description (Optional[
str
]) – The description of the command shows up in the client. Must be between 1-100 characters long.
Default to the functions docstring or “No Description”. -
description_localizations (Optional[
Localizations
]) – Localizations object for description field. Values follow the same restrictions asdescription
-
allow_dm (Optional[
bool
]) – Indicates whether the command is available in DMs with the app, only for globally-scoped commands.
By default, commands are visible. -
is_nsfw (
bool
) –Whether this command is an NSFW command, default
False
Note
Currently all sub-commands of a command that is marked as NSFW are NSFW too.
-
default_required_permissions (Optional[
Permissions
]) – Permissions that a Member needs by default to execute(see) the command. -
options (Optional[List[
SlashCommandOption
]]) – A list of max. 25 options for the command. If not provided the options will be generated
usinggenerate_options()
that creates the options out of the function parameters.
Required options must be listed before optional ones.
Use theconnector
parameter to connect non-ascii option names with the parameter of the function. -
guild_ids (Optional[List[
int
]]) – ID’s of guilds this command should be registered in. If empty, the command will be global. -
connector (Optional[Dict[
str
,str
]]) – A dictionary containing the name of function-parameters as keys and the name of the option as values.
Useful for using non-ascii Letters in your option names without getting ide-errors. -
option_descriptions (Optional[Dict[
str
,str
]]) –Descriptions the
generate_options()
should take for the Options that will be generated.
The keys are thename
of the option and the value thedescription
.Note
This will only be used if
options
is not set. -
option_descriptions_localizations (Optional[Dict[
str
,Localizations
]]) – Localizeddescription
for the options.
In the format{'option_name': Localizations(...)}
-
base_name (Optional[
str
]) – The name of the base-command(a-z, _ and -, 1-32 characters) if you want the command
to be in a command-/sub-command-group.
If the base-command does not exist yet, it will be added. -
base_name_localizations (Optional[
Localizations
]) – Localizedbase_name
’s for the command. -
base_desc (Optional[
str
]) – The description of the base-command(1-100 characters). -
base_desc_localizations (Optional[
Localizations
]) – Localizedbase_description
’s for the command. -
group_name (Optional[
str
]) – The name of the command-group(a-z, _ and -, 1-32 characters) if you want the command to be in a sub-command-group. -
group_name_localizations (Optional[
Localizations
]) – Localizedgroup_name
’s for the command. -
group_desc (Optional[
str
]) – The description of the sub-command-group(1-100 characters). -
group_desc_localizations (Optional[
Localizations
]) – Localizedgroup_desc
’s for the command.
-
- Raises:
-
-
TypeError – The function the decorator is attached to is not actual a coroutine
or a parameter passed toSlashCommandOption
is invalid for theoption_type
or theoption_type
itself is invalid. -
InvalidArgument – You passed
group_name
but nobase_name
. -
ValueError – Any of
name
,description
,options
,base_name
,base_desc
,group_name
orgroup_desc
is not valid.
-
- Returns:
-
-
If neither
guild_ids
norbase_name
passed: An instance ofSlashCommand
. -
If
guild_ids
and nobase_name
where passed: An instance ofGuildOnlySlashCommand
representing the guild-only slash-commands. -
If
base_name
and noguild_ids
where passed: An instance ofSubCommand
. -
If
base_name
andguild_ids
passed: instance ofGuildOnlySubCommand
representing the guild-only sub-commands.
-
- Return type:
-
The slash-command registered.
-
- classmethod message_command(name=None, name_localizations=<Localizations: None>, default_required_permissions=None, allow_dm=True, is_nsfw=False, guild_ids=None)
-
A decorator that registers a
MessageCommand
(shows up underApps
when right-clicking on a message)
to the client. The function this is attached to must be a coroutine.Note
sync_commands
of theBot
instance must be set toTrue
to register a command if it does not already exist and update it if changes where made.- Parameters:
-
-
name (Optional[
str
]) – The name of the message-command, default to the functions name.
Must be between 1-32 characters long. -
name_localizations (
Localizations
) – Localizedname
’s. -
default_required_permissions (Optional[
Permissions
]) – Permissions that a member needs by default to execute(see) the command. -
allow_dm (
bool
) – Indicates whether the command is available in DMs with the app, only for globally-scoped commands.
By default, commands are visible. -
is_nsfw (
bool
) –Whether this command is an NSFW command, default
False
. -
guild_ids (Optional[List[
int
]]) – ID’s of guilds this command should be registered in. If empty, the command will be global.
-
- Returns:
-
The message-command registered.
- Return type:
-
MessageCommand
- Raises:
-
TypeError: – The function the decorator is attached to is not actual a coroutine.
- classmethod user_command(name=None, name_localizations=<Localizations: None>, default_required_permissions=None, allow_dm=True, is_nsfw=False, guild_ids=None)
-
A decorator that registers a
UserCommand
(shows up underApps
when right-clicking on a user) to the client.
The function this is attached to must be a coroutine.Note
sync_commands
of theBot
instance must be set toTrue
to register a command if he not already exists and update him if changes where made.- Parameters:
-
-
name (Optional[
str
]) – The name of the user-command, default to the functions name.
Must be between 1-32 characters long. -
name_localizations (
Localizations
) – Localizedname
’s. -
default_required_permissions (Optional[
Permissions
]) – Permissions that a member needs by default to execute(see) the command. -
allow_dm (
bool
) – Indicates whether the command is available in DMs with the app, only for globally-scoped commands.
By default, commands are visible. -
is_nsfw (
bool
) –Whether this command is an NSFW command, default
False
. -
guild_ids (Optional[List[
int
]]) – ID’s of guilds this command should be registered in. If empty, the command will be global.
-
- Returns:
-
The user-command registered.
- Return type:
-
UserCommand
- Raises:
-
TypeError: – The function the decorator is attached to is not actual a coroutine.
- has_error_handler()
-
bool
: Checks whether the cog has an error handler.New in version 1.7.
- cog_unload()
-
A special method that is called when the cog gets removed.
This function cannot be a coroutine. It must be a regular
function.Subclasses must replace this if they want special unloading behaviour.
- bot_check_once(ctx)
-
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 theContext
.
- bot_check(ctx)
-
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 theContext
.
- cog_check(ctx)
-
A special method that registers as a
commands.check()
for every command and subcommand in this cog.This function can be a coroutine and must take a sole parameter,
ctx
, to represent theContext
.
- await cog_command_error(ctx, error)
-
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.
- Parameters:
-
-
ctx (
Context
) – The invocation context where the error happened. -
error (
CommandError
) – The error that happened.
-
- await cog_before_invoke(ctx)
-
A special method that acts as a cog local pre-invoke hook.
This is similar to
Command.before_invoke()
.This must be a coroutine.
- Parameters:
-
ctx (
Context
) – The invocation context.
- await cog_after_invoke(ctx)
-
A special method that acts as a cog local post-invoke hook.
This is similar to
Command.after_invoke()
.This must be a coroutine.
- Parameters:
-
ctx (
Context
) – The invocation context.
- await cog_application_command_error(cmd, interaction, error)
-
A special method that is called whenever an error
is dispatched inside this cog.
This is similar to
on_application_command_error()
except only applying
to the application-commands inside this cog.This must be a coroutine.
- Parameters:
-
-
cmd (Union[
SlashCommand
,SubCommand
]) – The invoked command. -
interaction (
discord.ApplicationCommandInteraction
) – The interaction. -
error (
Exception
) – The error that happened.
-
CogMeta
- class discord.ext.commands.CogMeta(*args, **kwargs)
-
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 theabc.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
- name
-
The cog name. By default, it is the name of the class with no modification.
- Type:
-
str
- description
-
The cog description. By default, it is the cleaned docstring of the class.
New in version 1.6.
- Type:
-
str
- command_attrs
-
A list of attributes to apply to every command inside this cog. The dictionary
is passed into theCommand
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
- Type:
-
dict
Help Commands
HelpCommand
Methods
-
defadd_check -
asynccommand_callback -
defcommand_not_found -
asyncfilter_commands -
defget_bot_mapping -
defget_command_signature -
defget_destination -
defget_max_size -
asyncon_help_command_error -
asyncprepare_help_command -
defremove_check -
defremove_mentions -
asyncsend_bot_help -
asyncsend_cog_help -
asyncsend_command_help -
asyncsend_error_message -
asyncsend_group_help -
defsubcommand_not_found
- class discord.ext.commands.HelpCommand(*args, **kwargs)
-
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.- context
-
The context that invoked this help formatter. This is generally set after
the help command assigned,command_callback()
, has been called.- Type:
-
Optional[
Context
]
- show_hidden
-
Specifies if hidden commands should be shown in the output.
Defaults toFalse
.- Type:
-
bool
- verify_checks
-
Specifies if commands should have their
Command.checks
called
and verified. IfTrue
, always callsCommands.checks
.
IfNone
, only callsCommands.checks
in a guild setting.
IfFalse
, never callsCommands.checks
. Defaults toTrue
.Changed in version 1.7.
- Type:
-
Optional[
bool
]
- command_attrs
-
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 theCommand
constructor.- Type:
-
dict
- add_check(func)
-
Adds a check to the help command.
New in version 1.4.
- Parameters:
-
func – The function that will be used as a check.
- remove_check(func)
-
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.
- Parameters:
-
func – The function to remove from the checks.
- get_bot_mapping()
-
Retrieves the bot mapping passed to
send_bot_help()
.
- property clean_prefix
-
The cleaned up invoke prefix. i.e. mentions are
@name
instead of<@id>
.- Type:
-
str
- property invoked_with
-
Similar to
Context.invoked_with
except properly handles
the case whereContext.send_help()
is used.If the help command was used regularly then this returns
theContext.invoked_with
attribute. Otherwise, if
it the help command was called usingContext.send_help()
then it returns the internal command name of the help command.- Returns:
-
The command name that triggered this invocation.
- Return type:
-
str
- get_command_signature(command)
-
Retrieves the signature portion of the help page.
- Parameters:
-
command (
Command
) – The command to get the signature of. - Returns:
-
The signature for the command.
- Return type:
-
str
- remove_mentions(string)
-
Removes mentions from the string to prevent abuse.
This includes
@everyone
,@here
, member mentions and role mentions.- Returns:
-
The string with mentions removed.
- Return type:
-
str
- property cog
-
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
.- Returns:
-
The cog that is currently set for the help command.
- Return type:
-
Optional[
Cog
]
- command_not_found(string)
-
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.
- Parameters:
-
string (
str
) – The string that contains the invalid command. Note that this has
had mentions removed to prevent abuse. - Returns:
-
The string to use when a command has not been found.
- Return type:
-
str
- subcommand_not_found(command, string)
-
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 namedstring
.
-
- Parameters:
-
-
command (
Command
) – The command that did not have the subcommand requested. -
string (
str
) – The string that contains the invalid subcommand. Note that this has
had mentions removed to prevent abuse.
-
- Returns:
-
The string to use when the command did not have the subcommand requested.
- Return type:
-
str
-
- await filter_commands(commands, *, sort=False, key=None)
-
This function is a coroutine.
Returns a filtered list of commands and optionally sorts them.
This takes into account the
verify_checks
andshow_hidden
attributes.- Parameters:
-
-
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 tosorted()
that
takes aCommand
as its sole parameter. Ifsort
is
passed asTrue
then this will default as the command name.
-
- Returns:
-
A list of commands that passed the filter.
- Return type:
-
List[
Command
]
- get_max_size(commands)
-
Returns the largest name length of the specified command list.
- Parameters:
-
commands (Sequence[
Command
]) – A sequence of commands to check for the largest size. - Returns:
-
The maximum width of the commands.
- Return type:
-
int
- get_destination()
-
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.
- Returns:
-
The destination where the help command will be output.
- Return type:
-
abc.Messageable
- await send_error_message(error)
-
This function is a coroutine.
Handles the implementation when an error happens in the help command.
For example, the result ofcommand_not_found()
or
command_has_no_subcommand_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 byget_destination()
.Note
You can access the invocation context with
HelpCommand.context
.- Parameters:
-
error (
str
) – The error message to display to the user. Note that this has
had mentions removed to prevent abuse.
- await on_help_command_error(ctx, error)
-
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.- Parameters:
-
-
ctx (
Context
) – The invocation context. -
error (
CommandError
) – The error that was raised.
-
- await send_bot_help(mapping)
-
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 useget_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 callfilter_commands()
yourself.- Parameters:
-
mapping (Mapping[Optional[
Cog
], List[Command
]]) – A mapping of cogs to commands that have been requested by the user for help.
The key of the mapping is theCog
that the command belongs to, or
None
if there isn’t one, and the value is a list of commands that belongs to that cog.
- await send_cog_help(cog)
-
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 useget_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 cog see
Cog.get_commands()
.
The commands returned not filtered. To do the filtering you will have to call
filter_commands()
yourself.- Parameters:
-
cog (
Cog
) – The cog that was requested for help.
- await send_group_help(group)
-
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 useget_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 callfilter_commands()
yourself.- Parameters:
-
group (
Group
) – The group that was requested for help.
- await send_command_help(command)
-
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 useget_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
.Showing Help
There are certain attributes and methods that are helpful for a help command
to show such as the following:-
Command.help
-
Command.brief
-
Command.short_doc
-
Command.description
-
get_command_signature()
There are more than just these attributes but feel free to play around with
these to help you get started to get the output that you want.- Parameters:
-
command (
Command
) – The command that was requested for help.
-
- await prepare_help_command(ctx, command=None)
-
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.- Parameters:
-
-
ctx (
Context
) – The invocation context. -
command (Optional[
str
]) – The argument passed to the help command.
-
- await command_callback(ctx, *, command=None)
-
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.-
send_bot_help()
-
send_cog_help()
-
send_group_help()
-
send_command_help()
-
get_destination()
-
command_not_found()
-
subcommand_not_found()
-
send_error_message()
-
on_help_command_error()
-
prepare_help_command()
-
DefaultHelpCommand
Methods
-
defadd_command_formatting -
defadd_indented_commands -
defget_destination -
defget_ending_note -
asyncsend_pages -
defshorten_text
- class discord.ext.commands.DefaultHelpCommand(*args, **kwargs)
-
The implementation of the default help command.
This inherits from
HelpCommand
.It extends it with the following attributes.
- width
-
The maximum number of characters that fit in a line.
Defaults to 80.- Type:
-
int
- sort_commands
-
Whether to sort the commands in the output alphabetically. Defaults to
True
.- Type:
-
bool
- dm_help
-
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. IfFalse
, none of the help
output is DM’d. IfNone
, then the bot will only DM when the help
message becomes too long (dictated by more thandm_help_threshold
characters).
Defaults toFalse
.- Type:
-
Optional[
bool
]
- dm_help_threshold
-
The number of characters the paginator must accumulate before getting DM’d to the
user ifdm_help
is set toNone
. Defaults to 1000.- Type:
-
Optional[
int
]
- indent
-
How much to indent the commands from a heading. Defaults to
2
.- Type:
-
int
- commands_heading
-
The command list’s heading string used when the help command is invoked with a category name.
Useful for i18n. Defaults to"Commands:"
- Type:
-
str
- no_category
-
The string used when there is a command which does not belong to any category(cog).
Useful for i18n. Defaults to"No Category"
- Type:
-
str
- paginator
-
The paginator used to paginate the help command output.
- Type:
-
Paginator
- shorten_text(text)
-
str
: Shortens text to fit into thewidth
.
- get_ending_note()
-
str
: Returns help command’s ending note. This is mainly useful to override for i18n purposes.
- add_indented_commands(commands, *, heading, max_size=None)
-
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 tomax_size
followed by
the command’sCommand.short_doc
and then shortened
to fit into thewidth
.- Parameters:
-
-
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, callsget_max_size()
on the
commands parameter.
-
- await send_pages()
-
A helper utility to send the page output from
paginator
to the destination.
- add_command_formatting(command)
-
A utility function to format the non-indented block of commands and groups.
- Parameters:
-
command (
Command
) – The command to format.
- get_destination()
-
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.
- Returns:
-
The destination where the help command will be output.
- Return type:
-
abc.Messageable
MinimalHelpCommand
Methods
-
defadd_aliases_formatting -
defadd_bot_commands_formatting -
defadd_command_formatting -
defadd_subcommand_formatting -
defget_command_signature -
defget_destination -
defget_ending_note -
defget_opening_note -
asyncsend_pages
- class discord.ext.commands.MinimalHelpCommand(*args, **kwargs)
-
An implementation of a help command with minimal output.
This inherits from
HelpCommand
.- sort_commands
-
Whether to sort the commands in the output alphabetically. Defaults to
True
.- Type:
-
bool
- commands_heading
-
The command list’s heading string used when the help command is invoked with a category name.
Useful for i18n. Defaults to"Commands"
- Type:
-
str
- aliases_heading
-
The alias list’s heading string used to list the aliases of the command. Useful for i18n.
Defaults to"Aliases:"
.- Type:
-
str
- dm_help
-
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. IfFalse
, none of the help
output is DM’d. IfNone
, then the bot will only DM when the help
message becomes too long (dictated by more thandm_help_threshold
characters).
Defaults toFalse
.- Type:
-
Optional[
bool
]
- dm_help_threshold
-
The number of characters the paginator must accumulate before getting DM’d to the
user ifdm_help
is set toNone
. Defaults to 1000.- Type:
-
Optional[
int
]
- no_category
-
The string used when there is a command which does not belong to any category(cog).
Useful for i18n. Defaults to"No Category"
- Type:
-
str
- paginator
-
The paginator used to paginate the help command output.
- Type:
-
Paginator
- await send_pages()
-
A helper utility to send the page output from
paginator
to the destination.
- get_opening_note()
-
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.
- Returns:
-
The help command opening note.
- Return type:
-
str
- get_command_signature(command)
-
Retrieves the signature portion of the help page.
- Parameters:
-
command (
Command
) – The command to get the signature of. - Returns:
-
The signature for the command.
- Return type:
-
str
- get_ending_note()
-
Return the help command’s ending note. This is mainly useful to override for i18n purposes.
The default implementation does nothing.
- Returns:
-
The help command ending note.
- Return type:
-
str
- add_bot_commands_formatting(commands, heading)
-
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.- Parameters:
-
-
commands (Sequence[
Command
]) – A list of commands that belong to the heading. -
heading (
str
) – The heading to add to the line.
-
- add_subcommand_formatting(command)
-
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’sCommand.short_doc
.- Parameters:
-
command (
Command
) – The command to show information of.
- add_aliases_formatting(aliases)
-
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.
- Parameters:
-
aliases (Sequence[
str
]) – A list of aliases to format.
- add_command_formatting(command)
-
A utility function to format commands and groups.
- Parameters:
-
command (
Command
) – The command to format.
- get_destination()
-
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.
- Returns:
-
The destination where the help command will be output.
- Return type:
-
abc.Messageable
Paginator
Methods
-
defadd_line -
defclear -
defclose_page
- class discord.ext.commands.Paginator(prefix=‘«`’, suffix=‘«`’, max_size=2000, linesep=‘n’)
-
A class that aids in paginating code blocks for Discord messages.
- len(x)
-
Returns the total number of characters in the paginator.
- prefix
-
The prefix inserted to every page. e.g. three backticks.
- Type:
-
str
- suffix
-
The suffix appended at the end of every page. e.g. three backticks.
- Type:
-
str
- max_size
-
The maximum amount of codepoints allowed in a page.
- Type:
-
int
- linesep
-
- The character string inserted between lines. e.g. a newline character.
-
New in version 1.7.
- Type:
-
str
- clear()
-
Clears the paginator to have no pages.
- add_line(line=», *, empty=False)
-
Adds a line to the current page.
If the line exceeds the
max_size
then an exception
is raised.- Parameters:
-
-
line (
str
) – The line to add. -
empty (
bool
) – Indicates if another empty line should be added.
-
- Raises:
-
RuntimeError – The line was too big for the current
max_size
.
- close_page()
-
Prematurely terminate a page.
- property pages
-
Returns the rendered list of pages.
- Type:
-
List[
str
]
Enums
- class discord.ext.commands.BucketType
-
Specifies a type of bucket for, e.g. a cooldown.
- default
-
The default bucket operates on a global basis.
- user
-
The user bucket operates on a per-user basis.
- guild
-
The guild bucket operates on a per-guild basis.
- channel
-
The channel bucket operates on a per-channel basis.
- member
-
The member bucket operates on a per-member basis.
- category
-
The category bucket operates on a per-category basis.
- role
-
The role bucket operates on a per-role basis.
New in version 1.3.
Checks
- discord.ext.commands.check(predicate)
-
A decorator that adds a check to the
Command
or its
subclasses. These checks could be accessed viaCommand.checks
.These checks should be predicates that take in a single parameter taking
aContext
. If the check returns aFalse
-like value then
during invocation aCheckFailure
exception is raised and sent to
theon_command_error()
event.If an exception should be thrown in the predicate then it should be a
subclass ofCommandError
. 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!')
- Parameters:
-
predicate (Callable[[
Context
],bool
]) – The predicate to check if the command should be invoked.
- discord.ext.commands.check_any(*checks)
-
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 fromCheckFailure
.Note
The
predicate
attribute for this function is a coroutine.New in version 1.3.
- Parameters:
-
*checks (Callable[[
Context
],bool
]) – An argument list of checks that have been decorated with
thecheck()
decorator. - Raises:
-
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!')
- discord.ext.commands.has_role(item)
-
A
check()
that is added that checks if the member invoking the
command has the role specified via the name or ID specified.If a string is specified, you must give the exact name of the role, including
caps and spelling.If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will
returnFalse
.This check raises one of two special exceptions,
MissingRole
if the user
is missing a role, orNoPrivateMessage
if it is used in a private message.
Both inherit fromCheckFailure
.Changed in version 1.1: Raise
MissingRole
orNoPrivateMessage
instead of genericCheckFailure
- Parameters:
-
item (Union[
int
,str
]) – The name or ID of the role to check.
- discord.ext.commands.has_permissions(**perms)
-
A
check()
that is added that checks if the member has all of
the permissions necessary.Note that this check operates on the 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 fromCheckFailure
.- Parameters:
-
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.')
- discord.ext.commands.has_guild_permissions(**perms)
-
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.
- discord.ext.commands.has_any_role(*items)
-
A
check()
that is added that checks if the member invoking the
command has any of the roles specified. This means that if they have
one out of the three roles specified, then this check will 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, orNoPrivateMessage
if it is used in a private message.
Both inherit fromCheckFailure
.Changed in version 1.1: Raise
MissingAnyRole
orNoPrivateMessage
instead of genericCheckFailure
- Parameters:
-
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')
- discord.ext.commands.bot_has_role(item)
-
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, orNoPrivateMessage
if it is used in a private message.
Both inherit fromCheckFailure
.Changed in version 1.1: Raise
BotMissingRole
orNoPrivateMessage
instead of genericCheckFailure
- discord.ext.commands.bot_has_permissions(**perms)
-
Similar to
has_permissions()
except checks if the bot itself has
the permissions listed.This check raises a special exception,
BotMissingPermissions
that is inherited fromCheckFailure
.
- discord.ext.commands.bot_has_guild_permissions(**perms)
-
Similar to
has_guild_permissions()
, but checks the bot
members guild permissions.New in version 1.3.
- discord.ext.commands.bot_has_any_role(*items)
-
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, orNoPrivateMessage
if it is used in a private message.
Both inherit fromCheckFailure
.Changed in version 1.1: Raise
BotMissingAnyRole
orNoPrivateMessage
instead of generic checkfailure
- discord.ext.commands.cooldown(rate, per, type=<BucketType.default: 0>)
-
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 oftype
which must be of enum
typeBucketType
.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.
- Parameters:
-
-
rate (
int
) – The number of times a command can be used before triggering a cooldown. -
per (
float
) – The amount of seconds to wait for a cooldown when it’s been triggered. -
type (Union[
BucketType
, Callable[[Message
], 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.
-
- discord.ext.commands.max_concurrency(number, per=<BucketType.default: 0>, *, wait=False)
-
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.
- Parameters:
-
-
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 tonumber
times per guild. -
wait (
bool
) – Whether the command should wait for the queue to be over. If this is set toFalse
then instead of waiting until the command can run again, the command raises
MaxConcurrencyReached
to its error handler. If this is set toTrue
then the command waits until it can be executed.
-
- discord.ext.commands.before_invoke(coro)
-
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.
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('and i have existed since {}'.format(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') bot.add_cog(What())
- discord.ext.commands.after_invoke(coro)
-
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.
- discord.ext.commands.guild_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 fromCheckFailure
.
- discord.ext.commands.dm_only()
-
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 fromCheckFailure
.New in version 1.1.
- discord.ext.commands.is_owner()
-
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
fromCheckFailure
.
- discord.ext.commands.is_nsfw()
-
A
check()
that checks if the channel is a NSFW channel.This check raises a special exception,
NSFWChannelRequired
that is derived fromCheckFailure
.Changed in version 1.1: Raise
NSFWChannelRequired
instead of genericCheckFailure
.
DM channels will also now pass this check.
Context
Attributes
- args
- author
- bot
- channel
- cog
- command
- command_failed
- guild
- invoked_parents
- invoked_subcommand
- invoked_with
- kwargs
- me
- message
- prefix
- subcommand_passed
- valid
- voice_client
Methods
-
asyncfetch_message -
defhistory -
asyncinvoke -
asyncpins -
asyncreinvoke -
asyncreply -
asyncsend -
asyncsend_help -
asynctrigger_typing -
deftyping
- class discord.ext.commands.Context(**attrs)
-
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.- message
-
The message that triggered the command being executed.
- Type:
-
Message
- bot
-
The bot that contains the command being executed.
- Type:
-
Bot
- args
-
The list of transformed arguments that were passed into the command.
If this is accessed during theon_command_error()
event
then this list could be incomplete.- Type:
-
list
- kwargs
-
A dictionary of transformed arguments that were passed into the command.
Similar toargs
, if this is accessed in the
on_command_error()
event then this dict could be incomplete.- Type:
-
dict
- prefix
-
The prefix that was used to invoke the command.
- Type:
-
str
- command
-
The command that is being invoked currently.
- Type:
-
Command
- invoked_with
-
The command name that triggered this invocation. Useful for finding out
which alias called the command.- Type:
-
str
- invoked_parents
-
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.
- Type:
-
List[
str
]
- invoked_subcommand
-
The subcommand that was invoked.
If no valid subcommand was invoked then this is equal toNone
.- Type:
-
Command
- subcommand_passed
-
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 toNone
.- Type:
-
Optional[
str
]
- command_failed
-
A boolean that indicates if the command failed to be parsed, checked,
or invoked.- Type:
-
bool
- async for … in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
-
Returns an
AsyncIterator
that enables receiving the destination’s message history.You must have
read_message_history
permissions to use 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 = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- Parameters:
-
-
limit (Optional[
int
]) – The number of messages to retrieve.
IfNone
, 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 date is provided it must be a timezone-naive datetime representing UTC time. -
after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message.
If a date is provided it must be a timezone-naive datetime representing UTC time. -
around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message.
If a date is provided it must be a timezone-naive datetime representing UTC 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 toTrue
, return messages in oldest->newest order. Defaults toTrue
if
after
is specified, otherwiseFalse
.
-
- Raises:
-
-
Forbidden – You do not have permissions to get channel message history.
-
HTTPException – The request to get message history failed.
-
- Yields:
-
Message
– The message with the message data parsed.
- async with typing()
-
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
Note
This is both a regular context manager and an async context manager.
This means that bothwith
andasync with
work with this.Example Usage:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
- await invoke(*args, **kwargs)
-
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.Warning
The first parameter passed must be the command being invoked.
- Parameters:
-
-
command (
Command
) – The command that is going to be called. -
*args – The arguments to to use.
-
**kwargs – The keyword arguments to use.
-
- Raises:
-
TypeError – The command argument to invoke is missing.
- await reinvoke(*, call_hooks=False, restart=True)
-
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 regularinvoke()
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.- Parameters:
-
-
call_hooks (
bool
) – Whether to call the before and after invoke hooks. -
restart (
bool
) – Whether to start the call chain from the very beginning
or where we left off (i.e. the command that caused the error).
The default is to start where we left off.
-
- Raises:
-
ValueError – The context to reinvoke is not valid.
- property valid
-
Checks if the invocation context is valid to be invoked with.
- Type:
-
bool
- property cog
-
Returns the cog associated with this context’s command. None if it does not exist.
- Type:
-
Optional[
Cog
]
- guild
-
Returns the guild associated with this context’s command. None if not available.
- Type:
-
Optional[
Guild
]
- channel
-
Returns the channel associated with this context’s command.
Shorthand forMessage.channel
.- Type:
-
Union[
abc.Messageable
]
-
Union[
User
,Member
]:
Returns the author associated with this context’s command. Shorthand forMessage.author
- me
-
Union[
Member
,ClientUser
]:
Similar toGuild.me
except it may return theClientUser
in private message contexts.
- property voice_client
-
A shortcut to
Guild.voice_client
, if applicable.- Type:
-
Optional[
VoiceProtocol
]
- await send_help(entity=<bot>)
-
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 aCommand
.Note
Due to the way this function works, instead of returning
something similar tocommand_not_found()
this returnsNone
on bad input or no help command.- Parameters:
-
entity (Optional[Union[
Command
,Cog
,str
]]) – The entity to show help for. - Returns:
-
The result of the help command, if any.
- Return type:
-
Any
- await reply(content=None, **kwargs)
-
This function is a coroutine.
A shortcut method to
abc.Messageable.send()
to reply to the
Message
.New in version 1.6.
- Raises:
-
-
HTTPException – Sending the message failed.
-
Forbidden – You do not have the proper permissions to send the message.
-
InvalidArgument – The
files
list is not of the appropriate size or
you specified bothfile
andfiles
.
-
- Returns:
-
The message that was sent.
- Return type:
-
Message
- await fetch_message(id)
-
This function is a coroutine.
Retrieves a single
Message
from the destination.This can only be used by bot accounts.
- Parameters:
-
id (
int
) – The message ID to look for. - Raises:
-
-
NotFound – The specified message was not found.
-
Forbidden – You do not have the permissions required to get a message.
-
HTTPException – Retrieving the message failed.
-
- Returns:
-
The message asked for.
- Return type:
-
Message
- await pins()
-
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Message
objects returned by this method do not contain complete
Message.reactions
data.- Raises:
-
HTTPException – Retrieving the pinned messages failed.
- Returns:
-
The messages that are currently pinned.
- Return type:
-
List[
Message
]
- await send(content=None, *, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)
-
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
.
If the content is set toNone
(the default), then theembed
parameter must
be provided.To upload a single file, the
file
parameter should be used with a
singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects.If the
embed
parameter is provided, it must be of typeEmbed
and
it must be a rich embed type.- Parameters:
-
-
content (
str
) – The content of the message to send. -
tts (
bool
) – Indicates if the message should be sent using text-to-speech. -
embed (
Embed
) – The rich embed for the content. -
embeds (List[
Embed
]) – A list containing up to ten embeds -
components (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) – A list of up to fiveButton
’s or oneBaseSelect
like object. -
file (
File
) – The file to upload. -
files (List[
File
]) – Alist
of files to upload. Must be a maximum of 10. -
stickers (List[
GuildSticker
]) – A list of up to 3discord.GuildSticker
that should be sent with the message. -
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 withallowed_mentions
.
The merging behaviour only overrides attributes that have been explicitly passed
to the object, otherwise it uses the attributes set inallowed_mentions
.
If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
-
reference (Union[
Message
,MessageReference
]) –A reference to the
Message
to which you are replying, this can be created using
to_reference()
or passed directly as aMessage
. You can control
whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
-
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
-
suppress_embeds (
bool
) – Whether to supress embeds send with the message, default toFalse
-
suppress_notifications (
bool
) –Whether to suppress desktop- & push-notifications for this message, default to
False
Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.
New in version 2.0.
-
- Raises:
-
-
HTTPException – Sending the message failed.
-
Forbidden – You do not have the proper permissions to send the message.
-
InvalidArgument – The
files
list is not of the appropriate size,
you specified bothfile
andfiles
,
or thereference
object is not aMessage
orMessageReference
.
-
- Returns:
-
The message that was sent.
- Return type:
-
Message
- await trigger_typing()
-
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
Converters
- class discord.ext.commands.Converter
-
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 caseddiscord
classes.Classes that derive from this should override the
convert()
method to do its conversion logic. This method must be a coroutine.- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
- class discord.ext.commands.MemberConverter
-
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 name#discrim
-
Lookup by name
-
Lookup by nickname
Changed in version 1.5: Raise
MemberNotFound
instead of genericBadArgument
Changed in version 1.5.1: This converter now lazily fetches members from the gateway and HTTP APIs,
optionally caching the result ifMemberCacheFlags.joined
is enabled.- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.UserConverter
-
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 name#discrim
-
Lookup by name
Changed in version 1.5: Raise
UserNotFound
instead of genericBadArgument
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.- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.MessageConverter
-
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
orChannelNotReadable
instead of genericBadArgument
- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.PartialMessageConverter
-
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
- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.TextChannelConverter
-
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 name
Changed in version 1.5: Raise
ChannelNotFound
instead of genericBadArgument
- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.VoiceChannelConverter
-
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 name
Changed in version 1.5: Raise
ChannelNotFound
instead of genericBadArgument
- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.StoreChannelConverter
-
Converts to a
StoreChannel
.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 name.
New in version 1.7.
- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.StageChannelConverter
-
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 name
- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.CategoryChannelConverter
-
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 name
Changed in version 1.5: Raise
ChannelNotFound
instead of genericBadArgument
- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.InviteConverter
-
Converts to a
Invite
.This is done via an HTTP request using
Bot.fetch_invite()
.Changed in version 1.5: Raise
BadInviteArgument
instead of genericBadArgument
- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
- class discord.ext.commands.GuildConverter
-
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.
- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.RoleConverter
-
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 genericBadArgument
- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.GameConverter
-
Converts to
Game
.- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
- class discord.ext.commands.ColourConverter
-
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
inColour
-
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 genericBadArgument
Changed in version 1.7: Added support for
rgb
function and 3-digit hex shortcuts- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.EmojiConverter
-
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 genericBadArgument
- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
-
- class discord.ext.commands.PartialEmojiConverter
-
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 genericBadArgument
- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
- class discord.ext.commands.clean_content(*, fix_channel_mentions=False, use_nicknames=True, escape_markdown=False, remove_markdown=False)
-
Converts the argument to mention scrubbed version of
said content.This behaves similarly to
clean_content
.- fix_channel_mentions
-
Whether to clean channel mentions.
- Type:
-
bool
- use_nicknames
-
Whether to use nicknames when transforming mentions.
- Type:
-
bool
- escape_markdown
-
Whether to also escape special markdown characters.
- Type:
-
bool
- remove_markdown
-
Whether to also remove special markdown characters. This option is not supported with
escape_markdown
New in version 1.7.
- Type:
-
bool
- await convert(ctx, argument)
-
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 aCommandError
derived exception as it will
properly propagate to the error handlers.- Parameters:
-
-
ctx (
Context
) – The invocation context that the argument is being used in. -
argument (
str
) – The argument that is being converted.
-
- Raises:
-
-
.CommandError – A generic exception occurred when converting the argument.
-
.BadArgument – The converter failed to convert the argument.
-
- ext.commands.Greedy
-
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 passnumbers
with
[1, 2, 3, 4, 5, 6]
andreason
withhello
.For more information, check Special Converters.
Exceptions
- exception discord.ext.commands.CommandError(message=None, *args)
-
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
fromBot
,on_command_error()
.
- exception discord.ext.commands.ConversionError(converter, original)
-
Exception raised when a Converter class raises non-CommandError.
This inherits from
CommandError
.- converter
-
The converter that failed.
- Type:
-
discord.ext.commands.Converter
- original
-
The original exception that was raised. You can also get this via
the__cause__
attribute.- Type:
-
Exception
- exception discord.ext.commands.MissingRequiredArgument(param)
-
Exception raised when parsing a command and a parameter
that is required is not encountered.This inherits from
UserInputError
- param
-
The argument that is missing.
- Type:
-
inspect.Parameter
- exception discord.ext.commands.ArgumentParsingError(message=None, *args)
-
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.
- exception discord.ext.commands.UnexpectedQuoteError(quote)
-
An exception raised when the parser encounters a quote mark inside a non-quoted string.
This inherits from
ArgumentParsingError
.- quote
-
The quote mark that was found inside the non-quoted string.
- Type:
-
str
- exception discord.ext.commands.InvalidEndOfQuotedStringError(char)
-
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
.- char
-
The character found instead of the expected string.
- Type:
-
str
- exception discord.ext.commands.ExpectedClosingQuoteError(close_quote)
-
An exception raised when a quote character is expected but not found.
This inherits from
ArgumentParsingError
.- close_quote
-
The quote character expected.
- Type:
-
str
- exception discord.ext.commands.BadArgument(message=None, *args)
-
Exception raised when a parsing or conversion failure is encountered
on an argument to pass into a command.This inherits from
UserInputError
- exception discord.ext.commands.BadUnionArgument(param, converters, errors)
-
Exception raised when a
typing.Union
converter fails for all
its associated types.This inherits from
UserInputError
- param
-
The parameter that failed being converted.
- Type:
-
inspect.Parameter
- converters
-
A tuple of converters attempted in conversion, in order of failure.
- Type:
-
Tuple[Type, …]
- errors
-
A list of errors that were caught from failing the conversion.
- Type:
-
List[
CommandError
]
- exception discord.ext.commands.PrivateMessageOnly(message=None)
-
Exception raised when an operation does not work outside of private
message contexts.This inherits from
CheckFailure
- exception discord.ext.commands.NoPrivateMessage(message=None)
-
Exception raised when an operation does not work in private message
contexts.This inherits from
CheckFailure
- exception discord.ext.commands.CheckFailure(message=None, *args)
-
Exception raised when the predicates in
Command.checks
have failed.This inherits from
CommandError
- exception discord.ext.commands.CheckAnyFailure(checks, errors)
-
Exception raised when all predicates in
check_any()
fail.This inherits from
CheckFailure
.New in version 1.3.
- errors
-
A list of errors that were caught during execution.
- Type:
-
List[
CheckFailure
]
- checks
-
A list of check predicates that failed.
- Type:
-
List[Callable[[
Context
],bool
]]
- exception discord.ext.commands.CommandNotFound(message=None, *args)
-
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 discord.ext.commands.DisabledCommand(message=None, *args)
-
Exception raised when the command being invoked is disabled.
This inherits from
CommandError
- exception discord.ext.commands.CommandInvokeError(e)
-
Exception raised when the command being invoked raised an exception.
This inherits from
CommandError
- original
-
The original exception that was raised. You can also get this via
the__cause__
attribute.- Type:
-
Exception
- exception discord.ext.commands.TooManyArguments(message=None, *args)
-
Exception raised when the command was passed too many arguments and its
Command.ignore_extra
attribute was not set toTrue
.This inherits from
UserInputError
- exception discord.ext.commands.UserInputError(message=None, *args)
-
The base exception type for errors that involve errors
regarding user input.This inherits from
CommandError
.
- exception discord.ext.commands.CommandOnCooldown(cooldown, retry_after)
-
Exception raised when the command being invoked is on cooldown.
This inherits from
CommandError
- cooldown
-
A class with attributes
rate
,per
, andtype
similar to
thecooldown()
decorator.- Type:
-
Cooldown
- retry_after
-
The amount of seconds to wait before you can retry again.
- Type:
-
float
- exception discord.ext.commands.MaxConcurrencyReached(number, per)
-
Exception raised when the command being invoked has reached its maximum concurrency.
This inherits from
CommandError
.- number
-
The maximum number of concurrent invokers allowed.
- Type:
-
int
- per
-
The bucket type passed to the
max_concurrency()
decorator.- Type:
-
BucketType
- exception discord.ext.commands.NotOwner(message=None, *args)
-
Exception raised when the message author is not the owner of the bot.
This inherits from
CheckFailure
- exception discord.ext.commands.MessageNotFound(argument)
-
Exception raised when the message provided was not found in the channel.
This inherits from
BadArgument
New in version 1.5.
- argument
-
The message supplied by the caller that was not found
- Type:
-
str
- exception discord.ext.commands.MemberNotFound(argument)
-
Exception raised when the member provided was not found in the bot’s
cache.This inherits from
BadArgument
New in version 1.5.
- argument
-
The member supplied by the caller that was not found
- Type:
-
str
- exception discord.ext.commands.GuildNotFound(argument)
-
Exception raised when the guild provided was not found in the bot’s cache.
This inherits from
BadArgument
New in version 1.7.
- argument
-
The guild supplied by the called that was not found
- Type:
-
str
- exception discord.ext.commands.UserNotFound(argument)
-
Exception raised when the user provided was not found in the bot’s
cache.This inherits from
BadArgument
New in version 1.5.
- argument
-
The user supplied by the caller that was not found
- Type:
-
str
- exception discord.ext.commands.ChannelNotFound(argument)
-
Exception raised when the bot can not find the channel.
This inherits from
BadArgument
New in version 1.5.
- argument
-
The channel supplied by the caller that was not found
- Type:
-
str
- exception discord.ext.commands.ChannelNotReadable(argument)
-
Exception raised when the bot does not have permission to read messages
in the channel.This inherits from
BadArgument
New in version 1.5.
- argument
-
The channel supplied by the caller that was not readable
- Type:
-
abc.GuildChannel
- exception discord.ext.commands.BadColourArgument(argument)
-
Exception raised when the colour is not valid.
This inherits from
BadArgument
New in version 1.5.
- argument
-
The colour supplied by the caller that was not valid
- Type:
-
str
- exception discord.ext.commands.RoleNotFound(argument)
-
Exception raised when the bot can not find the role.
This inherits from
BadArgument
New in version 1.5.
- argument
-
The role supplied by the caller that was not found
- Type:
-
str
- exception discord.ext.commands.BadInviteArgument
-
Exception raised when the invite is invalid or expired.
This inherits from
BadArgument
New in version 1.5.
- exception discord.ext.commands.EmojiNotFound(argument)
-
Exception raised when the bot can not find the emoji.
This inherits from
BadArgument
New in version 1.5.
- argument
-
The emoji supplied by the caller that was not found
- Type:
-
str
- exception discord.ext.commands.PartialEmojiConversionFailure(argument)
-
Exception raised when the emoji provided does not match the correct
format.This inherits from
BadArgument
New in version 1.5.
- argument
-
The emoji supplied by the caller that did not match the regex
- Type:
-
str
- exception discord.ext.commands.BadBoolArgument(argument)
-
Exception raised when a boolean argument was not convertable.
This inherits from
BadArgument
New in version 1.5.
- argument
-
The boolean argument supplied by the caller that is not in the predefined list
- Type:
-
str
- exception discord.ext.commands.MissingPermissions(missing_perms, *args)
-
Exception raised when the command invoker lacks permissions to run a
command.This inherits from
CheckFailure
- missing_perms
-
The required permissions that are missing.
- Type:
-
list
- exception discord.ext.commands.BotMissingPermissions(missing_perms, *args)
-
Exception raised when the bot’s member lacks permissions to run a
command.This inherits from
CheckFailure
- missing_perms
-
The required permissions that are missing.
- Type:
-
list
- exception discord.ext.commands.MissingRole(missing_role)
-
Exception raised when the command invoker lacks a role to run a command.
This inherits from
CheckFailure
New in version 1.1.
- missing_role
-
The required role that is missing.
This is the parameter passed tohas_role()
.- Type:
-
Union[
str
,int
]
- exception discord.ext.commands.BotMissingRole(missing_role)
-
Exception raised when the bot’s member lacks a role to run a command.
This inherits from
CheckFailure
New in version 1.1.
- missing_role
-
The required role that is missing.
This is the parameter passed tohas_role()
.- Type:
-
Union[
str
,int
]
- exception discord.ext.commands.MissingAnyRole(missing_roles)
-
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.
- missing_roles
-
The roles that the invoker is missing.
These are the parameters passed tohas_any_role()
.- Type:
-
List[Union[
str
,int
]]
- exception discord.ext.commands.BotMissingAnyRole(missing_roles)
-
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.
- missing_roles
-
The roles that the bot’s member is missing.
These are the parameters passed tohas_any_role()
.- Type:
-
List[Union[
str
,int
]]
- exception discord.ext.commands.NSFWChannelRequired(channel)
-
Exception raised when a channel does not have the required NSFW setting.
This inherits from
CheckFailure
.New in version 1.1.
- Parameters:
-
channel (
discord.abc.GuildChannel
) – The channel that does not have NSFW enabled.
- exception discord.ext.commands.ExtensionError(message=None, *args, name)
-
Base exception for extension related errors.
This inherits from
DiscordException
.- name
-
The extension that had an error.
- Type:
-
str
- exception discord.ext.commands.ExtensionAlreadyLoaded(name)
-
An exception raised when an extension has already been loaded.
This inherits from
ExtensionError
- exception discord.ext.commands.ExtensionNotLoaded(name)
-
An exception raised when an extension was not loaded.
This inherits from
ExtensionError
- exception discord.ext.commands.NoEntryPointError(name)
-
An exception raised when an extension does not have a
setup
entry point function.This inherits from
ExtensionError
- exception discord.ext.commands.ExtensionFailed(name, original)
-
An exception raised when an extension failed to load during execution of the module or
setup
entry point.This inherits from
ExtensionError
- name
-
The extension that had the error.
- Type:
-
str
- original
-
The original exception that was raised. You can also get this via
the__cause__
attribute.- Type:
-
Exception
- exception discord.ext.commands.ExtensionNotFound(name, original=None)
-
An exception raised when an extension is not found.
This inherits from
ExtensionError
Changed in version 1.3: Made the
original
attribute always None.- name
-
The extension that had the error.
- Type:
-
str
- original
-
Always
None
for backwards compatibility.- Type:
-
NoneType
- exception discord.ext.commands.CommandRegistrationError(name, *, alias_conflict=False)
-
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.
- name
-
The command name that had the error.
- Type:
-
str
- alias_conflict
-
Whether the name that conflicts is an alias of the command we try to add.
- Type:
-
bool
Exception Hierarchy
-
DiscordException
-
-
CommandError
-
-
ConversionError
-
UserInputError
-
-
MissingRequiredArgument
-
TooManyArguments
-
BadArgument
-
-
MessageNotFound
-
MemberNotFound
-
UserNotFound
-
ChannelNotFound
-
ChannelNotReadable
-
BadColourArgument
-
RoleNotFound
-
BadInviteArgument
-
EmojiNotFound
-
PartialEmojiConversionFailure
-
BadBoolArgument
-
-
BadUnionArgument
-
ArgumentParsingError
-
-
UnexpectedQuoteError
-
InvalidEndOfQuotedStringError
-
ExpectedClosingQuoteError
-
-
-
CommandNotFound
-
CheckFailure
-
-
CheckAnyFailure
-
PrivateMessageOnly
-
NoPrivateMessage
-
NotOwner
-
MissingPermissions
-
BotMissingPermissions
-
MissingRole
-
BotMissingRole
-
MissingAnyRole
-
BotMissingAnyRole
-
NSFWChannelRequired
-
-
DisabledCommand
-
CommandInvokeError
-
CommandOnCooldown
-
MaxConcurrencyReached
-
-
ExtensionError
-
-
ExtensionAlreadyLoaded
-
ExtensionNotLoaded
-
NoEntryPointError
-
ExtensionFailed
-
ExtensionNotFound
-
-
-
ClientException
-
-
CommandRegistrationError
-
Я пытаюсь отправить сообщение, когда команда не найдена, но она не работает:
@client.event
async def on_ready():
change_status.start()
print("----------------------")
print("Logged In As")
print("Username: %s" % client.user.name)
print("ID: %s" % client.user.id)
print("----------------------")
async def on_message(ctx, error):
if isinstance(error, commands.CommandNotFound):
text = ('Sorry {}, this command does not exist check $help for a more detailed list of').format(ctx.author.mention)
msg = await ctx.send(text)
await ctx.message.delete()
await asyncio.sleep(5)
await msg.delete()
else:
pass
raise error
3 ответа
Лучший ответ
Я нашел ответ на свою проблему, вместо того, чтобы запускать ее через декоратор client.event, я запускал ее через декоратор client.listen:
@client.event
async def on_ready():
change_status.start()
print("----------------------")
print("Logged In As")
print("Username: %s" % client.user.name)
print("ID: %s" % client.user.id)
print("----------------------")
@client.listen()
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
text = ('Sorry {}, this command does not exist check $help for a more detailed list of').format(ctx.author.mention)
msg = await ctx.send(text)
await ctx.message.delete()
await asyncio.sleep(5)
await msg.delete()
0
master_0ogway
25 Ноя 2020 в 16:49
Вы ищете мероприятие on_command_error
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send("Command does not exist.")
Справка:
- on_command_error
1
Łukasz Kwieciński
25 Ноя 2020 в 15:10
Событие on_command_error
вызывается, когда возникает ошибка при выполнении любой команды. а внутри события on_command_error
вы можете проверить, является ли ошибка экземпляром CommandNotFound
, который выдается, когда набранная команда не найдена, или она не существует. И если это так, вы можете отправить сообщение в канал, где была использована команда.
@client.event
async def on_command_error(ctx, error):
"""Command error handler"""
embed = discord.Embed(color=discord.Color.red())
if isinstance(error, commands.CommandNotFound):
embed.title = "Command not Found"
embed.description = "Recheck what you've typed."
#await ctx.send(embed=embed)
0
BillyDev
26 Ноя 2020 в 06:31
Всем привет, сегодня мы напишем Discord-бота на Python и discord.py + бонусом посмотрим на примеры ботов. Приступим 🙂
Перед работой
Перед тем, как начать, вам нужны:
- Python 3;
- discord.py;
- Discord-аккаунт и свой сервер.
Для установки discord.py воспользуйтесь пакетным менеджером:
pip3 install discord.py
Создаём нашего бота
Перейдите на Developer Portal и нажмите на New application.
Вы создали своё приложение, на странице приложение перейдите в Bot >> Add Bot и создайте своего Discord-бота.
Сохраните токен бота! Дальше он нам понадобится!
Если всё прошло успешно, поздравляю, половина дела сделана 😀
Добавление бота на сервер
Теперь можно добавить бота на сервер.
Перейдите в OAuth2 >> URL Generator, в Scopes выбираем Bot и ниже — права бота, копируем сгенерированный URL. Вставляем в браузер, и добавляем на наш сервер.
Эхо-бот
Напишем традиционного эхо-бота, и разберём каждую строчку кода.
Код:
import discord
from discord.ext import commands
config = {
'token': 'your-token',
'prefix': 'prefix',
}
bot = commands.Bot(command_prefix=config['prefix'])
@bot.event
async def on_message(ctx):
if ctx.author != bot.user:
await ctx.reply(ctx.content)
bot.run(config['token'])
Пример работы:
Разбор:
import discord
from discord.ext import commands
Нужные нам импорты.
config = {
'token': 'your-token',
'prefix': 'prefix',
}
Вспомогательный словарь config в котором храним токен и префикс команд (далее расскажу зачем нужен префикс команд).
bot = commands.Bot(command_prefix=config['prefix'])
Создаём нашего бота, в аргументе передаём префикс.
@bot.event
Декоратор, предназначенный для обработки событий, подробнее здесь.
async def on_message(ctx):
Создаём асинхронную функцию, с параметром ctx, представляет из себя сообщение.
if ctx.author != bot.user:
Проверка, не является ли автор сообщения нашим Discord-ботом. Дело в том, что если бот отправит сообщение, это будет новым событием, и тогда получается цикл.
await ctx.reply(ctx.content)
Отвечаем на сообщение (ctx.reply), в аргументы передаём сообщение (ctx.content).
bot.run(config['token'])
Запускаем нашего бота, в аргументы передаём токен бота.
Надеюсь вы разобрались с кодом, и мы можем переходить далее.
Обработка команд
Перед тем, как обрабатывать команды, нам пригодится наш префикс.
Рассмотрим код:
import random
import discord
from discord.ext import commands
config = {
'token': 'your-token',
'prefix': '$',
}
bot = commands.Bot(command_prefix=config['prefix'])
@bot.command()
async def rand(ctx, *arg):
await ctx.reply(random.randint(0, 100))
bot.run(config['token'])
Результат работы:
Разбор:
@bot.command()
Декоратор обработки команд
async def rand(ctx, *arg):
Асинхронная функция rand
await ctx.reply(random.randint(0, 100))
Отвечаем на сообщение, в аргументы передаём случайное число от 0 до 100
Бонус
Проверка роли:
import random
import discord
from discord.ext import commands
config = {
'token': 'your-token',
'prefix': '$',
}
bot = commands.Bot(command_prefix=config['prefix'])
@bot.command()
@commands.has_role("Хозяин")
async def rand(ctx, *arg):
await ctx.reply(random.randint(0, 100))
bot.run(config['token'])
Выгнать пользователя
import discord
from discord.ext import commands
config = {
'token': 'your-token',
'prefix': '$',
}
bot = commands.Bot(command_prefix=config['prefix'])
@bot.command()
async def kick(ctx, user : discord.User(), *arg, reason='Причина не указана'):
await bot.kick(user)
await ctx.send('Пользователь {user.name} был изгнан по причине "{reason}"')
bot.run(config['token'])