Referensi API

Laman ini akan memberikan garis besar untuk ekstensi aplikasi API ndiscord.py.

Fungsi Utama

ApplicationCommand

class discord.ext.app.ApplicationCommand(*args, **kwargs)

Sebuah kelas yang mengimplementasikan protokol untuk perintah aplikasi.

Ini tidak untuk dibuat secara manual, tetapi mohon gunakan dekorator atau fungsi yang sudah disediakan.

id

ID untuk perintahnya, bisa jadi None jika perintah belum didaftarkan.

tipe

Optional[int]

name

Nama perintahnya.

tipe

str

callback

Coroutine yang akan dipanggil saat perintah dipanggil.

tipe

coroutine

guild_ids

Koleksi ID guild di mana perintah ini dapat dipakai.

tipe

List[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 from ApplicationCommandError should be used. Note that if the checks fail then ApplicationCheckFailure exception is raised to the on_application_error() event.

tipe

List[Callable[[ApplicationContext], bool]]

type

The type of application command.

tipe

ApplicationCommandType

cog

The cog that this command belongs to. None if there isn't one.

tipe

Optional[Cog]

@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.

Parameter

coro (coroutine) -- The coroutine to register as the post-invoke hook.

Raises

TypeError -- The coroutine passed is not actually a coroutine.

@before_invoke

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.

This pre-invoke hook takes a sole parameter, a ApplicationContext.

Parameter

coro (coroutine) -- The coroutine to register as the pre-invoke hook.

Raises

TypeError -- The coroutine passed is not actually a coroutine.

@error

A decorator that registers a coroutine as a local error handler.

A local error handler is an on_application_error() event limited to a single command. However, the on_application_error() is still invoked afterwards as the catch-all.

Parameter

coro (coroutine) -- The coroutine to register as the local error handler.

Raises

TypeError -- The coroutine passed is not actually a coroutine.

property qualified_name

The application qualified name.

tipe

str

has_error_handler()

bool: Checks whether the command has an error handler registered.

add_check(func)

Adds a check to the command.

This is the non-decorator interface to check().

Parameter

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.

Parameter

func -- The function to remove from the checks.

property cog_name: Optional[str]

The name of the cog this command belongs to, if any.

tipe

Optional[str]

await invoke(ctx)

This function is a coroutine.

Execute or invoke the function callback of the app command.

Parameter

ctx (ApplicationContext) -- The invocation context.

Raises
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.

Parameter
  • 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.

Kembali

A new instance of this app command.

Return type

ApplicationCommand

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.

Parameter

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.

Kembali

A boolean indicating if the command can be invoked.

Return type

bool

to_dict()

dict: A discord API friendly dictionary that can be submitted to the API.

ContextMenuApplication

class discord.ext.app.ContextMenuApplication(*args, **kwargs)

A class that implements an application command that can be invoked by opening Discord context menu.

Currently implement message context and user context.

Ini tidak untuk dibuat secara manual, tetapi mohon gunakan dekorator atau fungsi yang sudah disediakan.

id

ID untuk perintahnya, bisa jadi None jika perintah belum didaftarkan.

tipe

Optional[int]

name

Nama perintahnya.

tipe

str

guild_ids

Koleksi ID guild di mana perintah ini dapat dipakai.

tipe

List[int]

callback

Coroutine yang akan dipanggil saat perintah dipanggil.

tipe

coroutine

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 from ApplicationCommandError should be used. Note that if the checks fail then ApplicationCheckFailure exception is raised to the on_application_error() event.

tipe

List[Callable[[ApplicationContext], bool]]

type

The type of application command.

tipe

ApplicationCommandType

cog

The cog that this command belongs to. None if there isn't one.

tipe

Optional[Cog]

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. And ctx which can be the first/second argument.

tipe

OrderedDict[str, Parameter]

@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.

Parameter

coro (coroutine) -- The coroutine to register as the post-invoke hook.

Raises

TypeError -- The coroutine passed is not actually a coroutine.

@before_invoke

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.

This pre-invoke hook takes a sole parameter, a ApplicationContext.

Parameter

coro (coroutine) -- The coroutine to register as the pre-invoke hook.

Raises

TypeError -- The coroutine passed is not actually a coroutine.

@error

A decorator that registers a coroutine as a local error handler.

A local error handler is an on_application_error() event limited to a single command. However, the on_application_error() is still invoked afterwards as the catch-all.

Parameter

coro (coroutine) -- The coroutine to register as the local error handler.

Raises

TypeError -- The coroutine passed is not actually a coroutine.

for ... in walk_commands()

An iterator that recursively walks through all commands and subcommands.

Hasil

ContextMenuApplication -- 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().

Parameter

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.

Parameter

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.

Kembali

A boolean indicating if the command can be invoked.

Return type

bool

property cog_name: Optional[str]

The name of the cog this command belongs to, if any.

tipe

Optional[str]

copy()

Creates a copy of this app command.

Kembali

A new instance of this app command.

Return type

ApplicationCommand

has_error_handler()

bool: Checks whether the command has an error handler registered.

await invoke(ctx)

This function is a coroutine.

Execute or invoke the function callback of the app command.

Parameter

ctx (ApplicationContext) -- The invocation context.

Raises
property qualified_name

The application qualified name.

tipe

str

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.

Parameter
  • 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.

Parameter

func -- The function to remove from the checks.

to_dict()

dict: A discord API friendly dictionary that can be submitted to the API.

SlashCommand

class discord.ext.app.SlashCommand(*args, **kwargs)

A class that implements an application command that can be invoked through a via Discord /slash command.

Ini tidak untuk dibuat secara manual, tetapi mohon gunakan dekorator atau fungsi yang sudah disediakan.

id

ID untuk perintahnya, bisa jadi None jika perintah belum didaftarkan.

tipe

Optional[int]

name

Nama perintahnya.

tipe

str

description

The description of the command.

tipe

str

guild_ids

Koleksi ID guild di mana perintah ini dapat dipakai.

tipe

List[int]

options

A list of options that the user can set for the command.

tipe

List[Option]

callback

Coroutine yang akan dipanggil saat perintah dipanggil.

tipe

coroutine

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 from ApplicationCommandError should be used. Note that if the checks fail then ApplicationCheckFailure exception is raised to the on_application_error() event.

tipe

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.

tipe

Optional[SlashCommand]

type

The type of application command.

tipe

ApplicationCommandType

sub_type

The type of the slash command, can only be SlashCommandOptionType.sub_command or SlashCommandOptionType.sub_command_group.

tipe

SlashCommandOptionType

cog

The cog that this command belongs to. None if there isn't one.

tipe

Optional[Cog]

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. And ctx which can be the first/second argument.

tipe

OrderedDict[str, Parameter]

@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.

Parameter

coro (coroutine) -- The coroutine to register as the post-invoke hook.

Raises

TypeError -- The coroutine passed is not actually a coroutine.

@before_invoke

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.

This pre-invoke hook takes a sole parameter, a ApplicationContext.

Parameter

coro (coroutine) -- The coroutine to register as the pre-invoke hook.

Raises

TypeError -- The coroutine passed is not actually a coroutine.

@error

A decorator that registers a coroutine as a local error handler.

A local error handler is an on_application_error() event limited to a single command. However, the on_application_error() is still invoked afterwards as the catch-all.

Parameter

coro (coroutine) -- The coroutine to register as the local error handler.

Raises

TypeError -- The coroutine passed is not actually a coroutine.

@command

A decorator that would add a new subcommand to the parent command.

Kembali

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.

Kembali

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

tipe

Dict[str, SlashCommand]

has_parent()

bool: Check if the command have parent or not.

await invoke(ctx)

This function is a coroutine.

Execute or invoke the function callback of the app command.

Parameter

ctx (ApplicationContext) -- The invocation context.

Raises
add_command(command)

Adds a SlashCommand into the internal list of commands.

This is usually not called, instead the command() or group() shortcut decorators are used instead.

Parameter

command (Command) -- The command to add.

Raises
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.

tipe

Set[SlashCommand]

for ... in walk_commands()

An iterator that recursively walks through all commands and subcommands.

Hasil

SlashCommand -- A command or group from the internal list of commands.

to_dict()

dict: A discord API friendly dictionary that can be submitted to the API.

add_check(func)

Adds a check to the command.

This is the non-decorator interface to check().

Parameter

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.

Parameter

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.

Kembali

A boolean indicating if the command can be invoked.

Return type

bool

property cog_name: Optional[str]

The name of the cog this command belongs to, if any.

tipe

Optional[str]

copy()

Creates a copy of this app command.

Kembali

A new instance of this app command.

Return type

ApplicationCommand

has_error_handler()

bool: Checks whether the command has an error handler registered.

property qualified_name

The application qualified name.

tipe

str

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.

Parameter
  • 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.

Parameter

func -- The function to remove from the checks.

UserCommand

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.

Ini tidak untuk dibuat secara manual, tetapi mohon gunakan dekorator atau fungsi yang sudah disediakan.

id

ID untuk perintahnya, bisa jadi None jika perintah belum didaftarkan.

tipe

Optional[int]

name

Nama perintahnya.

tipe

str

guild_ids

Koleksi ID guild di mana perintah ini dapat dipakai.

tipe

List[int]

callback

Coroutine yang akan dipanggil saat perintah dipanggil.

tipe

coroutine

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 from ApplicationCommandError should be used. Note that if the checks fail then ApplicationCheckFailure exception is raised to the on_application_error() event.

tipe

List[Callable[[ApplicationContext], bool]]

type

The type of application command.

tipe

ApplicationCommandType

cog

The cog that this command belongs to. None if there isn't one.

tipe

Optional[Cog]

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. And ctx which can be the first/second argument.

tipe

OrderedDict[str, Parameter]

@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.

Parameter

coro (coroutine) -- The coroutine to register as the post-invoke hook.

Raises

TypeError -- The coroutine passed is not actually a coroutine.

@before_invoke

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.

This pre-invoke hook takes a sole parameter, a ApplicationContext.

Parameter

coro (coroutine) -- The coroutine to register as the pre-invoke hook.

Raises

TypeError -- The coroutine passed is not actually a coroutine.

@error

A decorator that registers a coroutine as a local error handler.

A local error handler is an on_application_error() event limited to a single command. However, the on_application_error() is still invoked afterwards as the catch-all.

Parameter

coro (coroutine) -- The coroutine to register as the local error handler.

Raises

TypeError -- The coroutine passed is not actually a coroutine.

add_check(func)

Adds a check to the command.

This is the non-decorator interface to check().

Parameter

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.

Parameter

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.

Kembali

A boolean indicating if the command can be invoked.

Return type

bool

property cog_name: Optional[str]

The name of the cog this command belongs to, if any.

tipe

Optional[str]

copy()

Creates a copy of this app command.

Kembali

A new instance of this app command.

Return type

ApplicationCommand

has_error_handler()

bool: Checks whether the command has an error handler registered.

await invoke(ctx)

This function is a coroutine.

Execute or invoke the function callback of the app command.

Parameter

ctx (ApplicationContext) -- The invocation context.

Raises
property qualified_name

The application qualified name.

tipe

str

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.

Parameter
  • 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.

Parameter

func -- The function to remove from the checks.

to_dict()

dict: A discord API friendly dictionary that can be submitted to the API.

for ... in walk_commands()

An iterator that recursively walks through all commands and subcommands.

Hasil

ContextMenuApplication -- A command or group from the internal list of commands.

MessageCommand

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.

Ini tidak untuk dibuat secara manual, tetapi mohon gunakan dekorator atau fungsi yang sudah disediakan.

id

ID untuk perintahnya, bisa jadi None jika perintah belum didaftarkan.

tipe

Optional[int]

name

Nama perintahnya.

tipe

str

guild_ids

Koleksi ID guild di mana perintah ini dapat dipakai.

tipe

List[int]

callback

Coroutine yang akan dipanggil saat perintah dipanggil.

tipe

coroutine

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 from ApplicationCommandError should be used. Note that if the checks fail then ApplicationCheckFailure exception is raised to the on_application_error() event.

tipe

List[Callable[[ApplicationContext], bool]]

type

The type of application command.

tipe

ApplicationCommandType

cog

The cog that this command belongs to. None if there isn't one.

tipe

Optional[Cog]

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. And ctx which can be the first/second argument.

tipe

OrderedDict[str, Parameter]

@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.

Parameter

coro (coroutine) -- The coroutine to register as the post-invoke hook.

Raises

TypeError -- The coroutine passed is not actually a coroutine.

@before_invoke

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.

This pre-invoke hook takes a sole parameter, a ApplicationContext.

Parameter

coro (coroutine) -- The coroutine to register as the pre-invoke hook.

Raises

TypeError -- The coroutine passed is not actually a coroutine.

@error

A decorator that registers a coroutine as a local error handler.

A local error handler is an on_application_error() event limited to a single command. However, the on_application_error() is still invoked afterwards as the catch-all.

Parameter

coro (coroutine) -- The coroutine to register as the local error handler.

Raises

TypeError -- The coroutine passed is not actually a coroutine.

add_check(func)

Adds a check to the command.

This is the non-decorator interface to check().

Parameter

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.

Parameter

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.

Kembali

A boolean indicating if the command can be invoked.

Return type

bool

property cog_name: Optional[str]

The name of the cog this command belongs to, if any.

tipe

Optional[str]

copy()

Creates a copy of this app command.

Kembali

A new instance of this app command.

Return type

ApplicationCommand

has_error_handler()

bool: Checks whether the command has an error handler registered.

await invoke(ctx)

This function is a coroutine.

Execute or invoke the function callback of the app command.

Parameter

ctx (ApplicationContext) -- The invocation context.

Raises
property qualified_name

The application qualified name.

tipe

str

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.

Parameter
  • 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.

Parameter

func -- The function to remove from the checks.

to_dict()

dict: A discord API friendly dictionary that can be submitted to the API.

for ... in walk_commands()

An iterator that recursively walks through all commands and subcommands.

Hasil

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.

name

The name of the argument.

tipe

str

description

The description of the argument.

tipe

str

input_type

The type of the argument.

tipe

SlashCommandOptionType

required

Indicates if the argument is required.

tipe

bool

default

The default value of the argument.

tipe

Optional[Any]

choices

A list of valid options for the argument.

tipe

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.

tipe

Optional[List[ChannelType]]

min_value

The minimum value of the number option, the input_type must be SlashCommandOptionType.number or SlashCommandOptionType.integer.

tipe

Optional[int]

max_value

The maximum value of the number option, the input_type must be SlashCommandOptionType.number or SlashCommandOptionType.integer.

tipe

Optional[int]

autocomplete

Indicates if the argument should be autocompleted.

Peringatan

choices cannot be present if this is True. And it also only works for SlashCommandOptionType.string only.

tipe

Optional[bool]

Attributes
class discord.ext.app.OptionChoice(name, value=None)

A class that implement an option choice for Option.

You can pass this directly to the choices arguments in Option.

name

The name of the argument that will be passed to the command.

tipe

str

value

The value that will be showed to the user.

tipe

str

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 of SlashCommand, UserCommand, or MessageCommand. The exact class depends on the cls parameter.

By default the description attribute is received automatically from the docstring of the function and is cleaned up with the use of inspect.cleandoc. If the docstring is bytes, then it is decoded into str using utf-8 encoding.

The name attribute also defaults to the function name unchanged.

Baru pada versi 2.0.

Parameter
  • cls (ApplicationCommand) -- The class to construct with. By default this is SlashCommand. 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().

Baru pada versi 2.0.

Parameter
  • 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.

Kembali

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().

Baru pada versi 2.0.

Parameter
  • 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.

Kembali

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().

Baru pada versi 2.0.

Parameter
  • 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.

Kembali

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().

Baru pada versi 2.0.

Kembali

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

Parameter
  • 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 like str 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.

    Peringatan

    choices cannot be present if this is True. And it also only works for SlashCommandOptionType.string only.

Mixins

This is information for Mixins created to help load applications into the Bot or Client.

Peringatan

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 by Bot.

Baru pada versi 2.0.

all_applications

A collection of registered commands that the bot knows.

tipe

ApplicationCommandFactory

debug_guilds

Get the list of guilds that are being used for debugging purpose.

tipe

List[int]

@application_command(*args, **kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list via add_application().

Baru pada versi 2.0.

Kembali

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 via add_application(). This shortcut is made specifically for SlashCommand.

Baru pada versi 2.0.

Parameter
  • 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.

Kembali

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 via add_application(). This shortcut is made specifically for UserCommand.

Baru pada versi 2.0.

Parameter
  • 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.

Kembali

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 via add_application(). This shortcut is made specifically for MessageCommand.

Baru pada versi 2.0.

Parameter
  • 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.

Kembali

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.

Parameter

command (ApplicationCommand) -- The command to register.

remove_application(command)

Remove command from the list of registered commands.

Parameter

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.

Parameter
  • command (ApplicationCommand) -- The command to register.

  • force (bool) -- If True, 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 the on_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 runs ApplicationCommand.invoke() on it. If no matching command was found, it replies to the interaction with a default message.

Baru pada versi 2.0.

Parameter

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.

Parameter
  • 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 to ApplicationContext's interface.

Kembali

The invocation context. The type of this can change via the cls parameter.

Return type

ApplicationContext

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.

Parameter

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

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.

tipe

Dict[str, SlashCommand]

user_commands

All user commands registered with this factory.

tipe

Dict[str, UserCommand]

message_commands

All message commands registered with this factory.

tipe

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.

Parameter
  • 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.

Parameter
Kembali

The command that was requested, or None if not found.

Return type

Optional[ApplicationCommand] derived

remove_command(command)

Remove a command from the factory.

Parameter

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.

Kembali

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.

Parameter
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.

Parameter

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.

Parameter

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.

Parameter

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 via ApplicationCommand.checks.

These checks should be predicates that take in a single parameter taking a ApplicationContext. If the check returns a False-like value then during invocation a ApplicationCheckFailure exception is raised and sent to the on_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 to on_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)

Catatan

The function returned by predicate is always a coroutine, even if the original function was not a coroutine.

Contoh-contoh

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!')
Parameter

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 from ApplicationCheckFailure.

Catatan

The predicate attribute for this function is a coroutine.

Parameter

*checks (Callable[[ApplicationContext], bool]) -- An argument list of checks that have been decorated with the check() decorator.

Raises

TypeError -- A check passed has not been decorated with the check() decorator.

Contoh-contoh

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, or ApplicationNoPrivateMessage if it is used in a private message. Both inherit from ApplicationCheckFailure.

Parameter

item (Union[int, str]) -- The name or ID of the role to check.

@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, or ApplicationNoPrivateMessage if it is used in a private message. Both inherit from ApplicationCheckFailure.

@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, or ApplicationNoPrivateMessage if it is used in a private message. Both inherit from ApplicationCheckFailure.

Parameter

items (List[Union[str, int]]) -- An argument list of names or IDs to check that the member has roles wise.

Contoh

@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, or ApplicationNoPrivateMessage if it is used in a private message. Both inherit from ApplicationCheckFailure.

@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 type ApplicationBucketType.

If a cooldown is triggered, then ApplicationCommandOnCooldown is triggered in on_application_error() and the local error handler.

A command can only have a single cooldown.

Parameter
  • 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 type Interaction and must return a ApplicationCooldown or None. If None is returned then that cooldown is effectively bypassed.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user or global basis. Denoted by the third argument of type which must be of enum type ApplicationBucketType.

If a cooldown is triggered, then ApplicationCommandOnCooldown is triggered in on_application_error() and the local error handler.

A command can only have a single cooldown.

Parameter
  • cooldown (Callable[[Interaction], Optional[ApplicationCooldown]]) -- A function that takes a interaction and returns a cooldown that will apply to this invocation or None if the cooldown should be bypassed.

  • type (BucketType) -- The type of cooldown to have.

@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.

Parameter
  • 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 to number times per guild.

  • wait (bool) -- Whether the command should wait for the queue to be over. If this is set to False then instead of waiting until the command can run again, the command raises ApplicationMaxConcurrencyReached to its error handler. If this is set to True 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 from ApplicationCheckFailure.

Parameter

perms -- An argument list of permissions to check for.

Contoh

@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 from ApplicationCheckFailure.

@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 from ApplicationCheckFailure.

@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 from ApplicationCheckFailure.

@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 from ApplicationCheckFailure.

@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 from ApplicationCheckFailure.

Berubah pada versi 2.0: Raise ApplicationNSFWChannelRequired instead of generic ApplicationCheckFailure. 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.

Contoh

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

Attributes
class discord.ext.app.ApplicationCooldown(rate, per)

Represents a cooldown for an application.

rate

The total number of tokens available per per seconds.

tipe

int

per

The length of the cooldown period in seconds.

tipe

float

get_tokens(current=None)

Returns the number of available tokens before rate limiting is applied.

Parameter

current (Optional[float]) -- The time in seconds since Unix epoch to calculate tokens at. If not supplied then time.time() is used.

Kembali

The number of tokens available before the cooldown is to be applied.

Return type

int

get_retry_after(current=None)

Returns the time in seconds until the cooldown will be reset.

Parameter

current (Optional[float]) -- The current time in seconds since Unix epoch. If not supplied, then time.time() is used.

Kembali

The number of seconds to wait before this cooldown will be reset.

Return type

float

update_rate_limit(current=None)

Updates the cooldown rate limit.

Parameter

current (Optional[float]) -- The time in seconds since Unix epoch to update the rate limit at. If not supplied, then time.time() is used.

Kembali

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.

Kembali

A new instance of this cooldown.

Return type

ApplicationCooldown

Context

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.

tipe

Bot

interaction

The interaction object which is used to interact with the user.

tipe

Interaction

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.

tipe

list

kwargs

A dictionary of transformed arguments that were passed into the command. Similar to args, if this is accessed in the on_application_error() event then this dict could be incomplete.

tipe

dict

command

The command or application command that are being executed. If it's not passed yet, it will be None.

tipe

Union[SlashCommand, UserCommand, MessageCommand]

command_failed

A boolean that indicates if this command failed to be parsed, checked, or invoked.

tipe

bool

invoked_subcommand

The subcommand that was invoked, if any.

tipe

Optional[SlashCommand]

autocompleting

The argument name that needs to be autocompleted.

tipe

Optional[str]

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.

Contoh-contoh

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.

Parameter
  • limit (Optional[int]) -- The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Optional[Union[Snowflake, datetime.datetime]]) -- Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.

  • oldest_first (Optional[bool]) -- If set to True, return messages in oldest->newest order. Defaults to True if after is specified, otherwise False.

