API Reference¶
The following section outlines the API of ndiscord.py’s application extension module.
Core Functions¶
ApplicationCommand¶
- defadd_check
- @after_invoke
- @before_invoke
- asynccan_run
- defcopy
- @error
- defhas_error_handler
- asyncinvoke
- asyncreinvoke
- defremove_check
- defto_dict
- class discord.ext.app.ApplicationCommand(*args, **kwargs)¶
A class that implements the protocol for bot application command.
These should not be created manually, instead please use the provided decorator or function interface.
- id¶
The ID of the command, can be None if the command has not been registered yet.
- Type
Optional[
int
]
- checks¶
A list of predicates that verifies if the command could be executed with the given
ApplicationContext
as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited fromApplicationCommandError
should be used. Note that if the checks fail thenApplicationCheckFailure
exception is raised to theon_application_error()
event.- Type
List[Callable[[
ApplicationContext
],bool
]]
- type¶
The type of application command.
- Type
ApplicationCommandType
- @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
ApplicationContext
.
- @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
ApplicationContext
.
- @error¶
A decorator that registers a coroutine as a local error handler.
A local error handler is an
on_application_error()
event limited to a single command. However, theon_application_error()
is still invoked afterwards as the catch-all.
- add_check(func)¶
Adds a check to the command.
This is the non-decorator interface to
check()
.- Parameters
func – The function that will be used as a check.
- remove_check(func)¶
Removes a check from the command.
This function is idempotent and will not raise an exception if the function is not in the command’s checks.
- Parameters
func – The function to remove from the checks.
- property cog_name: Optional[str]¶
The name of the cog this command belongs to, if any.
- Type
Optional[
str
]
- await invoke(ctx)¶
This function is a coroutine.
Execute or invoke the function callback of the app command.
- Parameters
ctx (
ApplicationContext
) – The invocation context.- Raises
ApplicationCommandInvokeError – An error occurred while invoking the command.
ApplicationTooManyArguments – The number of arguments passed to the command was more than allowed.
ApplicationMissingRequiredArgument – The command failed because it was missing a required argument.
ApplicationBadArgument – The command failed because one of the arguments passed to it was invalid.
ApplicationMemberNotFound – The member data being passed does not exist in cache.
ApplicationUserNotFound – The user data being passed does not exist in cache.
ApplicationMentionableNotFound – The mentionable data being passed does not exist in cache.
ApplicationCommandOnCooldown – The command you’re trying to execute is on cooldown.
ApplicationMaxConcurrencyReached – The maximum concurrency limit for this command has been reached.
- await reinvoke(ctx, *, call_hooks=False)¶
This function is a coroutine.
Execute again or reinvoke the function callback of the app command. This will perform a similar action to
Bot.invoke()
except you can set if you want to invoke hooks or not.This will also bypass the concurrency checks and cooldown check.
- Parameters
ctx (
ApplicationContext
) – The invocation context.call_hooks (
bool
) – Should we call the before_hooks and after_hooks or not.
- Raises
ApplicationCommandInvokeError – An error occurred while invoking the command.
- copy()¶
Creates a copy of this app command.
- Returns
A new instance of this app command.
- Return 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.- Parameters
ctx (
ApplicationContext
) – 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
SlashCommand¶
- defadd_check
- defadd_command
- @after_invoke
- @before_invoke
- asynccan_run
- @command
- defcopy
- @error
- @group
- defhas_error_handler
- defhas_parent
- asyncinvoke
- asyncreinvoke
- defremove_check
- defto_dict
- defwalk_commands
- class discord.ext.app.SlashCommand(*args, **kwargs)¶
A class that implements an application command that can be invoked through a via Discord /slash command.
These should not be created manually, instead please use the provided decorator or function interface.
- id¶
The ID of the command, can be None if the command has not been registered yet.
- Type
Optional[
int
]
- checks¶
A list of predicates that verifies if the command could be executed with the given
ApplicationContext
as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited fromApplicationCommandError
should be used. Note that if the checks fail thenApplicationCheckFailure
exception is raised to theon_application_error()
event.- Type
List[Callable[[
ApplicationContext
],bool
]]
- parent¶
The parent command of this one if there is one. Usually used for the child of a subcommand or subcommand group.
- Type
Optional[
SlashCommand
]
- type¶
The type of application command.
- Type
ApplicationCommandType
- sub_type¶
The type of the slash command, can only be
SlashCommandOptionType.sub_command
orSlashCommandOptionType.sub_command_group
.- Type
SlashCommandOptionType
- params¶
A ordered dictionary of parameters that the command callback takes. This also includes the
self
parameter, which is the first parameter if you have cogs attached. Andctx
which can be the first/second argument.
- @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
ApplicationContext
.
- @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
ApplicationContext
.
- @error¶
A decorator that registers a coroutine as a local error handler.
A local error handler is an
on_application_error()
event limited to a single command. However, theon_application_error()
is still invoked afterwards as the catch-all.
- @command¶
A decorator that would add a new subcommand to the parent command.
- Returns
A decorator that converts the provided method into a
SlashCommand
, adds it to the bot, then returns it.- Return type
Callable[…,
SlashCommand
]
- @group¶
A decorator that would add a new subcommand group to the parent command.
- Returns
A decorator that converts the provided method into a
SlashCommand
, adds it to the bot, then returns it.- Return type
Callable[…,
SlashCommand
]
- property children¶
A list of children
- Type
Dict[
str
,SlashCommand
]
- await invoke(ctx)¶
This function is a coroutine.
Execute or invoke the function callback of the app command.
- Parameters
ctx (
ApplicationContext
) – The invocation context.- Raises
ApplicationCommandInvokeError – An error occurred while invoking the command.
ApplicationTooManyArguments – The number of arguments passed to the command was more than allowed.
ApplicationMissingRequiredArgument – The command failed because it was missing a required argument.
ApplicationBadArgument – The command failed because one of the arguments passed to it was invalid.
ApplicationMemberNotFound – The member data being passed does not exist in cache.
ApplicationUserNotFound – The user data being passed does not exist in cache.
ApplicationMentionableNotFound – The mentionable data being passed does not exist in cache.
ApplicationCommandOnCooldown – The command you’re trying to execute is on cooldown.
ApplicationMaxConcurrencyReached – The maximum concurrency limit for this command has been reached.
- add_command(command)¶
Adds a
SlashCommand
into the internal list of commands.This is usually not called, instead the
command()
orgroup()
shortcut decorators are used instead.- Parameters
command (
Command
) – The command to add.- Raises
ApplicationRegistrationError – If the command or its alias is already registered by different command.
ApplicationRegistrationMaxDepthError – If the command parent already reach the maximum depth of 2 nested child.
ApplicationRegistrationExistingParentOptions – If the parent command contains options other than
sub_command
orsub_command_group
.TypeError – If the command passed is not a subclass of
SlashCommand
.
- property commands: Set[discord.ext.app.core.SlashCommand[discord.ext.app._types.CogT, discord.ext.app._types.BotT]]¶
A unique set of commands without aliases that are registered.
- Type
Set[
SlashCommand
]
- for ... in walk_commands()¶
An iterator that recursively walks through all commands and subcommands.
- Yields
SlashCommand
– A command or group from the internal list of commands.
- add_check(func)¶
Adds a check to the command.
This is the non-decorator interface to
check()
.- Parameters
func – The function that will be used as a check.
- 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.- Parameters
ctx (
ApplicationContext
) – 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 cog_name: Optional[str]¶
The name of the cog this command belongs to, if any.
- Type
Optional[
str
]
- copy()¶
Creates a copy of this app command.
- Returns
A new instance of this app command.
- Return type
- await reinvoke(ctx, *, call_hooks=False)¶
This function is a coroutine.
Execute again or reinvoke the function callback of the app command. This will perform a similar action to
Bot.invoke()
except you can set if you want to invoke hooks or not.This will also bypass the concurrency checks and cooldown check.
- Parameters
ctx (
ApplicationContext
) – The invocation context.call_hooks (
bool
) – Should we call the before_hooks and after_hooks or not.
- Raises
ApplicationCommandInvokeError – An error occurred while invoking the command.
- remove_check(func)¶
Removes a check from the command.
This function is idempotent and will not raise an exception if the function is not in the command’s checks.
- Parameters
func – The function to remove from the checks.
UserCommand¶
- defadd_check
- @after_invoke
- @before_invoke
- asynccan_run
- defcopy
- @error
- defhas_error_handler
- asyncinvoke
- asyncreinvoke
- defremove_check
- defto_dict
- defwalk_commands
- class discord.ext.app.UserCommand(*args, **kwargs)¶
A class that implements the context menu application. This will be used to implement user command where someone can right click someone username to execute an application command.
This class will pass Union[
User
,Member
] to the callback.These should not be created manually, instead please use the provided decorator or function interface.
- id¶
The ID of the command, can be None if the command has not been registered yet.
- Type
Optional[
int
]
- checks¶
A list of predicates that verifies if the command could be executed with the given
ApplicationContext
as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited fromApplicationCommandError
should be used. Note that if the checks fail thenApplicationCheckFailure
exception is raised to theon_application_error()
event.- Type
List[Callable[[
ApplicationContext
],bool
]]
- type¶
The type of application command.
- Type
ApplicationCommandType
- params¶
A ordered dictionary of parameters that the command callback takes. This also includes the
self
parameter, which is the first parameter if you have cogs attached. Andctx
which can be the first/second argument.
- @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
ApplicationContext
.
- @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
ApplicationContext
.
- @error¶
A decorator that registers a coroutine as a local error handler.
A local error handler is an
on_application_error()
event limited to a single command. However, theon_application_error()
is still invoked afterwards as the catch-all.
- add_check(func)¶
Adds a check to the command.
This is the non-decorator interface to
check()
.- Parameters
func – The function that will be used as a check.
- 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.- Parameters
ctx (
ApplicationContext
) – 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 cog_name: Optional[str]¶
The name of the cog this command belongs to, if any.
- Type
Optional[
str
]
- copy()¶
Creates a copy of this app command.
- Returns
A new instance of this app command.
- Return type
- await invoke(ctx)¶
This function is a coroutine.
Execute or invoke the function callback of the app command.
- Parameters
ctx (
ApplicationContext
) – The invocation context.- Raises
ApplicationCommandInvokeError – An error occurred while invoking the command.
ApplicationTooManyArguments – The number of arguments passed to the command was more than allowed.
ApplicationMissingRequiredArgument – The command failed because it was missing a required argument.
ApplicationBadArgument – The command failed because one of the arguments passed to it was invalid.
ApplicationMemberNotFound – The member data being passed does not exist in cache.
ApplicationUserNotFound – The user data being passed does not exist in cache.
ApplicationMentionableNotFound – The mentionable data being passed does not exist in cache.
ApplicationCommandOnCooldown – The command you’re trying to execute is on cooldown.
ApplicationMaxConcurrencyReached – The maximum concurrency limit for this command has been reached.
- await reinvoke(ctx, *, call_hooks=False)¶
This function is a coroutine.
Execute again or reinvoke the function callback of the app command. This will perform a similar action to
Bot.invoke()
except you can set if you want to invoke hooks or not.This will also bypass the concurrency checks and cooldown check.
- Parameters
ctx (
ApplicationContext
) – The invocation context.call_hooks (
bool
) – Should we call the before_hooks and after_hooks or not.
- Raises
ApplicationCommandInvokeError – An error occurred while invoking the command.
- remove_check(func)¶
Removes a check from the command.
This function is idempotent and will not raise an exception if the function is not in the command’s checks.
- Parameters
func – The function to remove from the checks.
- for ... in walk_commands()¶
An iterator that recursively walks through all commands and subcommands.
- Yields
ContextMenuApplication
– A command or group from the internal list of commands.
MessageCommand¶
- defadd_check
- @after_invoke
- @before_invoke
- asynccan_run
- defcopy
- @error
- defhas_error_handler
- asyncinvoke
- asyncreinvoke
- defremove_check
- defto_dict
- defwalk_commands
- class discord.ext.app.MessageCommand(*args, **kwargs)¶
A class that implements the context menu application. This will be used to implement message command where someone can right click someone message to execute an application command.
This class will pass
Message
to the callback.These should not be created manually, instead please use the provided decorator or function interface.
- id¶
The ID of the command, can be None if the command has not been registered yet.
- Type
Optional[
int
]
- checks¶
A list of predicates that verifies if the command could be executed with the given
ApplicationContext
as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited fromApplicationCommandError
should be used. Note that if the checks fail thenApplicationCheckFailure
exception is raised to theon_application_error()
event.- Type
List[Callable[[
ApplicationContext
],bool
]]
- type¶
The type of application command.
- Type
ApplicationCommandType
- params¶
A ordered dictionary of parameters that the command callback takes. This also includes the
self
parameter, which is the first parameter if you have cogs attached. Andctx
which can be the first/second argument.
- @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
ApplicationContext
.
- @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
ApplicationContext
.
- @error¶
A decorator that registers a coroutine as a local error handler.
A local error handler is an
on_application_error()
event limited to a single command. However, theon_application_error()
is still invoked afterwards as the catch-all.
- add_check(func)¶
Adds a check to the command.
This is the non-decorator interface to
check()
.- Parameters
func – The function that will be used as a check.
- 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.- Parameters
ctx (
ApplicationContext
) – 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 cog_name: Optional[str]¶
The name of the cog this command belongs to, if any.
- Type
Optional[
str
]
- copy()¶
Creates a copy of this app command.
- Returns
A new instance of this app command.
- Return type
- await invoke(ctx)¶
This function is a coroutine.
Execute or invoke the function callback of the app command.
- Parameters
ctx (
ApplicationContext
) – The invocation context.- Raises
ApplicationCommandInvokeError – An error occurred while invoking the command.
ApplicationTooManyArguments – The number of arguments passed to the command was more than allowed.
ApplicationMissingRequiredArgument – The command failed because it was missing a required argument.
ApplicationBadArgument – The command failed because one of the arguments passed to it was invalid.
ApplicationMemberNotFound – The member data being passed does not exist in cache.
ApplicationUserNotFound – The user data being passed does not exist in cache.
ApplicationMentionableNotFound – The mentionable data being passed does not exist in cache.
ApplicationCommandOnCooldown – The command you’re trying to execute is on cooldown.
ApplicationMaxConcurrencyReached – The maximum concurrency limit for this command has been reached.
- await reinvoke(ctx, *, call_hooks=False)¶
This function is a coroutine.
Execute again or reinvoke the function callback of the app command. This will perform a similar action to
Bot.invoke()
except you can set if you want to invoke hooks or not.This will also bypass the concurrency checks and cooldown check.
- Parameters
ctx (
ApplicationContext
) – The invocation context.call_hooks (
bool
) – Should we call the before_hooks and after_hooks or not.
- Raises
ApplicationCommandInvokeError – An error occurred while invoking the command.
- remove_check(func)¶
Removes a check from the command.
This function is idempotent and will not raise an exception if the function is not in the command’s checks.
- Parameters
func – The function to remove from the checks.
- for ... in walk_commands()¶
An iterator that recursively walks through all commands and subcommands.
- Yields
ContextMenuApplication
– A command or group from the internal list of commands.
Options¶
- class discord.ext.app.Option(input_type, /, description=None, **kwargs)¶
A class that implement a single option for an
SlashCommand
.These can be used as type-hints for your arguments or created by decorator.
- input_type¶
The type of the argument.
- default¶
The default value of the argument.
- Type
Optional[
Any
]
- choices¶
A list of valid options for the argument.
- Type
List[
OptionChoice
]
- channel_types¶
A list of channel types that the option is valid for. If provided, the user can only use the defined channel type for the option.
- Type
Optional[List[
ChannelType
]]
- min_value¶
The minimum value of the number option, the
input_type
must beSlashCommandOptionType.number
orSlashCommandOptionType.integer
.- Type
Optional[
int
]
- max_value¶
The maximum value of the number option, the
input_type
must beSlashCommandOptionType.number
orSlashCommandOptionType.integer
.- Type
Optional[
int
]
Decorators¶
This is all available decorators that user can use to create application command.
- @discord.ext.app.application_command(cls=<class 'discord.ext.app.core.SlashCommand'>, **attrs)¶
A decorator that transforms a function into an
ApplicationCommand
. More specifically, usually one ofSlashCommand
,UserCommand
, orMessageCommand
. The exact class depends on thecls
parameter.By default the
description
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.The
name
attribute also defaults to the function name unchanged.New in version 2.0.
- Parameters
cls (
ApplicationCommand
) – The class to construct with. By default this isSlashCommand
. You usually do not change this.attrs – Keyword arguments to pass into the construction of the class denoted by
cls
.
- Raises
TypeError – If the function is not a coroutine or is already a command.
- @discord.ext.app.slash_command(**kwargs)¶
Decorator for slash commands that invokes
application_command()
.New in version 2.0.
- Parameters
name (Optional[
str
]) – The name of the command. Defaults to the name of the method.description (Optional[
str
]) – A short description of the command.guild_ids (Optional[List[
int
]]) – Guild IDs where the command can be run on. Setting this will make the command only usable from this guild.checks (Optional[List[Callable[[
ApplicationContext
],bool
]]]) – A list of predicates that must be true for the command to be invoked.
- Returns
A decorator that converts the provided method into a
SlashCommand
.- Return type
Callable[…,
SlashCommand
]
- @discord.ext.app.user_command(**kwargs)¶
Decorator for user commands that invokes
application_command()
.New in version 2.0.
- Parameters
name (Optional[
str
]) – The name of the command. Defaults to the name of the method.guild_ids (Optional[List[
int
]]) – Guild IDs where the command can be run on. Setting this will make the command only usable from this guild.checks (Optional[List[Callable[[
ApplicationContext
],bool
]]]) – A list of predicates that must be true for the command to be invoked.
- Returns
A decorator that converts the provided method into a
UserCommand
.- Return type
Callable[…,
UserCommand
]
- @discord.ext.app.message_command(**kwargs)¶
Decorator for message commands that invokes
application_command()
.New in version 2.0.
- Parameters
name (Optional[
str
]) – The name of the command. Defaults to the name of the method.guild_ids (Optional[List[
int
]]) – Guild IDs where the command can be run on. Setting this will make the command only usable from this guild.checks (Optional[List[Callable[[
ApplicationContext
],bool
]]]) – A list of predicates that must be true for the command to be invoked.
- Returns
A decorator that converts the provided method into a
MessageCommand
.- Return type
Callable[…,
MessageCommand
]
- @discord.ext.app.command(**kwargs)¶
This is an alias for
application_command()
.New in version 2.0.
- Returns
A decorator that converts the provided method into an
ApplicationCommand
.- Return type
Callable[…,
ApplicationCommand
]
- @discord.ext.app.option(name, type=None, **kwargs)¶
A decorator that can be used instead of typehinting
Option
- Parameters
name (
str
) – The name of the option in the arguments.type (Optional[Union[Type[Union[
str
,int
,float
,bool
]],int
,Snowflake
,GuildChannel
,Member
,Role
,Mentionable
]]) – The type of the option, default to string if not defined. You can pass something likestr
and it will automatically converted to proper type. You can also give a number and it will try to find that enum.description (
str
) – The description of the option.required (
bool
) – Whether the option is required or not.choices (List[Union[
OptionChoice
,str
]]) – A list of valid choices for the option.default (Optional[Any]) – The default value of the option.
channel_types (Optional[List[
ChannelType
]]) – A list of channel types that the option is valid for. If provided, the user can only use the defined channel type for the option.autocomplete (Optional[
bool
]) –Indicates if the argument should be autocompleted.
Warning
choices
cannot be present if this isTrue
. And it also only works forSlashCommandOptionType.string
only.
Mixins¶
This is information for Mixins created to help load applications into the Bot or Client.
Warning
You should not create all of this mixins manually if you don’t know what you’re doing.
ApplicationCommandMixin¶
- class discord.ext.app.ApplicationCommandMixin(*args, **kwargs)¶
A mixin that provides application commands to the bot.
These mixin should not be created manually, this will be used by
Client
or byBot
.New in version 2.0.
- all_applications¶
A collection of registered commands that the bot knows.
- @application_command(*args, **kwargs)¶
A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_application()
.New in version 2.0.
- Returns
A decorator that converts the provided method into an
ApplicationCommand
, adds it to the bot, then returns it.- Return type
Callable[…,
ApplicationCommand
]
- @slash_command(*args, **kwargs)¶
A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_application()
. This shortcut is made specifically forSlashCommand
.New in version 2.0.
- Parameters
name (Optional[
str
]) – The name of the command. Defaults to the name of the method.description (Optional[
str
]) – A short description of the command.guild_ids (Optional[List[
int
]]) – Guild IDs where the command can be run on. Setting this will make the command only usable from this guild.checks (Optional[List[Callable[[
ApplicationContext
],bool
]]]) – A list of predicates that must be true for the command to be invoked.
- Returns
A decorator that converts the provided method into a
SlashCommand
, adds it to the bot, then returns it.- Return type
Callable[…,
SlashCommand
]
- @user_command(*args, **kwargs)¶
A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_application()
. This shortcut is made specifically forUserCommand
.New in version 2.0.
- Parameters
name (Optional[
str
]) – The name of the command. Defaults to the name of the method.guild_ids (Optional[List[
int
]]) – Guild IDs where the command can be run on. Setting this will make the command only usable from this guild.checks (Optional[List[Callable[[
ApplicationContext
],bool
]]]) – A list of predicates that must be true for the command to be invoked.
- Returns
A decorator that converts the provided method into a
UserCommand
, adds it to the bot, then returns it.- Return type
Callable[…,
UserCommand
]
- @message_command(*args, **kwargs)¶
A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_application()
. This shortcut is made specifically forMessageCommand
.New in version 2.0.
- Parameters
name (Optional[
str
]) – The name of the command. Defaults to the name of the method.guild_ids (Optional[List[
int
]]) – Guild IDs where the command can be run on. Setting this will make the command only usable from this guild.checks (Optional[List[Callable[[
ApplicationContext
],bool
]]]) – A list of predicates that must be true for the command to be invoked.
- Returns
A decorator that converts the provided method into a
MessageCommand
, adds it to the bot, then returns it.- Return type
Callable[…,
MessageCommand
]
- add_application(command)¶
Register a new application command.
- Parameters
command (
ApplicationCommand
) – The command to register.
- remove_application(command)¶
Remove command from the list of registered commands.
- Parameters
command (
ApplicationCommand
) – The command to register.
- register_application(command, *, force=False)¶
Register the command to the factories and remove from pending section. Please make sure the app already been registered to Discord.
- Parameters
command (
ApplicationCommand
) – The command to register.force (
bool
) – IfTrue
, the command will be registered even if it’s not registered to Discord.
- await process_application_commands(interaction)¶
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_interaction()
event. If you choose to override theon_interaction()
event, then you should invoke this coroutine as well.This function finds a registered command matching the interaction id from
ApplicationCommandMixin.application_command()
and runsApplicationCommand.invoke()
on it. If no matching command was found, it replies to the interaction with a default message.New in version 2.0.
- Parameters
interaction (
discord.Interaction
) – The interaction to process
- await get_application_context(interaction, cls=None)¶
This function is a coroutine.
Returns the invocation context from the interaction. This is a more low-level counter-part for
process_application_commands()
to allow users more fine grained control over the processing.- Parameters
interaction (
discord.Interaction
) – The interaction to get the invocation context from.cls – The factory class that will be used to create the context. By default, this is
ApplicationContext
. Should a custom class be provided, it must be similar enough toApplicationContext
's interface.
- Returns
The invocation context. The type of this can change via the
cls
parameter.- Return type
- await on_interaction(interaction)¶
This function is a coroutine.
This event handle should handle all interaction coming from Discord. This would pass the information into
process_application_commands()
If you’re overriding this, please dont forget to call the
process_application_commands()
or the application wont work.- Parameters
interaction (
discord.Interaction
) – The interaction to process
- await on_application_error(context, exception)¶
This function is a coroutine.
The default command error handler provided by the bot.
By default this prints to
sys.stderr
however it could be overridden to have a different implementation.This only fires if you do not specify any listeners for command error.
ApplicationCommandFactory¶
- defadd_command
- defall_commands
- defget_command
- defremove_command
- defvalues
- class discord.ext.app.mixins.ApplicationCommandFactory¶
A “factory” or collector of application commands.
These factory should not be created manually, it will be called from
ApplicationCommandMixin
.- slash_commands¶
All slash commands registered with this factory.
- Type
Dict[
str
,SlashCommand
]
- user_commands¶
All user commands registered with this factory.
- Type
Dict[
str
,UserCommand
]
- message_commands¶
All message commands registered with this factory.
- Type
Dict[
str
,MessageCommand
]
- all_commands()¶
List[
ApplicationCommand
]: Get all commands from this factory.
- values()¶
List[
ApplicationCommand
]: Get all commands from this factory.
- add_command(command, *, force=False)¶
Add a new command to the factories.
If the command already exist, it will raise an
ApplicationRegistrationError
.- Parameters
command (
ApplicationCommand
derived) – The command to register.force (
bool
) – Force registration the command.
- Raises
ApplicationRegistrationError – Raised when you’re trying to register a command with the same name as other command that already been registered.
- get_command(name, type)¶
Get a command from the factory.
- Parameters
name (
str
) – The command name to searchtype (
ApplicationCommandType
) – The type of command to search for.
- Returns
The command that was requested, or
None
if not found.- Return type
Optional[
ApplicationCommand
] derived
- remove_command(command)¶
Remove a command from the factory.
- Parameters
command (Union[
str
,ApplicationCommand
derived]) – The command to search for, it will try to match by name. If you provide a string, it will try to guess where the command is.- Returns
The command that was removed, if
None
it means the command doesn’t exist.- Return type
Optional[
ApplicationCommand
]
Event Reference¶
These events function similar to the regular events, except they are custom to the app extension module.
- discord.ext.app.on_application_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.
- Parameters
ctx (
ApplicationContext
) – The invocation context.error (
ApplicationCommandError
derived) – The error that was raised.
- discord.ext.app.on_application(ctx)¶
An event that is called when a command is found and is about to be invoked.
This event is called regardless of whether the command itself succeeds via error or completes.
- Parameters
ctx (
ApplicationContext
) – The invocation context.
- discord.ext.app.on_application_completion(ctx)¶
An event that is called when a command has completed its invocation.
This event is called only if the command succeeded, i.e. all checks have passed and the user input it correctly.
- Parameters
ctx (
ApplicationContext
) – The invocation context.
- discord.ext.app.on_unknown_application(interaction)¶
An event that is called if an unknown command is invoked.
This event is called just after the Bot try to find matching command.
- Parameters
ctx (
Interaction
) – The interaction context.
Enums¶
- class discord.ext.app.ApplicationBucketType¶
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.
Checks¶
- @discord.ext.app.check(predicate)¶
A decorator that adds a check to the
ApplicationCommand
or its subclasses. These checks could be accessed viaApplicationCommand.checks
.These checks should be predicates that take in a single parameter taking a
ApplicationContext
. If the check returns aFalse
-like value then during invocation aApplicationCheckFailure
exception is raised and sent to theon_application_error()
event.If an exception should be thrown in the predicate then it should be a subclass of
ApplicationCommandError
. Any exception not subclassed from it will be propagated while those subclassed will be sent toon_application_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 = app.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 app.check(extended_check)
Note
The function returned by
predicate
is always a coroutine, even if the original function was not a coroutine.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 == 466469077444067372 @app.slash_command() @app.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 == 466469077444067372 return app.check(predicate) @bot.slash_command() @is_me() async def only_me(ctx): await ctx.send('Only you!')
- Parameters
predicate (Callable[[
ApplicationContext
],bool
]) – The predicate to check if the command should be invoked.
- @discord.ext.app.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
ApplicationCheckAnyFailure
is raised to signal the failure. It inherits fromApplicationCheckFailure
.Note
The
predicate
attribute for this function is a coroutine.- Parameters
*checks (Callable[[
ApplicationContext
],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 app.check(predicate) @app.slash_command() @app.check_any(app.is_owner(), is_guild_owner()) async def only_for_owners(ctx): await ctx.send('Hello mister owner!')
- @discord.ext.app.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,
ApplicationMissingRole
if the user is missing a role, orApplicationNoPrivateMessage
if it is used in a private message. Both inherit fromApplicationCheckFailure
.
- @discord.ext.app.bot_has_role(**perms)¶
Similar to
has_role()
except checks if the bot itself has the role.This check raises one of two special exceptions,
ApplicationBotMissingRole
if the bot is missing the role, orApplicationNoPrivateMessage
if it is used in a private message. Both inherit fromApplicationCheckFailure
.
- @discord.ext.app.has_any_role(*items)¶
A
check()
that is added that checks if the member invoking the command has any of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.Similar to
has_role()
, the names or IDs passed in must be exact.This check raises one of two special exceptions,
ApplicationMissingAnyRole
if the user is missing all roles, orApplicationNoPrivateMessage
if it is used in a private message. Both inherit fromApplicationCheckFailure
.Raise
ApplicationMissingAnyRole
orApplicationNoPrivateMessage
instead of genericApplicationCheckFailure
- Parameters
items (List[Union[
str
,int
]]) – An argument list of names or IDs to check that the member has roles wise.
Example
@app.slash_command() @app.has_any_role('Library Devs', 'Moderators', 466469077444067372) async def cool(ctx): await ctx.send('You are cool indeed')
- @discord.ext.app.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,
ApplicationBotMissingAnyRole
if the bot is missing all roles, orApplicationNoPrivateMessage
if it is used in a private message. Both inherit fromApplicationCheckFailure
.
- @discord.ext.app.cooldown(rate, per, type=ApplicationBucketType.default)¶
A decorator that adds a cooldown to a
ApplicationCommand
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 or global basis. Denoted by the third argument of
type
which must be of enum typeApplicationBucketType
.If a cooldown is triggered, then
ApplicationCommandOnCooldown
is triggered inon_application_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[
ApplicationBucketType
, Callable[[Interaction
], Any]]) – The type of cooldown to have. If callable, should return a key for the mapping.
- @discord.ext.app.dynamic_cooldown(cooldown, type=ApplicationBucketType.default)¶
A decorator that adds a dynamic cooldown to a
ApplicationCommand
This differs from
cooldown()
in that it takes a function that accepts a single parameter of typeInteraction
and must return aApplicationCooldown
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 or global basis. Denoted by the third argument of
type
which must be of enum typeApplicationBucketType
.If a cooldown is triggered, then
ApplicationCommandOnCooldown
is triggered inon_application_error()
and the local error handler.A command can only have a single cooldown.
- Parameters
cooldown (Callable[[
Interaction
], Optional[ApplicationCooldown
]]) – A function that takes a interaction and returns a cooldown that will apply to this invocation orNone
if the cooldown should be bypassed.type (
BucketType
) – The type of cooldown to have.
- @discord.ext.app.max_concurrency(number, per=ApplicationBucketType.default, *, wait=False)¶
A decorator that adds a maximum concurrency to a
ApplicationCommand
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.
- Parameters
number (
int
) – The maximum number of invocations of this command that can be running at the same time.per (
ApplicationBucketType
) – The bucket that this concurrency is based on, e.g.ApplicationBucketType.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 raisesApplicationMaxConcurrencyReached
to its error handler. If this is set toTrue
then the command waits until it can be executed.
- @discord.ext.app.has_permissions(**perms)¶
A
check()
that is added that checks if the member has all of the permissions necessary.Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under
discord.Permissions
.This check raises a special exception,
ApplicationMissingPermissions
that is inherited fromApplicationCheckFailure
.- Parameters
perms – An argument list of permissions to check for.
Example
@app.slash_command() @app.has_permissions(manage_messages=True) async def test(ctx): await ctx.send('You can manage messages.')
- @discord.ext.app.bot_has_permissions(**perms)¶
Similar to
has_permissions()
except checks if the bot itself has the permissions listed.This check raises a special exception,
ApplicationBotMissingPermissions
that is inherited fromApplicationCheckFailure
.
- @discord.ext.app.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,
ApplicationNoPrivateMessage
.
- @discord.ext.app.bot_has_guild_permissions(**perms)¶
Similar to
has_guild_permissions()
, but checks the bot members guild permissions.
- @discord.ext.app.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,
ApplicationPrivateMessageOnly
that is inherited fromApplicationCheckFailure
.
- @discord.ext.app.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,
ApplicationNoPrivateMessage
that is inherited fromApplicationCheckFailure
.
- @discord.ext.app.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,
ApplicationNotOwner
that is derived fromApplicationCheckFailure
.
- @discord.ext.app.is_nsfw¶
A
check()
that checks if the channel is a NSFW channel.This check raises a special exception,
ApplicationNSFWChannelRequired
that is derived fromApplicationCheckFailure
.Changed in version 2.0: Raise
ApplicationNSFWChannelRequired
instead of genericApplicationCheckFailure
. DM channels will also now pass this check.
- @discord.ext.app.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.
Example
async def record_usage(ctx): print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at) @app.slash_command() @app.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): @app.before_invoke(record_usage) @app.slash_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}') @app.slash_command() async def where(self, ctx): # Output: <Nothing> await ctx.send('on Discord') @app.slash_command() async def why(self, ctx): # Output: <Nothing> await ctx.send('because someone made me') bot.add_cog(What())
- @discord.ext.app.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.
Cooldown¶
- defcopy
- defget_retry_after
- defget_tokens
- defreset
- defupdate_rate_limit
- class discord.ext.app.ApplicationCooldown(rate, per)¶
Represents a cooldown for an application.
- 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.
- copy()¶
Creates a copy of this cooldown.
- Returns
A new instance of this cooldown.
- Return type
Context¶
- asyncautocomplete
- asyncdefer
- asyncdelete
- asyncedit
- asyncfetch_message
- defis_autocomplete
- asyncpins
- asyncpong
- asyncrespond
- asyncsend
- asynctrigger_typing
- class discord.ext.app.ApplicationContext(*, bot, interaction, args=..., kwargs=..., command=..., command_failed=False)¶
Represents the context in which a application 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.- bot¶
The bot which is invoking the command.
- Type
Bot
- interaction¶
The interaction object which is used to interact with the user.
- Type
- args¶
The list of transformed arguments that were passed into the command. If this is accessed during the
on_application_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_application_error()
event then this dict could be incomplete.- Type
- command¶
The command or application command that are being executed. If it’s not passed yet, it will be None.
- Type
Union[
SlashCommand
,UserCommand
,MessageCommand
]
- command_failed¶
A boolean that indicates if this command failed to be parsed, checked, or invoked.
- Type
- invoked_subcommand¶
The subcommand that was invoked, if any.
- Type
Optional[
SlashCommand
]
- async for ... in Context.history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an
AsyncIterator
that enables receiving the destination’s message history.You must have
read_message_history
permissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int
]) – The number of messages to retrieve. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages before this date or message. If a 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 Context.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!')
- property cog: Optional[discord.ext.app._types.CogT]¶
Returns the cog associated with this context’s command. None if it does not exist.
- Type
Optional[
Cog
]
- property invoked_with: Optional[str]¶
The original string that the user used to invoke the command. Might be none if the command is context menu.
- Type
invoked_with
- Type
Optional[
str
]
- property responded: bool¶
Indicates whether an interaction response has been done before.
An interaction can only be responded to once.
- Type
- property deferred: bool¶
Indicates if the interaction already been deferred.
If it’s already deferred, when user use
respond()
orsend()
it will useedit()
to edit the response instead.- Type
- 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. None if not available.
- Type
Optional[Union[
GuildChannel
,PartialMessageable
,Thread
]
- author¶
Returns the author associated with this context’s command. Shorthand for
Message.author
- me¶
Similar to
Guild.me
except it may return theClientUser
in private message contexts.- Type
Union[
Member
,ClientUser
]
- property voice_client: Optional[discord.voice_client.VoiceProtocol]¶
A shortcut to
Guild.voice_client
, if applicable.- Type
Optional[
VoiceProtocol
]
- response¶
Shortcut for
Interaction.response
- Type
- property respond¶
This function is a coroutine.
Respond to the interaction.
This property is a shortcut for
Webhook.send
,send_message()
, oredit_original_message
.It will automatically selected the appropriate method based on the current state of the interaction.
If the interaction already deferred, it will use
edit()
to edit the response instead. If the interaction is already responded, it will usesend()
to respond while if it haven’t it will useInteractionResponse.send_message
to respond.
- edit(*, content=..., embeds=..., embed=..., file=..., files=..., view=..., allowed_mentions=None)¶
This function is a coroutine.
Edits the original interaction response message.
This is a lower level interface to
InteractionMessage.edit()
in case you do not want to fetch the message and save an HTTP request.This method is also the only way to edit the original message if the message sent was ephemeral.
- Parameters
content (Optional[
str
]) – The content to edit the message with orNone
to clear it.embeds (List[
Embed
]) – A list of embeds to edit the message with.embed (Optional[
Embed
]) – The embed to edit the message with.None
suppresses the embeds. This should not be mixed with theembeds
parameter.file (
File
) – The file to upload. This cannot be mixed withfiles
parameter.files (List[
File
]) – A list of files to send with the content. This cannot be mixed with thefile
parameter.allowed_mentions (
AllowedMentions
) – Controls the mentions being processed in this message. Seeabc.Messageable.send()
for more information.view (Optional[
View
]) – The updated view to update this message with. IfNone
is passed then the view is removed.
- Raises
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
TypeError – You specified both
embed
andembeds
orfile
andfiles
ValueError – The length of
embeds
was invalid.
- Returns
The newly edited message.
- Return type
InteractionMessage
- await defer(*, ephemeral=False)¶
This function is a coroutine.
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
- Parameters
ephemeral (
bool
) – Indicates whether the deferred message will eventually be ephemeral. This only applies for interactions of typeInteractionType.application_command
.- Raises
HTTPException – Deferring the interaction failed.
InteractionResponded – This interaction has already been responded to before.
- delete()¶
This function is a coroutine.
Deletes the original interaction response message.
This is a lower level interface to
InteractionMessage.delete()
in case you do not want to fetch the message and save an HTTP request.- Raises
HTTPException – Deleting the message failed.
Forbidden – Deleted a message that is not yours.
- pong()¶
This function is a coroutine.
Pongs the ping interaction.
This should rarely be used.
- Raises
HTTPException – Ponging the interaction failed.
InteractionResponded – This interaction has already been responded to before.
- await autocomplete(choices)¶
This function is a coroutine.
Response to an autocomplete interaction.
This method give the user choices to choose from. If there’s nothing to be autocopmleted, it will raise Error.
- Parameters
choices (List[Union[
str
,OptionChoice
]]) – The choices for autocompletion that will be sent to user.- Raises
HTTPException – Autocompleting an option failed.
ValueError – If the choices has more than 25 choices.
InteractionResponded – This interaction has already been responded to before.
ApplicationNoAutocomplete – If the current context doesn’t have any autocomplete to do.
- property send¶
This function is a coroutine.
Respond to the interaction.
This property is a shortcut for
Webhook.send
,send_message()
, oredit_original_message
.It will automatically selected the appropriate method based on the current state of the interaction.
If the interaction already deferred, it will use
edit()
to edit the response instead. If the interaction is already responded, it will usesend()
to respond while if it haven’t it will useInteractionResponse.send_message
to respond.
- 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 pins()¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Message
objects returned by this method do not contain completeMessage.reactions
data.- Raises
HTTPException – Retrieving the pinned messages failed.
- Returns
The messages that are currently pinned.
- Return type
List[
Message
]
Exceptions¶
- exception discord.ext.app.ApplicationCommandError¶
The base exception type for all command related errors.
This inherits from
discord.DiscordException
.This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from
Bot
,on_application_error()
.
- exception discord.ext.app.ApplicationCommandInvokeError(e)¶
Exception raised when the application command being invoked raised an exception.
This inherits from
ApplicationCommandError
- exception discord.ext.app.ApplicationRegistrationError(name)¶
An exception raised when the command can’t be added because the name is already taken by a different command.
This inherits from
discord.ClientException
- exception discord.ext.app.ApplicationRegistrationMaxDepthError(name, parent_name)¶
An exception raised when the command can’t be added because the parent reach the maximum depth for more child.
This inherits from
discord.ClientException
- exception discord.ext.app.ApplicationRegistrationExistingParentOptions(name, option)¶
An exception raise when the command can’t be added because the parent command contains and options that cannot be used if the child is a subcommand or group.
This inherits from
discord.ClientException
- exception discord.ext.app.ApplicationAutocompleteError¶
The base exception type for errors that involve autocomplete.
This inherits from
ApplicationCommandError
.
- exception discord.ext.app.ApplicationNoAutocomplete(name)¶
An exception that will be raised if you try to respond with autocomplete where there is nothing to be autocompleted.
This errors will be raised from client side and not server side.
This inherits from
ApplicationAutocompleteError
.
- exception discord.ext.app.ApplicationUserInputError¶
The base exception type for errors that involve errors regarding user input.
This inherits from
ApplicationCommandError
.
- exception discord.ext.app.ApplicationMissingRequiredArgument(command, param)¶
Exception raised when parsing a command and a parameter that is required is not encountered.
This inherits from
ApplicationUserInputError
- param¶
The argument that is missing.
- Type
- exception discord.ext.app.ApplicationTooManyArguments¶
Exception raised when the command was passed too many arguments.
This inherits from
ApplicationUserInputError
- exception discord.ext.app.ApplicationBadArgument¶
Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command.
This inherits from
ApplicationUserInputError
- exception discord.ext.app.ApplicationUserNotFound(argument)¶
Exception raised when the user provided was not found in the bot’s cache.
This inherits from
ApplicationBadArgument
New in version 1.5.
- exception discord.ext.app.ApplicationMemberNotFound(argument)¶
Exception raised when the member provided was not found in the bot’s cache.
This inherits from
ApplicationBadArgument
- exception discord.ext.app.ApplicationMentionableNotFound(argument)¶
Exception raised when the mentionable provided was not found in the bot’s cache.
This inherits from
ApplicationBadArgument
- exception discord.ext.app.ApplicationCommandOnCooldown(cooldown, retry_after, type)¶
Exception raised when the command being invoked is on cooldown.
This inherits from
ApplicationCommandError
- cooldown¶
A class with attributes
rate
andper
similar to thecooldown()
decorator.- Type
- type¶
The type associated with the cooldown.
- exception discord.ext.app.ApplicationMaxConcurrencyReached(number, per)¶
Exception raised when the command being invoked has reached its maximum concurrency.
This inherits from
ApplicationCommandError
.- per¶
The bucket type passed to the
max_concurrency()
decorator.
- exception discord.ext.app.ApplicationCheckFailure¶
Exception raised when a invoked check fails.
This inherits from
ApplicationCommandError
.
- exception discord.ext.app.ApplicationCheckAnyFailure(checks, errors)¶
Exception raised when all predicates in
check_any()
fail.This inherits from
ApplicationCheckFailure
.New in version 1.3.
- errors¶
A list of errors that were caught during execution.
- Type
List[
ApplicationCheckFailure
]
- checks¶
A list of check predicates that failed.
- Type
List[Callable[[
ApplicationContext
],bool
]]
- exception discord.ext.app.ApplicationPrivateMessageOnly(message=None)¶
Exception raised when an operation does not work outside of private message contexts.
This inherits from
ApplicationCheckFailure
- exception discord.ext.app.ApplicationNoPrivateMessage(message=None)¶
Exception raised when an operation does not work in private message contexts.
This inherits from
ApplicationCheckFailure
- exception discord.ext.app.ApplicationMissingRole(missing_role)¶
Exception raised when the command invoker lacks a role to run a command.
This inherits from
ApplicationCheckFailure
- missing_role¶
The required role that is missing. This is the parameter passed to
has_role()
.
- exception discord.ext.app.ApplicationBotMissingRole(missing_role)¶
Exception raised when the bot’s member lacks a role to run a command.
This inherits from
ApplicationCheckFailure
- missing_role¶
The required role that is missing. This is the parameter passed to
has_role()
.
- exception discord.ext.app.ApplicationMissingAnyRole(missing_roles)¶
Exception raised when the command invoker lacks any of the roles specified to run a command.
This inherits from
ApplicationCheckFailure
New in version 1.1.
- missing_roles¶
The roles that the invoker is missing. These are the parameters passed to
has_any_role()
.
- exception discord.ext.app.ApplicationBotMissingAnyRole(missing_roles)¶
Exception raised when the bot’s member lacks any of the roles specified to run a command.
This inherits from
ApplicationCheckFailure
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 discord.ext.app.ApplicationMissingPermissions(missing_permissions, *args)¶
Exception raised when the command invoker lacks permissions to run a command.
This inherits from
ApplicationCheckFailure
- exception discord.ext.app.ApplicationBotMissingPermissions(missing_permissions, *args)¶
Exception raised when the bot’s member lacks permissions to run a command.
This inherits from
ApplicationCheckFailure
- exception discord.ext.app.ApplicationNSFWChannelRequired(channel)¶
Exception raised when a channel does not have the required NSFW setting.
This inherits from
ApplicationCheckFailure
.New in version 1.1.
- Parameters
channel (Union[
abc.GuildChannel
,Thread
]) – The channel that does not have NSFW enabled.
- exception discord.ext.app.ApplicationNotOwner¶
Exception raised when the message author is not the owner of the bot.
This inherits from
ApplicationCheckFailure