API Reference¶
The following section outlines the API of nextcord’s command extension module.
Bots¶
Bot¶
- activity
- all_views
- allowed_mentions
- application_flags
- application_id
- cached_messages
- case_insensitive
- cogs
- command_prefix
- commands
- default_guild_ids
- description
- emojis
- extensions
- guilds
- help_command
- intents
- latency
- owner_id
- owner_ids
- private_channels
- scheduled_events
- status
- stickers
- strip_after_prefix
- user
- users
- voice_clients
- defadd_all_application_commands
- defadd_all_cog_commands
- defadd_application_command
- defadd_application_command_check
- defadd_check
- defadd_cog
- defadd_command
- defadd_listener
- defadd_modal
- defadd_view
- @after_invoke
- @application_command_after_invoke
- @application_command_before_invoke
- @application_command_check
- asyncapplication_info
- asyncbefore_identify_hook
- @before_invoke
- asyncchange_presence
- @check
- @check_once
- asyncclear
- asyncclose
- @command
- asyncconnect
- asynccreate_dm
- asynccreate_guild
- asyncdelete_application_commands
- asyncdelete_invite
- asyncdiscover_application_commands
- @event
- asyncfetch_channel
- asyncfetch_guild
- asyncfetch_guild_preview
- deffetch_guilds
- asyncfetch_invite
- asyncfetch_premium_sticker_packs
- asyncfetch_stage_instance
- asyncfetch_sticker
- asyncfetch_template
- asyncfetch_user
- asyncfetch_webhook
- asyncfetch_widget
- defget_all_application_commands
- defget_all_channels
- defget_all_members
- defget_application_command
- defget_application_command_from_signature
- defget_application_commands
- defget_channel
- defget_cog
- defget_command
- asyncget_context
- defget_emoji
- defget_guild
- defget_interaction
- defget_partial_messageable
- asyncget_prefix
- defget_scheduled_event
- defget_stage_instance
- defget_sticker
- defget_user
- @group
- asyncinvoke
- defis_closed
- asyncis_owner
- defis_ready
- defis_ws_ratelimited
- @listen
- defload_extension
- defload_extensions
- defload_extensions_from_module
- asynclogin
- defmessage_command
- asyncon_application_command_error
- asyncon_command_error
- asyncon_error
- defparse_mentions
- asyncprocess_application_commands
- asyncprocess_commands
- asyncprocess_with_str
- asyncregister_application_commands
- asyncregister_new_application_commands
- defreload_extension
- defremove_application_command_check
- defremove_check
- defremove_cog
- defremove_command
- defremove_listener
- defremove_modal
- defremove_view
- defrun
- defslash_command
- asyncstart
- asyncsync_all_application_commands
- asyncsync_application_commands
- defunload_extension
- defuser_command
- defviews
- asyncwait_for
- asyncwait_until_ready
- defwalk_commands
- class nextcord.ext.commands.Bot(command_prefix=(), help_command=..., description=None, *, max_messages=1000, connector=None, proxy=None, proxy_auth=None, shard_id=None, shard_count=None, application_id=None, intents=<Intents value=3243773>, member_cache_flags=..., chunk_guilds_at_startup=..., status=None, activity=None, allowed_mentions=None, heartbeat_timeout=60.0, guild_ready_timeout=2.0, assume_unsync_clock=True, enable_debug_events=False, loop=None, lazy_load_commands=True, rollout_associate_known=True, rollout_delete_unknown=True, rollout_register_new=True, rollout_update_known=True, rollout_all_guilds=False, default_guild_ids=None, owner_id=None, owner_ids=None, strip_after_prefix=False, case_insensitive=False)¶
Represents a discord bot.
This class is a subclass of
nextcord.Client
and as a result anything that you can do with anextcord.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 and
nextcord.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:
- help_command¶
The help command implementation to use. This can be dynamically set at runtime. To remove the help command pass
None
. For more information on implementing a help command, see Help Commands.- 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 usingapplication_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:
- @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.
- @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.
- @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 fromCommandError
.Example
@bot.check def check_commands(ctx): return ctx.command.qualified_name in allowed_commands
- @check_once¶
A decorator that adds a “call once” global check to the bot.
Unlike regular global checks, this one is called only once per
invoke()
call.Regular global checks are called whenever a command is called or
Command.can_run()
is called. This type of check bypasses that and ensures that it’s called only once, even inside the default help command.Note
When using this function the
Context
sent to a group subcommand may only parse the parent command and not the subcommands due to it being invoked once 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 fromCommandError
.Example
@bot.check_once def whitelist(ctx): return ctx.message.author.id in my_whitelist
- @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!')
- 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
]
- @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 as
on_ready()
The functions being listened to must be a coroutine.
New in version 3.0.
Example
@client.listen() async def on_message(message): print('one') # in some other file... @client.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_all_application_commands()¶
Adds application commands that are either decorated by the Client or added via a cog to the state. This does not register commands with Discord. If you want that, use
sync_all_application_commands()
instead.Changed in version 3.0: This replaces the now removed
add_startup_application_commands
method.
- add_all_cog_commands()¶
Adds all
ApplicationCommand
objects inside added cogs to the application command list.
- add_application_command(command, overwrite=False, use_rollout=False, pre_remove=True)¶
Adds a BaseApplicationCommand object to the client for use.
- Parameters:
command (
ApplicationCommand
) – Command to add to the client for usage.overwrite (
bool
) – If to overwrite any existing commands that would conflict with this one. Defaults toFalse
use_rollout (
bool
) – If to apply the rollout signatures instead of existing ones. Defaults toFalse
pre_remove (
bool
) – If the command should be removed before adding it. This will clear all signatures from storage, including rollout ones.
- add_application_command_check(func)¶
Adds a global application command check to the client.
This is the non-decorator interface to
application_command_check()
.- Parameters:
func (Callable[[
Interaction
],MaybeCoro[bool]
]]) – The function that was used as a global application check.
- add_check(func, *, call_once=False)¶
Adds a global check to the bot.
This is the non-decorator interface to
check()
andcheck_once()
.
- add_cog(cog, *, override=False)¶
Adds a “cog” to the bot.
A cog is a class that has its own event listeners and commands.
Changed in version 2.0:
ClientException
is raised when a cog with the same name is already loaded.- Parameters:
- Raises:
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()
orgroup()
shortcut decorators are used instead.Changed in version 1.4: Raise
CommandRegistrationError
instead of genericClientException
- add_listener(func, name=...)¶
The non decorator alternative to
listen()
.New in version 3.0.
- Parameters:
Example
async def on_ready(): pass async def my_message(message): pass client.add_listener(on_ready) client.add_listener(my_message, 'on_message')
- add_modal(modal, *, user_id=None)¶
Registers a
Modal
for persistent listening.This method can be called for modals whose lifetime must be eventually superior to the one of the program or for modals whose call does not depend on particular criteria.
- Parameters:
modal (
nextcord.ui.Modal
) – The view to register for dispatching.user_id (Optional[
int
]) – The user ID that the view is attached to. This is used to filter the modal calls based on the users.
- Raises:
TypeError – A modal was not passed.
ValueError – The modal is not persistent. A persistent modal has a set custom_id and all their components with a set custom_id and a timeout set to None.
- add_view(view, *, message_id=None)¶
Registers a
View
for persistent listening or for non- persistent storage.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.
Changed in version 2.6: Non-persistent views can now be stored during the lifetime of the bot.
- Parameters:
view (
nextcord.ui.View
) – The view to register for dispatching or to add to storage.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. This cannot be provided if the view is non-persistent.
- Raises:
TypeError – A view was not passed.
ValueError – The message_id parameter was passed in with a non-persistent view.
- property allowed_mentions¶
The allowed mention configuration.
New in version 1.4.
- Type:
Optional[
AllowedMentions
]
- application_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. There may only be one global post-invoke hook.
This post-invoke hook takes a sole parameter, a
Interaction
.Note
Similar to
application_command_before_invoke()
, this is not called unless checks succeed. This hook is, however, always called regardless of the internal command callback raising an error (i.e.ApplicationInvokeError
). This makes it ideal for clean-up scenarios.
- application_command_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
Interaction
.Note
The
application_command_before_invoke()
andapplication_command_after_invoke()
hooks are only called if all checks pass without error. If any check fails, then the hooks are not called.
- application_command_check(func)¶
A decorator that adds a global applications command check to the client.
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 application command the client has.Note
This function can either be a regular function or a coroutine.
Similar to a application command
check()
, this takes a single parameter of typeInteraction
and can only raise exceptions inherited fromApplicationError
.Example
@client.application_command_check def check_commands(interaction: Interaction) -> bool: return interaction.application_command.qualified_name in allowed_commands
- property application_flags¶
The client’s application flags.
New in version 2.0.
- Type:
- 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. 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:
- 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.
- 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 = nextcord.Game("with the API") await client.change_presence(status=nextcord.Status.idle, activity=game)
Changed in version 2.0: Removed the
afk
keyword-only parameter.- 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
, thenStatus.online
is used.
- Raises:
.InvalidArgument – If the
activity
parameter is not the proper type.
- await 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 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.
- await create_guild(*, name, region=VoiceRegion.us_west, icon=None, 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.1: The
icon
parameter now acceptsFile
,Attachment
, andAsset
.- Parameters:
name (
str
) – The name of the guild.region (
VoiceRegion
) – The region for the voice communication server. Defaults toVoiceRegion.us_west
.icon (Optional[Union[
bytes
,Asset
,Attachment
,File
]]) – The bytes-like object,File
,Attachment
, orAsset
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.
.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:
- property default_guild_ids¶
List[
int
] The default guild ids for all application commands.New in version 2.3.
- await delete_application_commands(*commands, guild_id=None)¶
This function is a coroutine. Deletes the given application commands either from a specific guild or globally, and removes the command IDs + signatures from the bot.
- Parameters:
commands (
BaseApplicationCommand
) – Application command to delete. Multiple args are accepted.guild_id (Optional[
int
]) – ID of the guild to delete the application commands from. If set toNone
, the commands will be deleted from global commands instead. Defaults toNone
.
- 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.
- await discover_application_commands(data=None, *, guild_id=None, associate_known=True, delete_unknown=True, update_known=True)¶
This function is a coroutine. Associates existing, deletes unknown, and updates modified commands for either global commands or a specific guild. This does a deep check on found commands, which may be expensive CPU-wise.
Running this for global or the same guild multiple times at once may cause unexpected or unstable behavior.
Changed in version 3.0: This replaces the now removed
deploy_application_commands
method.- Parameters:
data (Optional[List[
dict
]]) – Payload fromHTTPClient.get_guild_commands
orHTTPClient.get_global_commands
to deploy with. If None, the payload will be retrieved from Discord.guild_id (Optional[
int
]) – Guild ID to deploy application commands to. IfNone
, global commands are deployed to.associate_known (
bool
) – If True, commands on Discord that pass a signature check and a deep check will be associated with locally added ApplicationCommand objects.delete_unknown (
bool
) – IfTrue
, commands on Discord that fail a signature check will be removed. Ifupdate_known
isFalse
, commands that pass the signature check but fail the deep check will also be removed.update_known (
bool
) – IfTrue
, commands on Discord that pass a signature check but fail the deep check will be updated.
- 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.
- 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
Using this, you will not receive
Guild.channels
,Guild.members
,Member.activity
andMember.voice
perMember
.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.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:
- await fetch_guild_preview(guild_id, /)¶
This function is a coroutine.
Fetches a
GuildPreview
from an ID.Note
This will only fetch guilds that the bot is in or that are discoverable.
New in version 2.6.
- Parameters:
guild_id (
int
) – The guild’s ID to fetch from.- Raises:
.NotFound – The guild provided is unknown.
- Returns:
The guild preview from the ID
- Return type:
- fetch_guilds(*, limit=200, with_counts=False, before=None, after=None)¶
This function returns an async iterator.
Returns an async iterator that enables receiving your guilds.
Note
Using this, you will only receive
Guild.owner
,Guild.icon
,Guild.id
, andGuild.name
perGuild
.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)
All parameters are optional.
- Parameters:
limit (Optional[
int
]) –The number of guilds to retrieve. If
None
, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to200
.Changed in version 2.0: Changed default to
200
.with_counts (
bool
) –Whether to include approximate member and presence counts for the guilds. Defaults to
False
.New in version 2.6.
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)¶
This function is a coroutine.
Gets an
Invite
from a discord.gg URL or ID.Note
If the invite is for a guild you have not joined, the guild and channel attributes of the returned
Invite
will bePartialInviteGuild
andPartialInviteChannel
respectively.- 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 theInvite.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.
- Raises:
.NotFound – The invite has expired or is invalid.
.HTTPException – Getting the invite failed.
- Returns:
The invite from the URL/ID.
- Return type:
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:
- 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.
- 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.Note
This method is an API call. If you have
nextcord.Intents.members
and member cache enabled, considerget_user()
instead.
- 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:
- 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.
- get_all_application_commands()¶
Returns a copied set of all added
BaseApplicationCommand
objects.
- 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
Note
Just because you receive a
abc.GuildChannel
does not mean that you can communicate in said channel.abc.GuildChannel.permissions_for()
should be used for that.- 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_application_command(command_id)¶
Gets an application command from the cache that has the given command ID.
- Parameters:
command_id (
int
) – Command ID corresponding to an application command.- Returns:
Returns the application command corresponding to the ID. If no command is found,
None
is returned instead.- Return type:
Optional[
BaseApplicationCommand
]
- get_application_command_from_signature(qualified_name, *, type=ApplicationCommandType.chat_input, guild=None, search_localizations=False)¶
Gets a locally stored application command object that matches the given signature.
New in version 2.0.
Changed in version 3.0: - Subcommands/Subcommand groups can now be retrieved with this method. -
name
parameter was renamed toqualified_name
and now accepts subcommands/subcommand groups separated by a space. -cmd_type
parameter was renamed totype
, defaults toApplicationCommandType.chat_input
and is now a keyword-only parameter. -guild_id
parameter was renamed toguild
with type Union[int
,Snowflake
], defaults toNone
and is now a keyword-only parameter.- Parameters:
qualified_name (
str
) – Full name of the application command. Case sensitive. Subcommands must be separated by a space, E.g,parent group subcommand
.type (Union[
int
,ApplicationCommandType
]) – Type of application command. Defaults toApplicationCommandType.chat_input
.guild (Optional[Union[
int
,Snowflake
]]) – Guild ID of the signature. If set toNone
, it will attempt to get the global signature. Defaults toNone
.search_localizations (
bool
) –Whether to also search through the command’s
name_localizations
. Defaults toFalse
.New in version 3.0.
- Returns:
command – Application Command with the given signature. If no command with that signature is found,
None
is returned instead.- Return type:
Optional[
BaseApplicationCommand
,SlashApplicationSubcommand
]
- get_application_commands(rollout=False)¶
Gets registered global commands.
- Parameters:
rollout (
bool
) – Whether unregistered/unassociated commands should be returned as well. Defaults toFalse
- Returns:
List of
BaseApplicationCommand
objects that are global.- Return type:
List[
BaseApplicationCommand
]
- get_channel(id, /)¶
Returns a channel or thread 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
,Thread
,abc.PrivateChannel
]]
- get_cog(name)¶
Gets the cog instance requested.
If the cog is not found,
None
is returned instead.
- 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.
- await get_context(message, *, cls=<class 'nextcord.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 (
nextcord.Message
) – The message to get the invocation context from.cls – The factory class that will be used to create the context. By default, this is
Context
. Should a custom class be provided, it must be similar enough toContext
's interface.
- Returns:
The invocation context. The type of this can change via the
cls
parameter.- Return type:
- get_emoji(id, /)¶
Returns an emoji with the given ID.
- get_guild(id, /)¶
Returns a guild with the given ID.
- get_interaction(data, *, cls=<class 'nextcord.interactions.Interaction'>)¶
Returns an interaction for a gateway event.
- Parameters:
data – The data direct from the gateway.
cls – The factory class that will be used to create the interaction. By default, this is
Interaction
. Should a custom class be provided, it should be a subclass ofInteraction
.
- Returns:
Interaction – An instance
Interaction
or the provided subclass... note:: – This is synchronous due to how slash commands are implemented.
- get_partial_messageable(id, *, 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.type (Optional[
ChannelType
]) – The underlying channel type for the partial messageable.
- Returns:
The partial messageable
- Return type:
- 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 (
nextcord.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:
- get_scheduled_event(id, /)¶
Returns a scheduled event with the given ID.
New in version 2.0.
- Parameters:
id (
int
) – The scheduled event’s ID to search for.- Returns:
The scheduled event or
None
if not found.- Return type:
Optional[
ScheduledEvent
]
- 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 returns stage instance of
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.
- 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.
- 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.
- 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:
- load_extension(name, *, package=None, extras=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.
extras (Optional[
dict
]) –A mapping of kwargs to values to be passed to your cog’s
__init__
method as keyword arguments.Usage
# main.py bot.load_extension("cogs.me_cog", extras={"keyword_arg": True}) # cogs/me_cog.py class MeCog(commands.Cog): def __init__(self, bot, keyword_arg): self.bot = bot self.keyword_arg = keyword_arg def setup(bot, **kwargs): bot.add_cog(MeCog(bot, **kwargs)) # Alternately def setup(bot, keyword_arg): bot.add_cog(MeCog(bot, keyword_arg))
New in version 2.0.0.
- Raises:
ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided
package
parameter.ExtensionAlreadyLoaded – The extension is already loaded.
NoEntryPointError – The extension does not have a setup function.
ExtensionFailed – The extension or its setup function had an execution error.
InvalidSetupArguments –
load_extension
was givenextras
but thesetup
function did not take any additional arguments.
- load_extensions(names, *, package=None, packages=None, extras=None, stop_at_error=False)¶
Loads all extensions provided in a list.
Note
By default, any exceptions found while loading will not be raised but will be printed to console (standard error/
stderr
).New in version 2.1.
- Parameters:
names (List[
str
]) – The names of all of the extensions to load.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
.packages (Optional[List[
str
]]) –A list of package names to resolve relative imports with. This is required when loading an extension using a relative path, e.g
.foo.test
. Defaults toNone
.Usage:
# main.py bot.load_extensions( [ ".my_cog", ".my_cog_two", ], packages=[ "cogs.coolcog", "cogs.coolcogtwo", ], ) # cogs/coolcog/my_cog.py class MyCog(commands.Cog): def __init__(self, bot): self.bot = bot # ... def setup(bot): bot.add_cog(MyCog(bot)) # cogs/coolcogtwo/my_cog_two.py class MyCogTwo(commands.Cog): def __init__(self, bot): self.bot = bot # ... def setup(bot): bot.add_cog(MyCogTwo(bot))
extras (Optional[List[Dict[
str
, Any]]]) –A list of extra arguments to pass to the extension’s setup function.
Usage:
# main.py bot.load_extensions( [ ".my_cog", ".my_cog_two", ], package="cogs", extras=[{"my_attribute": 11}, {"my_other_attribute": 12}], ) # cogs/my_cog.py class MyCog(commands.Cog): def __init__(self, bot, my_attribute): self.bot = bot self.my_attribute = my_attribute # ... def setup(bot, **kwargs): bot.add_cog(MyCog(bot, **kwargs)) # cogs/my_cog_two.py class MyCogTwo(commands.Cog): def __init__(self, bot, my_other_attribute): self.bot = bot self.my_other_attribute = my_other_attribute # ... def setup(bot, my_other_attribute): bot.add_cog(MyCogTwo(bot, my_other_attribute))
stop_at_error (
bool
) – Whether or not an exception should be raised if we encounter one. Set toFalse
by default.
- Returns:
A list that contains the names of all of the extensions that loaded successfully.
- Return type:
List[
str
]- Raises:
ValueError – The length of
packages
or the length ofextras` is not equal to the length of ``names
.InvalidArgument – You passed in both
package
andpackages
.ExtensionNotFound – An extension could not be imported.
ExtensionAlreadyLoaded – An extension is already loaded.
NoEntryPointError – An extension does not have a setup function.
ExtensionFailed – An extension or its setup function had an execution error.
- load_extensions_from_module(source_module, *, ignore=None, stop_at_error=False)¶
Loads all extensions found in a module.
Once an extension found in a module has been loaded and did not throw any exceptions, it will be added to a list of extension names that will be returned.
Note
By default, any exceptions found while loading will not be raised but will be printed to console (standard error/
stderr
).New in version 2.1.
- Parameters:
- Returns:
A list that contains the names of all of the extensions that loaded successfully.
- Return type:
List[
str
]- Raises:
ValueError – The module at
source_module
is not found, or the module atsource_module
has no submodules.ExtensionNotFound – An extension could not be imported.
ExtensionAlreadyLoaded – An extension is already loaded.
NoEntryPointError – An extension does not have a setup function.
ExtensionFailed – An 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.
- 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.
- message_command(name=None, *, name_localizations=None, guild_ids=..., default_member_permissions=None, nsfw=False, integration_types=None, contexts=None, force_global=False)¶
Creates a Message context command from the decorated function.
- Parameters:
name (
str
) – Name of the command that users will see. If not set, it defaults to the name of the callback.name_localizations (Dict[Union[
Locale
,str
],str
]) – Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the valueguild_ids (Optional[Iterable[
int
]]) – IDs ofGuild
’s to add this command to. If not passed andClient.default_guild_ids
is set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command.default_member_permissions (Optional[Union[
Permissions
,int
]]) – Permission(s) required to use the command. Inputting8
orPermissions(administrator=True)
for example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by default. Server owners CAN override the permission requirements.nsfw (
bool
) –Whether the command can only be used in age-restricted channels. Defaults to
False
.New in version 2.4.
integration_types (Optional[Iterable[Union[
IntegrationType
,int
]]]) –Where the command is available, only for globally-scoped commands. Defaults to
guild_install
.New in version 3.0.
contexts (Optional[Iterable[Union[
InteractionContextType
,int
]]]) –Where the command can be used, only for globally-scoped commands. By default, all interaction context types included for new commands.
New in version 3.0.
force_global (
bool
) – If True, will force this command to register as a global command, even ifguild_ids
is set. Will still register to guilds. Has no effect ifguild_ids
are never set or added to.
- await on_application_command_error(interaction, exception)¶
This function is a coroutine.
The default application command error handler provided by the bot.
By default this prints to
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_command_error(context, exception)¶
This function is a coroutine.
The default command error handler provided by the bot.
By default this prints to
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
stderr
however it could be overridden to have a different implementation. Checkon_error()
for more details.
- parse_mentions(text)¶
Parses user mentions in a string and returns a list of
User
objects.Note
This does not include role or channel mentions. See
Guild.parse_mentions
forMember
objects,Guild.parse_role_mentions
forRole
objects, andGuild.parse_channel_mentions
forGuildChannel
objects.Note
Only cached users will be returned. To get the IDs of all users mentioned, use
parse_raw_mentions()
instead.New in version 2.2.
- 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_application_commands(interaction)¶
This function is a coroutine. Processes the data in the given interaction and calls associated applications or autocomplete if possible. Lazy-loads commands if enabled.
- Parameters:
interaction (
Interaction
) – Interaction from Discord to read data from.
- 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 to
get_context()
followed by a call toinvoke()
.This also checks if the message’s author is a bot and doesn’t call
get_context()
orinvoke()
if so.- Parameters:
message (
nextcord.Message
) – The message to process commands for.
- await process_with_str(message, content)¶
This function is a coroutine.
This function is like
process_commands()
except it processes the provided message with different content.This is useful if you want to execute multiple commands in a single message.
Example
@bot.event async def on_message(message): for msg in message.content.split(";"): await bot.process_with_str(message, msg)
- Parameters:
message (
nextcord.Message
) – The message to process commands for.content (
str
) – The content to subsitute for the message’s content.
- await register_application_commands(*commands, guild_id=None)¶
This function is a coroutine. Registers the given application commands either for a specific guild or globally, and adds the commands to the bot.
- Parameters:
commands (
BaseApplicationCommand
) – Application command to register. Multiple args are accepted.guild_id (Optional[
int
]) – ID of the guild to register the application commands to. If set toNone
, the commands will be registered as global commands instead. Defaults toNone
.
- await register_new_application_commands(data=None, guild_id=None)¶
This function is a coroutine. Registers locally added application commands that don’t match a signature that Discord has registered for either global commands or a specific guild.
- Parameters:
data (Optional[List[
dict
]]) – Data to use when comparing local application commands to what Discord has. Should be a list of application command data from Discord. If left asNone
, it will be fetched if needed. Defaults toNone
guild_id (Optional[
int
]) – ID of the guild to sync application commands with. If set toNone
, global commands will be synced instead. Defaults toNone
.
- reload_extension(name, *, package=None, extras=None)¶
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a
unload_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.
extras (Optional[
dict
]) –A mapping of kwargs to values to be passed to your cog’s
__init__
method as keyword arguments.Usage
# main.py bot.load_extension("cogs.me_cog", extras={"keyword_arg": False}) bot.reload_extension("cogs.me_cog", extras={"keyword_arg": True}) # cogs/me_cog.py class MeCog(commands.Cog): def __init__(self, bot, keyword_arg): self.bot = bot self.keyword_arg = keyword_arg def setup(bot, **kwargs): bot.add_cog(MeCog(bot, **kwargs)) # Alternately def setup(bot, keyword_arg): bot.add_cog(MeCog(bot, keyword_arg))
New in version v3.0.
- 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 provided
package
parameter.NoEntryPointError – The extension does not have a setup function.
ExtensionFailed – The extension setup function had an execution error.
InvalidSetupArguments –
reload_extension
was givenextras
but thesetup
function did not take any additional arguments.
- remove_application_command_check(func)¶
Removes a global application command check from the client.
This function is idempotent and will not raise an exception if the function is not in the global checks.
- Parameters:
func (Callable[[
Interaction
],MaybeCoro[bool]
]]) – The function to remove from the global application checks.
- 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 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.
- remove_command(name)¶
Remove a
Command
from the internal list of commands.This could also be used as a way to remove aliases.
- remove_listener(func, name=...)¶
Removes a listener from the pool of listeners.
New in version 3.0.
- Parameters:
func – The function that was used as a listener to remove.
name (
str
) – The name of the event we want to remove. Defaults tofunc.__name__
.
- remove_modal(modal)¶
Removes a
Modal
from persistent listening.This method should be used if a persistent modal is set in a cog and should be freed when the cog is unloaded to save memory.
New in version 2.3.
- Parameters:
modal (
nextcord.ui.Modal
) – The modal to remove from dispatching.- Raises:
TypeError – A modal was not passed.
ValueError – The modal is not persistent. A persistent modal has a set custom_id and all their components with a set custom_id and a timeout set to None.
- remove_view(view, message_id=None)¶
Removes a
View
from persistent listening or non-persistent storage.This method should be used if a persistent view is set in a cog and should be freed when the cog is unloaded to save memory or if you want to stop tracking a non-persistent view.
New in version 2.3.
Changed in version 2.6: Non-persistent views can now be removed from storage.
- Parameters:
view (
nextcord.ui.View
) – The view to remove from dispatching.message_id (Optional[
int
]) – The message ID that the view is attached to. This is used to properly remove the view from the view store. This cannot be provided if the view is non-persistent.
- Raises:
TypeError – A view was not passed.
ValueError – The message_id parameter was passed in with a non-persistent view.
- run(token, *, reconnect=True)¶
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use
start()
coroutine 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()
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.
- property scheduled_events¶
A list of scheduled events
New in version 2.0.
- Type:
List[ScheduledEvent]
- slash_command(name=None, description=None, *, name_localizations=None, description_localizations=None, guild_ids=..., nsfw=False, default_member_permissions=None, integration_types=None, contexts=None, force_global=False)¶
Creates a Slash application command from the decorated function.
- Parameters:
name (
str
) – Name of the command that users will see. If not set, it defaults to the name of the callback.description (
str
) – Description of the command that users will see. If not set, the docstring will be used. If no docstring is found for the command callback, it defaults to “No description provided”.name_localizations (Dict[Union[
Locale
,str
],str
]) – Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the value.description_localizations (Dict[Union[
Locale
,str
],str
]) – Description(s) of the command for users of specific locales. The locale code should be the key, with the localized description as the value.guild_ids (Optional[Iterable[
int
]]) – IDs ofGuild
’s to add this command to. If not passed andClient.default_guild_ids
is set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command.default_member_permissions (Optional[Union[
Permissions
,int
]]) – Permission(s) required to use the command. Inputting8
orPermissions(administrator=True)
for example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by default. Server owners CAN override the permission requirements.nsfw (
bool
) –Whether the command can only be used in age-restricted channels. Defaults to
False
.New in version 2.4.
integration_types (Optional[Iterable[Union[
IntegrationType
,int
]]]) –Where the command is available, only for globally-scoped commands. Defaults to
guild_install
.New in version 3.0.
contexts (Optional[Iterable[Union[
InteractionContextType
,int
]]]) –Where the command can be used, only for globally-scoped commands. By default, all interaction context types included for new commands.
New in version 3.0.
force_global (
bool
) – If True, will force this command to register as a global command, even ifguild_ids
is set. Will still register to guilds. Has no effect ifguild_ids
are never set or added to.
- 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.
New in version 2.0.
- Type:
List[
GuildSticker
]
- await sync_all_application_commands(data=None, *, use_rollout=True, associate_known=True, delete_unknown=True, update_known=True, register_new=True, ignore_forbidden=True)¶
This function is a coroutine.
Syncs all application commands with Discord. Will sync global commands if any commands added are global, and syncs with all guilds that have an application command targeting them.
This may call Discord many times depending on how different guilds you have local commands for, and how many commands Discord needs to be updated or added, which may cause your bot to be rate limited or even Cloudflare banned in VERY extreme cases.
This may incur high CPU usage depending on how many commands you have and how complex they are, which may cause your bot to halt while it checks local commands against the existing commands that Discord has.
For a more targeted version of this method, see
Client.sync_application_commands()
- Parameters:
data (Optional[Dict[Optional[
int
], List[dict
]]]) – Data to use when comparing local application commands to what Discord has. The key should be theint
guild ID (None for global) corresponding to the value list of application command payloads from Discord. Any guild ID’s not provided will be fetched if needed. Defaults toNone
use_rollout (
bool
) – If the rollout guild IDs of commands should be used. Defaults toTrue
associate_known (
bool
) – If local commands that match a command already on Discord should be associated with each other. Defaults toTrue
delete_unknown (
bool
) – If commands on Discord that don’t match a local command should be deleted. Defaults toTrue
update_known (
bool
) – If commands on Discord have a basic match with a local command, but don’t fully match, should be updated. Defaults toTrue
register_new (
bool
) – If a local command that doesn’t have a basic match on Discord should be added to Discord. Defaults toTrue
ignore_forbidden (
bool
) – If this command should suppress aerrors.Forbidden
exception when the bot encounters a guild where it doesn’t have permissions to view application commands. Defaults toTrue
- await sync_application_commands(data=None, *, guild_id=None, associate_known=True, delete_unknown=True, update_known=True, register_new=True)¶
This function is a coroutine. Syncs the locally added application commands with the Guild corresponding to the given ID, or syncs global commands if the guild_id is
None
.Changed in version 3.0: This replaces the now removed
delete_unknown_application_commands
,associate_application_commands
,update_application_commands
, androllout_application_commands
methods.- Parameters:
data (Optional[List[
dict
]]) – Data to use when comparing local application commands to what Discord has. Should be a list of application command data from Discord. If left asNone
, it will be fetched if needed. Defaults toNone
.guild_id (Optional[
int
]) – ID of the guild to sync application commands with. If set toNone
, global commands will be synced instead. Defaults toNone
.associate_known (
bool
) – If local commands that match a command already on Discord should be associated with each other. Defaults toTrue
.delete_unknown (
bool
) – If commands on Discord that don’t match a local command should be deleted. Defaults toTrue
.update_known (
bool
) – If commands on Discord have a basic match with a local command, but don’t fully match, should be updated. Defaults toTrue
.register_new (
bool
) – If a local command that doesn’t have a basic match on Discord should be added to Discord. Defaults toTrue
.
- 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
fromload_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 provided
package
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=None, guild_ids=..., default_member_permissions=None, nsfw=False, integration_types=None, contexts=None, force_global=False)¶
Creates a User context command from the decorated function.
- Parameters:
name (
str
) – Name of the command that users will see. If not set, it defaults to the name of the callback.name_localizations (Dict[Union[
Locale
,str
],str
]) – Name(s) of the command for users of specific locales. The locale code should be the key, with the localized name as the valueguild_ids (Optional[Iterable[
int
]]) – IDs ofGuild
’s to add this command to. If not passed andClient.default_guild_ids
is set, then those default guild ids will be used instead. If both of those are unset, then the command will be a global command.default_member_permissions (Optional[Union[
Permissions
,int
]]) – Permission(s) required to use the command. Inputting8
orPermissions(administrator=True)
for example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by default. Server owners CAN override the permission requirements.nsfw (
bool
) –Whether the command can only be used in age-restricted channels. Defaults to
False
.New in version 2.4.
integration_types (Optional[Iterable[Union[
IntegrationType
,int
]]]) –Where the command is available, only for globally-scoped commands. Defaults to
guild_install
.New in version 3.0.
contexts (Optional[Iterable[Union[
InteractionContextType
,int
]]]) –Where the command can be used, only for globally-scoped commands. By default, all interaction context types included for new commands.
New in version 3.0.
force_global (
bool
) – If True, will force this command to register as a global command, even ifguild_ids
is set. Will still register to guilds. Has no effect ifguild_ids
are never set or added to.
- views(*, persistent=True)¶
Returns all persistent or non-persistent views.
New in version 2.6.
- Parameters:
persistent (
bool
) – Whether or not we should grab persistent views. Defaults toTrue
.- Returns:
The views requested.
- Return type:
List[
ui.View
]
- 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 theasyncio.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('👍')
- 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 raisingasyncio.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
AutoShardedBot¶
- class nextcord.ext.commands.AutoShardedBot(command_prefix=(), help_command=..., description=None, *, max_messages=1000, connector=None, proxy=None, proxy_auth=None, shard_id=None, shard_count=None, shard_ids=None, application_id=None, intents=<Intents value=3243773>, member_cache_flags=..., chunk_guilds_at_startup=..., status=None, activity=None, allowed_mentions=None, heartbeat_timeout=60.0, guild_ready_timeout=2.0, assume_unsync_clock=True, enable_debug_events=False, loop=None, lazy_load_commands=True, rollout_associate_known=True, rollout_delete_unknown=True, rollout_register_new=True, rollout_update_known=True, rollout_all_guilds=False, default_guild_ids=None, owner_id=None, owner_ids=None, strip_after_prefix=False, case_insensitive=False)¶
This is similar to
Bot
except that it is inherited fromnextcord.AutoShardedClient
instead.
Prefix Helpers¶
- nextcord.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.
- nextcord.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
Event Reference¶
These events function similar to the regular events, except they are custom to the command extension module.
- nextcord.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.
Commands¶
Decorators¶
- @nextcord.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 ofinspect.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:
- Raises:
TypeError – If the function is not a coroutine or is already a command.
Command¶
- aliases
- brief
- callback
- checks
- clean_params
- cog
- cog_name
- cooldown_after_parsing
- description
- enabled
- extras
- full_parent_name
- help
- hidden
- ignore_extra
- inherit_hooks
- invoked_subcommand
- name
- parent
- parents
- qualified_name
- require_var_positional
- required_bot_guild_permissions
- required_bot_permissions
- required_guild_permissions
- required_permissions
- rest_is_raw
- root_parent
- short_doc
- signature
- usage
- 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 nextcord.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.
- 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:
- parent¶
The parent group that this command belongs to.
None
if there isn’t one.- Type:
Optional[
Group
]
- checks¶
A list of predicates that verifies if the command could be executed with the given
Context
as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited fromCommandError
should be used. Note that if the checks fail thenCheckFailure
exception is raised to theon_command_error()
event.
If
True
, the default help command does not show this in the help output.- Type:
- 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:
- 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:
- 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:
- 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:
- extras¶
A dict of user provided extras to attach to the Command.
Note
This object may be copied by the library.
New in version 2.0.
- Type:
- inherit_hooks¶
If
True
and this command has a parentGroup
then this command will inherit all checks, pre_invoke and after_invoke’s defined on the theGroup
This defaults toFalse
Note
Any
pre_invoke
orafter_invoke
’s defined on this will override parent ones.New in version 2.0.0.
- Type:
- @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.
- @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.
- @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.
- property required_permissions¶
Returns the permissions required to run this command.
Note
This returns the permissions set with
has_permissions()
.New in version 2.6.
- property required_bot_permissions¶
Returns the permissions the bot needs to run this command.
Note
This returns the permissions set with
bot_has_permissions()
.New in version 2.6.
- property required_guild_permissions¶
Returns the guild permissions needed to run this command.
Note
This returns the permissions set with
has_guild_permissions()
.New in version 2.6.
- property required_bot_guild_permissions¶
Returns the permissions the bot needs to have in this guild in order to run this command.
Note
This returns the permissions set with
bot_has_guild_permissions()
.New in version 2.6.
- 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__(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.
- copy()¶
Creates a copy of this command.
- Returns:
A new instance of this command.
- Return type:
- property clean_params¶
Dict[
str
,inspect.Parameter
]: Retrieves the parameter dictionary 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:
- 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 beone two three
.- Type:
- is_on_cooldown(ctx)¶
Checks whether the command is currently on cooldown.
- 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.
- has_error_handler()¶
bool
: Checks whether the command has an error handler registered.New in version 1.7.
- 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 thehelp
attribute is used instead.- Type:
- await can_run(ctx)¶
This function is a coroutine.
Checks if the command can be executed by checking all the predicates inside the
checks
attribute. This also checks whether the command is disabled.Changed in version 1.3: Checks whether the command is disabled or not
- 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:
Group¶
- 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 nextcord.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 is
False
, then the group callback will always be invoked first. This means that the checks and the parsing dictated by its parameters will be executed. Defaults toFalse
.- Type:
- case_insensitive¶
Indicates if the group’s commands should be case insensitive. Defaults to
False
.- Type:
- @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.
- @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.
- @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.
- @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
]
- 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()
orgroup()
shortcut decorators are used instead.Changed in version 1.4: Raise
CommandRegistrationError
instead of genericClientException
- await can_run(ctx)¶
This function is a coroutine.
Checks if the command can be executed by checking all the predicates inside the
checks
attribute. This also checks whether the command is disabled.Changed in version 1.3: Checks whether the command is disabled or not
- 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:
- property clean_params¶
Dict[
str
,inspect.Parameter
]: Retrieves the parameter dictionary 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:
- 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.
- get_cooldown_retry_after(ctx)¶
Retrieves the amount of seconds before this command can be tried again.
New in version 1.4.
- 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.
- 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 beone two three
.- Type:
- 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.
- property required_bot_guild_permissions¶
Returns the permissions the bot needs to have in this guild in order to run this command.
Note
This returns the permissions set with
bot_has_guild_permissions()
.New in version 2.6.
- property required_bot_permissions¶
Returns the permissions the bot needs to run this command.
Note
This returns the permissions set with
bot_has_permissions()
.New in version 2.6.
- property required_guild_permissions¶
Returns the guild permissions needed to run this command.
Note
This returns the permissions set with
has_guild_permissions()
.New in version 2.6.
- property required_permissions¶
Returns the permissions required to run this command.
Note
This returns the permissions set with
has_permissions()
.New in version 2.6.
- 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[
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 thehelp
attribute is used instead.- Type:
GroupMixin¶
- defadd_command
- @command
- defget_command
- @group
- defremove_command
- defwalk_commands
- class nextcord.ext.commands.GroupMixin(*args, case_insensitive=False, **kwargs)¶
A mixin that implements common functionality for classes that behave similar to
Group
and are allowed to register commands.- @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
]
- add_command(command)¶
Adds a
Command
into the internal list of commands.This is usually not called, instead the
command()
orgroup()
shortcut decorators are used instead.Changed in version 1.4: Raise
CommandRegistrationError
instead of genericClientException
- remove_command(name)¶
Remove a
Command
from the internal list of commands.This could also be used as a way to remove aliases.
- 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
Cogs¶
Cog¶
- clsCog.listener
- defbot_check
- defbot_check_once
- asynccog_after_invoke
- asynccog_before_invoke
- defcog_check
- asynccog_command_error
- defcog_unload
- defget_commands
- defget_listeners
- defhas_error_handler
- defwalk_commands
- class nextcord.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()¶
- for ... in walk_commands()¶
An iterator that recursively walks through this cog’s commands and subcommands.
- classmethod listener(name=...)¶
A decorator that marks a function as a listener.
This is the cog equivalent of
Bot.listen()
.
- 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
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.
Note
This is only called for prefix commands.
- 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.
CogMeta¶
- class nextcord.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 the
abc.ABCMeta
metaclass.For example, to create an abstract cog mixin class, the following would be done.
import abc class CogABCMeta(commands.CogMeta, abc.ABCMeta): pass class SomeMixin(metaclass=abc.ABCMeta): pass class SomeCogMixin(SomeMixin, commands.Cog, metaclass=CogABCMeta): pass
Note
When passing an attribute of a metaclass that is documented below, note that you must pass it as a keyword-only argument to the class creation like the following example:
class MyCog(commands.Cog, name='My Cog'): pass
- description¶
The cog description. By default, it is the cleaned docstring of the class.
New in version 1.6.
- Type:
- command_attrs¶
A list of attributes to apply to every command inside this cog. The dictionary is passed into the
Command
options at__init__
. If you specify attributes inside the command attribute in the class, it will override the one specified inside this attribute. For example:class MyCog(commands.Cog, command_attrs=dict(hidden=True)): @commands.command() async def foo(self, ctx): pass # hidden -> True @commands.command(hidden=False) async def bar(self, ctx): pass # hidden -> False
- Type:
Help Commands¶
HelpCommand¶
- 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 nextcord.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
]
Specifies if hidden commands should be shown in the output. Defaults to
False
.- Type:
- 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 the
Command
constructor.- Type:
- 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 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 the
Context.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:
- get_command_signature(command)¶
Retrieves the signature portion of the help page.
- 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:
- 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.
- 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:
- Returns:
The string to use when the command did not have the subcommand requested.
- Return type:
- 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.
- 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:
- 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 of
command_not_found()
will be passed here.You can override this method to customise the behaviour.
By default, this sends the error message to the destination specified by
get_destination()
.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 use
get_destination()
to know where to send, as this is a customisation point for other users.You can override this method to customise the behaviour.
Note
You can access the invocation context with
HelpCommand.context
.Also, the commands in the mapping are not filtered. To do the filtering you will have to call
filter_commands()
yourself.
- 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 use
get_destination()
to know where to send, as this is a customisation point for other users.You can override this method to customise the behaviour.
Note
You can access the invocation context with
HelpCommand.context
.To get the commands that belong to this cog see
Cog.get_commands()
. The commands returned not filtered. To do the filtering you will have to callfilter_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 use
get_destination()
to know where to send, as this is a customisation point for other users.You can override this method to customise the behaviour.
Note
You can access the invocation context with
HelpCommand.context
.To get the commands that belong to this group without aliases see
Group.commands
. The commands returned not filtered. To do the filtering you will have to 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 use
get_destination()
to know where to send, as this is a customisation point for other users.You can override this method to customise the behaviour.
Note
You can access the invocation context with
HelpCommand.context
.Showing Help
There are certain attributes and methods that are helpful for a help command to show such as the following:
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.
DefaultHelpCommand¶
- defadd_command_formatting
- defadd_indented_commands
- defget_destination
- defget_ending_note
- asyncsend_pages
- defshorten_text
- class nextcord.ext.commands.DefaultHelpCommand(*args, **kwargs)¶
The implementation of the default help command.
This inherits from
HelpCommand
.It extends it with the following attributes.
- sort_commands¶
Whether to sort the commands in the output alphabetically. Defaults to
True
.- Type:
- 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 if
dm_help
is set toNone
. Defaults to 1000.- Type:
Optional[
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:
- 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:
- 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.
- 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:
MinimalHelpCommand¶
- class nextcord.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:
- 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:
- aliases_heading¶
The alias list’s heading string used to list the aliases of the command. Useful for i18n. Defaults to
"Aliases:"
.- Type:
- 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 if
dm_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:
- 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:
- get_command_signature(command)¶
Retrieves the signature portion of the help page.
- 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:
- 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.
- 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:
Paginator¶
- class nextcord.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.
- linesep¶
- The character string inserted between lines. e.g. a newline character.
New in version 1.7.
- Type:
- 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:
- Raises:
RuntimeError – The line was too big for the current
max_size
.
- close_page()¶
Prematurely terminate a page.
Enums¶
- class nextcord.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¶
- @nextcord.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 a
Context
. 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 of
CommandError
. Any exception not subclassed from it will be propagated while those subclassed will be sent toon_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!')
- @nextcord.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!')
- @nextcord.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 return
False
.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
- @nextcord.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
nextcord.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.')
- @nextcord.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.
- @nextcord.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')
- @nextcord.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
- @nextcord.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
.
- @nextcord.ext.commands.bot_has_guild_permissions(**perms)¶
Similar to
has_guild_permissions()
, but checks the bot members guild permissions.New in version 1.3.
- @nextcord.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
- @nextcord.ext.commands.cooldown(rate, per, type=nextcord.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 of
type
which must be of enum typeBucketType
.If a cooldown is triggered, then
CommandOnCooldown
is triggered inon_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.
- @nextcord.ext.commands.dynamic_cooldown(cooldown, type=BucketType.default)¶
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 typenextcord.Message
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 of
type
which must be of enum typeBucketType
.If a cooldown is triggered, then
CommandOnCooldown
is triggered inon_command_error()
and the local error handler.A command can only have a single cooldown.
New in version 2.0.
- Parameters:
cooldown (Callable[[
nextcord.Message
], 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.
- @nextcord.ext.commands.max_concurrency(number, per=nextcord.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 raisesMaxConcurrencyReached
to its error handler. If this is set toTrue
then the command waits until it can be executed.
- @nextcord.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(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') bot.add_cog(What())
- @nextcord.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.
- @nextcord.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
.
- @nextcord.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.
- @nextcord.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
.
- @nextcord.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.
Cooldown¶
- defcopy
- defget_retry_after
- defget_tokens
- defreset
- defupdate_rate_limit
- class nextcord.ext.commands.Cooldown(rate, per)¶
Represents a cooldown for a command.
- get_tokens(current=None)¶
Returns the number of available tokens before rate limiting is applied.
- Parameters:
current (Optional[
float
]) – The time in seconds since Unix epoch to calculate tokens at. If not supplied thentime.time()
is used.- Returns:
The number of tokens available before the cooldown is to be applied.
- Return type:
- get_retry_after(current=None)¶
Returns the time in seconds until the cooldown will be reset.
- Parameters:
current (Optional[
float
]) – The current time in seconds since Unix epoch. If not supplied, thentime.time()
is used.- Returns:
The number of seconds to wait before this cooldown will be reset.
- Return type:
- update_rate_limit(current=None)¶
Updates the cooldown rate limit.
- Parameters:
current (Optional[
float
]) – The time in seconds since Unix epoch to update the rate limit at. If not supplied, thentime.time()
is used.- Returns:
The retry-after time in seconds if rate limited.
- Return type:
Optional[
float
]
- reset()¶
Reset the cooldown to its initial state.
Context¶
- asyncfetch_message
- asyncforward
- defhistory
- asyncinvoke
- asyncreinvoke
- asyncreply
- asyncsend
- asyncsend_help
- asynctrigger_typing
- deftyping
- class nextcord.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)¶
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.- args¶
The list of transformed arguments that were passed into the command. If this is accessed during the
on_command_error()
event then this list could be incomplete.- Type:
- kwargs¶
A dictionary of transformed arguments that were passed into the command. Similar to
args
, if this is accessed in theon_command_error()
event then this dict could be incomplete.- Type:
- 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[
inspect.Parameter
]
- 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 to
None
.- 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 to
None
.- Type:
Optional[
str
]
- command_failed¶
A boolean that indicates if the command failed to be parsed, checked, or invoked.
- Type:
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
This function returns an async iterator.
Returns an async iterator 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
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
ifafter
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 both
with
andasync with
work with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send('done!')
- 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.
- 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:
- Raises:
ValueError – The context to reinvoke is not valid.
- property clean_prefix¶
The cleaned up invoke prefix. i.e. mentions are
@name
instead of<@id>
.New in version 2.0.
- Type:
- 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 for
Message.channel
.- Type:
Union[
abc.Messageable
]
- author¶
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 to
command_not_found()
this returnsNone
on bad input or no help command.
- await reply(content=None, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.send()
to reply to theMessage
.New in version 1.6.
- 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:
- 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:
- await forward(message)¶
Forward a message to this channel.
- Parameters:
message (
Message
) – The message to forward.note:: (..) – It is not possible to forward messages through interactions. It is only possible to forward a message to a channel as a message.
- Raises:
HTTPException – Forwarding/sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
.. versionadded: – 3.0:
- 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, flags=None, suppress_embeds=None)¶
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
orembeds
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. Specifying both parameters will lead to an exception.To upload a single embed, the
embed
parameter should be used with a singleEmbed
object. To upload multiple embeds, theembeds
parameter should be used with alist
ofEmbed
objects. Specifying both parameters will lead to an exception.- 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 (Union[
int
,str
]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set 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 usingto_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.
view (
nextcord.ui.View
) – A Discord UI View to add to the message.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.
New in version 2.0.
flags (Optional[
MessageFlags
]) –The message flags being set for this message. Currently only
suppress_embeds
is able to be set.New in version 2.4.
suppress_embeds (Optional[
bool
]) –Whether to suppress embeds on this message.
New in version 2.4.
- 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 you specified bothembed
andembeds
, or thereference
object is not aMessage
,MessageReference
orPartialMessage
- Returns:
The message that was sent.
- Return type:
Converters¶
- class nextcord.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 cased
discord
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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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 if
MemberCacheFlags.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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.ext.commands.MessageConverter(*args, **kwargs)¶
Converts to a
nextcord.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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.ext.commands.PartialMessageConverter(*args, **kwargs)¶
Converts to a
nextcord.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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.ext.commands.GameConverter(*args, **kwargs)¶
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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.ext.commands.PartialEmojiConverter(*args, **kwargs)¶
Converts to a
PartialEmoji
.This is done by extracting the animated flag, name and ID from the emoji.
If the emoji is a unicode emoji, then the name is the unicode character.
Changed in version 1.5: Raise
PartialEmojiConversionFailure
instead of genericBadArgument
Changed in version 2.1: Add support for converting unicode emojis
- 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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.ext.commands.ThreadConverter(*args, **kwargs)¶
Coverts 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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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):
1. Lookup by ID. 3. 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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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
.- remove_markdown¶
Whether to also remove special markdown characters. This option is not supported with
escape_markdown
New in version 1.7.
- Type:
- 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 a
CommandError
derived exception as it will properly propagate to the error handlers.
- class nextcord.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.
- await nextcord.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 (
inspect.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 nextcord.ext.commands.FlagConverter¶
A converter that allows for a user-friendly flag syntax.
The flags are defined using PEP 526 type annotations similar to the
dataclasses
Python module. For more information on how this converter works, check the appropriate documentation.- 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 await convert(ctx, argument)¶
This function is a coroutine.
The method that actually converters an argument to the flag mapping.
- Parameters:
cls (Type[
FlagConverter
]) – The flag converter class.ctx (
Context
) – The invocation context.argument (
str
) – The argument to convert from.
- Raises:
FlagError – A flag related parsing error.
CommandError – A command related error.
- Returns:
The flag converter instance with all flags parsed.
- Return type:
- class nextcord.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.- 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:
- nextcord.ext.commands.flag(*, name=..., aliases=..., default=..., max_args=..., override=...)¶
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.
Warnings¶
- class nextcord.ext.commands.MissingMessageContentIntentWarning¶
Warning category raised when instantiating a
Bot
with acommand_prefix
but without themessage_content
intent enabled.This warning is not raised when the
command_prefix
is set to an empty iterable orwhen_mentioned
.This warning can be silenced using
warnings.simplefilter()
.import warnings from nextcord.ext import commands warnings.simplefilter("ignore", commands.MissingMessageContentIntentWarning)
Exceptions¶
- exception nextcord.ext.commands.CommandError(message=None, *args)¶
The base exception type for all command related errors.
This inherits from
nextcord.DiscordException
.This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from
Bot
,on_command_error()
.
- exception nextcord.ext.commands.ConversionError(converter, original)¶
Exception raised when a Converter class raises non-CommandError.
This inherits from
CommandError
.- converter¶
The converter that failed.
- exception nextcord.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:
- exception nextcord.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 nextcord.ext.commands.UnexpectedQuoteError(quote)¶
An exception raised when the parser encounters a quote mark inside a non-quoted string.
This inherits from
ArgumentParsingError
.
- exception nextcord.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
.
- exception nextcord.ext.commands.ExpectedClosingQuoteError(close_quote)¶
An exception raised when a quote character is expected but not found.
This inherits from
ArgumentParsingError
.
- exception nextcord.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 nextcord.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:
- 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 nextcord.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:
- 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 nextcord.ext.commands.PrivateMessageOnly(message=None)¶
Exception raised when an operation does not work outside of private message contexts.
This inherits from
CheckFailure
- exception nextcord.ext.commands.NoPrivateMessage(message=None)¶
Exception raised when an operation does not work in private message contexts.
This inherits from
CheckFailure
- exception nextcord.ext.commands.CheckFailure(message=None, *args)¶
Exception raised when the predicates in
Command.checks
have failed.This inherits from
CommandError
- exception nextcord.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
]
- exception nextcord.ext.commands.CommandNotFound(command_name)¶
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
.Changed in version 2.1: Added
command_name
as a parameter.
- exception nextcord.ext.commands.DisabledCommand(message=None, *args)¶
Exception raised when the command being invoked is disabled.
This inherits from
CommandError
- exception nextcord.ext.commands.CommandInvokeError(e)¶
Exception raised when the command being invoked raised an exception.
This inherits from
CommandError
- exception nextcord.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 nextcord.ext.commands.UserInputError(message=None, *args)¶
The base exception type for errors that involve errors regarding user input.
This inherits from
CommandError
.
- exception nextcord.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 thecooldown()
decorator.- Type:
- type¶
The type associated with the cooldown.
- Type:
- exception nextcord.ext.commands.MaxConcurrencyReached(number, per)¶
Exception raised when the command being invoked has reached its maximum concurrency.
This inherits from
CommandError
.- per¶
The bucket type passed to the
max_concurrency()
decorator.- Type:
- exception nextcord.ext.commands.NotOwner(message=None, *args)¶
Exception raised when the message author is not the owner of the bot.
This inherits from
CheckFailure
- exception nextcord.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.
- exception nextcord.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.
- exception nextcord.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.
- exception nextcord.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.
- exception nextcord.ext.commands.ChannelNotFound(argument)¶
Exception raised when the bot can not find the channel.
This inherits from
BadArgument
New in version 1.5.
- exception nextcord.ext.commands.ScheduledEventNotFound(argument)¶
Exception raised when the bot can not find the scheduled event.
This inherits from
BadArgument
New in version 2.0.
- exception nextcord.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 nextcord.ext.commands.ThreadNotFound(argument)¶
Exception raised when the bot can not find the thread.
This inherits from
BadArgument
New in version 2.0.
- exception nextcord.ext.commands.BadColourArgument(argument)¶
Exception raised when the colour is not valid.
This inherits from
BadArgument
New in version 1.5.
- exception nextcord.ext.commands.RoleNotFound(argument)¶
Exception raised when the bot can not find the role.
This inherits from
BadArgument
New in version 1.5.
- exception nextcord.ext.commands.BadInviteArgument(argument)¶
Exception raised when the invite is invalid or expired.
This inherits from
BadArgument
New in version 1.5.
- exception nextcord.ext.commands.EmojiNotFound(argument)¶
Exception raised when the bot can not find the emoji.
This inherits from
BadArgument
New in version 1.5.
- exception nextcord.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.
- exception nextcord.ext.commands.GuildStickerNotFound(argument)¶
Exception raised when the bot can not find the sticker.
This inherits from
BadArgument
New in version 2.0.
- exception nextcord.ext.commands.BadBoolArgument(argument)¶
Exception raised when a boolean argument was not convertable.
This inherits from
BadArgument
New in version 1.5.
- exception nextcord.ext.commands.MissingPermissions(missing_permissions, *args)¶
Exception raised when the command invoker lacks permissions to run a command.
This inherits from
CheckFailure
- exception nextcord.ext.commands.BotMissingPermissions(missing_permissions, *args)¶
Exception raised when the bot’s member lacks permissions to run a command.
This inherits from
CheckFailure
- exception nextcord.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 to
has_role()
.
- exception nextcord.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 to
has_role()
.
- exception nextcord.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 to
has_any_role()
.
- exception nextcord.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 to
has_any_role()
.
- exception nextcord.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 (Union[
abc.GuildChannel
,Thread
]) – The channel that does not have NSFW enabled.
- exception nextcord.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 nextcord.ext.commands.BadFlagArgument(flag)¶
An exception raised when a flag failed to convert a value.
This inherits from
FlagError
New in version 2.0.
- exception nextcord.ext.commands.MissingFlagArgument(flag)¶
An exception raised when a flag did not get a value.
This inherits from
FlagError
New in version 2.0.
- exception nextcord.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.
- exception nextcord.ext.commands.MissingRequiredFlag(flag)¶
An exception raised when a required flag was not given.
This inherits from
FlagError
New in version 2.0.
- exception nextcord.ext.commands.ExtensionError(message=None, *args, name)¶
Base exception for extension related errors.
This inherits from
DiscordException
.
- exception nextcord.ext.commands.ExtensionAlreadyLoaded(name)¶
An exception raised when an extension has already been loaded.
This inherits from
ExtensionError
- exception nextcord.ext.commands.ExtensionNotLoaded(name)¶
An exception raised when an extension was not loaded.
This inherits from
ExtensionError
- exception nextcord.ext.commands.NoEntryPointError(name)¶
An exception raised when an extension does not have a
setup
entry point function.This inherits from
ExtensionError
- exception nextcord.ext.commands.InvalidSetupArguments(name)¶
- An exception raised when an extension contains a
setup
function which does except
kwargs
butkwargs
were passed.
This inherits from
ExtensionError
- An exception raised when an extension contains a
- exception nextcord.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
- exception nextcord.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.
- exception nextcord.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
nextcord.ClientException
New in version 1.4.