Raises
  • Forbidden -- You do not have permissions to get channel message history.

  • HTTPException -- The request to get message history failed.

Hasil

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.

Catatan

This is both a regular context manager and an async context manager. This means that both with and async 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.

tipe

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.

tipe

invoked_with

tipe

Optional[str]

is_autocomplete()

is_autocomplete: bool: Returns True if the interaction is an autocomplete.

property responded: bool

Indicates whether an interaction response has been done before.

An interaction can only be responded to once.

tipe

bool

property deferred: bool

Indicates if the interaction already been deferred.

If it's already deferred, when user use respond() or send() it will use edit() to edit the response instead.

tipe

bool

guild

Returns the guild associated with this context's command. None if not available.

tipe

Optional[Guild]

channel

Returns the channel associated with this context's command. None if not available.

tipe

Optional[Union[GuildChannel, PartialMessageable, Thread]

author

Returns the author associated with this context's command. Shorthand for Message.author

tipe

Optional[Union[User, Member]]

me

Similar to Guild.me except it may return the ClientUser in private message contexts.

tipe

Union[Member, ClientUser]

property voice_client: Optional[discord.voice_client.VoiceProtocol]

A shortcut to Guild.voice_client, if applicable.

tipe

Optional[VoiceProtocol]

response

Shortcut for Interaction.response

tipe

InteractionResponse

property followup

Returns the follow up webhook for follow up interactions.

tipe

Webhook

property respond

This function is a coroutine.

Respond to the interaction.

This property is a shortcut for Webhook.send, send_message(), or edit_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 use send() to respond while if it haven't it will use InteractionResponse.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.

Parameter
  • content (Optional[str]) -- The content to edit the message with or None 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 the embeds parameter.

  • file (File) -- The file to upload. This cannot be mixed with files parameter.

  • files (List[File]) -- A list of files to send with the content. This cannot be mixed with the file parameter.

  • allowed_mentions (AllowedMentions) -- Controls the mentions being processed in this message. See abc.Messageable.send() for more information.

  • view (Optional[View]) -- The updated view to update this message with. If None 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 and embeds or file and files

  • ValueError -- The length of embeds was invalid.

Kembali

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.

Parameter

ephemeral (bool) -- Indicates whether the deferred message will eventually be ephemeral. This only applies for interactions of type InteractionType.application_command.

Raises
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
pong()

This function is a coroutine.

Pongs the ping interaction.

This should rarely be used.

Raises
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.

Parameter

choices (List[Union[str, OptionChoice]]) -- The choices for autocompletion that will be sent to user.

Raises
property send

This function is a coroutine.

Respond to the interaction.

This property is a shortcut for Webhook.send, send_message(), or edit_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 use send() to respond while if it haven't it will use InteractionResponse.send_message to respond.

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

Parameter

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.

Kembali

The message asked for.

Return type

Message

await pins()

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Catatan

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

Raises

HTTPException -- Retrieving the pinned messages failed.

Kembali

The messages that are currently pinned.

Return type

List[Message]

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

Typing indicator will go away after 10 seconds, or after a message is sent.

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

original

The original exception that was raised. You can also get this via the __cause__ attribute.

tipe

Exception

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

name

The command name that had the error.

tipe

str

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

name

The command name that had the error.

tipe

str

parent_name

The parent command name.

tipe

str

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

name

The command name that had the error.

tipe

str

option

The option that is not allowed.

tipe

Option

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.

name

The command name that had the error.

tipe

str

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.

tipe

inspect.Parameter

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

Baru pada versi 1.5.

argument

The user supplied by the caller that was not found

tipe

str

exception discord.ext.app.ApplicationMemberNotFound(argument)

Exception raised when the member provided was not found in the bot's cache.

This inherits from ApplicationBadArgument

argument

The member supplied by the caller that was not found

tipe

str

exception discord.ext.app.ApplicationMentionableNotFound(argument)

Exception raised when the mentionable provided was not found in the bot's cache.

This inherits from ApplicationBadArgument

argument

The member supplied by the caller that was not found

tipe

str

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 and per similar to the cooldown() decorator.

tipe

ApplicationCooldown

type

The type associated with the cooldown.

tipe

ApplicationBucketType

retry_after

The amount of seconds to wait before you can retry again.

tipe

float

exception discord.ext.app.ApplicationMaxConcurrencyReached(number, per)

Exception raised when the command being invoked has reached its maximum concurrency.

This inherits from ApplicationCommandError.

number

The maximum number of concurrent invokers allowed.

tipe

int

per

The bucket type passed to the max_concurrency() decorator.

tipe

ApplicationBucketType

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.

Baru pada versi 1.3.

errors

A list of errors that were caught during execution.

tipe

List[ApplicationCheckFailure]

checks

A list of check predicates that failed.

tipe

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().

tipe

Union[str, int]

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().

tipe

Union[str, int]

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

Baru pada versi 1.1.

missing_roles

The roles that the invoker is missing. These are the parameters passed to has_any_role().

tipe

List[Union[str, int]]

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

Baru pada versi 1.1.

missing_roles

The roles that the bot's member is missing. These are the parameters passed to has_any_role().

tipe

List[Union[str, int]]

exception discord.ext.app.ApplicationMissingPermissions(missing_permissions, *args)

Exception raised when the command invoker lacks permissions to run a command.

This inherits from ApplicationCheckFailure

missing_permissions

The required permissions that are missing.

tipe

List[str]

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

missing_permissions

The required permissions that are missing.

tipe

List[str]

exception discord.ext.app.ApplicationNSFWChannelRequired(channel)

Exception raised when a channel does not have the required NSFW setting.

This inherits from ApplicationCheckFailure.

Baru pada versi 1.1.

Parameter

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

Exception Hierarchy