API Reference

The following section outlines the API of disnake’s command extension module.

Bots

Bot

Methods
class disnake.ext.commands.Bot(command_prefix=None, help_command=<default-help-command>, description=None, *, strip_after_prefix=False, **options)[source]

Represents a discord bot.

This class is a subclass of disnake.Client and as a result anything that you can do with a disnake.Client you can do with this bot.

This class also subclasses GroupMixin to provide the functionality to manage commands.

Parameters:
  • test_guilds (List[int]) –

    The list of IDs of the guilds where you’re going to test your application commands. Defaults to None, which means global registration of commands across all guilds.

    New in version 2.1.

  • command_sync_flags (ext.commands.CommandSyncFlags) –

    The command sync flags for the session. This is a way of controlling when and how application commands will be synced with the Discord API. If not given, defaults to CommandSyncFlags.default().

    New in version 2.7.

  • sync_commands (bool) –

    Whether to enable automatic synchronization of application commands in your code. Defaults to True, which means that commands in API are automatically synced with the commands in your code.

    New in version 2.1.

    Deprecated since version 2.7: Replaced with command_sync_flags.

  • sync_commands_on_cog_unload (bool) –

    Whether to sync the application commands on cog unload / reload. Defaults to True.

    New in version 2.1.

    Deprecated since version 2.7: Replaced with command_sync_flags.

  • sync_commands_debug (bool) –

    Whether to always show sync debug logs (uses INFO log level if it’s enabled, prints otherwise). If disabled, uses the default DEBUG log level which isn’t shown unless the log level is changed manually. Useful for tracking the commands being registered in the API. Defaults to False.

    New in version 2.1.

    Changed in version 2.4: Changes the log level of corresponding messages from DEBUG to INFO or prints them, instead of controlling whether they are enabled at all.

    Deprecated since version 2.7: Replaced with command_sync_flags.

  • localization_provider (LocalizationProtocol) –

    An implementation of LocalizationProtocol to use for localization of application commands. If not provided, the default LocalizationStore implementation is used.

    New in version 2.5.

  • strict_localization (bool) –

    Whether to raise an exception when localizations for a specific key couldn’t be found. This is mainly useful for testing/debugging, consider disabling this eventually as missing localized names will automatically fall back to the default/base name without it. Only applicable if the localization_provider parameter is not provided. Defaults to False.

    New in version 2.5.

command_prefix

The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and disnake.Message as its second parameter and returns the prefix. This is to facilitate “dynamic” command prefixes. This callable can be either a regular function or a coroutine.

An empty string as the prefix always matches, enabling prefix-less command invocation. While this may be useful in DMs it should be avoided in servers, as it’s likely to cause performance issues and unintended command invocations.

The command prefix could also be an iterable of strings indicating that multiple checks for the prefix should be used and the first one to match will be the invocation prefix. You can get this prefix via Context.prefix. To avoid confusion empty iterables are not allowed.

If the prefix is None, the bot won’t listen to any prefixes, and prefix commands will not be processed. If you don’t need prefix commands, consider using InteractionBot or AutoShardedInteractionBot instead, which are drop-in replacements, just without prefix command support.

This can be provided as a parameter at creation.

Note

When passing multiple prefixes be careful to not pass a prefix that matches a longer prefix occurring later in the sequence. For example, if the command prefix is ('!', '!?') the '!?' prefix will never be matched to any message as the previous one matches messages starting with !?. This is especially important when passing an empty string, it should always be last as no prefix after it will be matched.

case_insensitive

Whether the commands should be case insensitive. Defaults to False. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well.

This can be provided as a parameter at creation.

Type:

bool

description

The content prefixed into the default help message.

This can be provided as a parameter at creation.

Type:

str

help_command[source]

The help command implementation to use. This can be dynamically set at runtime. To remove the help command pass None. For more information on implementing a help command, see Help Commands.

This can be provided as a parameter at creation.

Type:

Optional[HelpCommand]

owner_id

The user ID that owns the bot. If this is not set and is then queried via is_owner() then it is fetched automatically using application_info().

This can be provided as a parameter at creation.

Type:

Optional[int]

owner_ids

The user IDs that owns the bot. This is similar to owner_id. If this is not set and the application is team based, then it is fetched automatically using application_info(). For performance reasons it is recommended to use a set for the collection. You cannot set both owner_id and owner_ids.

This can be provided as a parameter at creation.

New in version 1.3.

Type:

Optional[Collection[int]]

strip_after_prefix

Whether to strip whitespace characters after encountering the command prefix. This allows for !   hello and !hello to both work if the command_prefix is set to !. Defaults to False.

This can be provided as a parameter at creation.

New in version 1.7.

Type:

bool

reload

Whether to enable automatic extension reloading on file modification for debugging. Whenever you save an extension with reloading enabled the file will be automatically reloaded for you so you do not have to reload the extension manually. Defaults to False

This can be provided as a parameter at creation.

New in version 2.1.

Type:

bool

i18n

An implementation of LocalizationProtocol used for localization of application commands.

New in version 2.5.

Type:

LocalizationProtocol

@after_invoke[source]

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

This is for text commands only, and doesn’t apply to application commands.

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

This post-invoke hook takes a sole parameter, a Context.

Note

Similar to before_invoke(), this is not called unless checks and argument parsing procedures succeed. This hook is, however, always called regardless of the internal command callback raising an error (i.e. CommandInvokeError). This makes it ideal for clean-up scenarios.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@after_slash_command_invoke[source]

Similar to Bot.after_invoke() but for slash commands, and it takes an ApplicationCommandInteraction as its only parameter.

@after_user_command_invoke[source]

Similar to Bot.after_slash_command_invoke() but for user commands.

@after_message_command_invoke[source]

Similar to Bot.after_slash_command_invoke() but for message commands.

@before_invoke[source]

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

This is for text commands only, and doesn’t apply to application commands.

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

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

Note

The before_invoke() and after_invoke() hooks are only called if all checks and argument parsing procedures pass without error. If any check or argument parsing procedures fail then the hooks are not called.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@before_slash_command_invoke[source]

Similar to Bot.before_invoke() but for slash commands, and it takes an ApplicationCommandInteraction as its only parameter.

@before_user_command_invoke[source]

Similar to Bot.before_slash_command_invoke() but for user commands.

@before_message_command_invoke[source]

Similar to Bot.before_slash_command_invoke() but for message commands.

@check[source]

A decorator that adds a global check to the bot.

This is for text commands only, and doesn’t apply to application commands.

A global check is similar to a check() that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.

Note

This function can either be a regular function or a coroutine.

Similar to a command check(), this takes a single parameter of type Context and can only raise exceptions inherited from CommandError.

Example

@bot.check
def check_commands(ctx):
    return ctx.command.qualified_name in allowed_commands
@check_once[source]

A decorator that adds a “call once” global check to the bot.

This is for text commands only, and doesn’t apply to application commands.

Unlike regular global checks, this one is called only once per invoke() call.

Regular global checks are called whenever a command is called or Command.can_run() is called. This type of check bypasses that and ensures that it’s called only once, even inside the default help command.

Note

When using this function the Context sent to a group subcommand may only parse the parent command and not the subcommands due to it being invoked once per Bot.invoke() call.

Note

This function can either be a regular function or a coroutine.

Similar to a command check(), this takes a single parameter of type Context and can only raise exceptions inherited from CommandError.

Example

@bot.check_once
def whitelist(ctx):
    return ctx.message.author.id in my_whitelist
@command(*args, **kwargs)[source]

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

Returns:

A decorator that converts the provided method into a Command, adds it to the bot, then returns it.

Return type:

Callable[…, Command]

@slash_command(*args, **kwargs)[source]

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

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the slash command (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • description (Optional[Union[str, Localized]]) –

    The description of the slash command. It will be visible in Discord.

    Changed in version 2.5: Added support for localizations.

  • options (List[Option]) – The list of slash command options. The options will be visible in Discord. This is the old way of specifying options. Consider using Parameters instead.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • nsfw (bool) –

    Whether this command is age-restricted. Defaults to False.

    New in version 2.8.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • connectors (Dict[str, str]) – Binds function names to option names. If the name of an option already matches the corresponding function param, you don’t have to specify the connectors. Connectors template: {"option-name": "param_name", ...}. If you’re using Parameters, you don’t need to specify this.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableSlashCommand, adds it to the bot, then returns it.

Return type:

Callable[…, InvokableSlashCommand]

@user_command(*args, **kwargs)[source]

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

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the user command (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • nsfw (bool) –

    Whether this command is age-restricted. Defaults to False.

    New in version 2.8.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True.

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableUserCommand, adds it to the bot, then returns it.

Return type:

Callable[…, InvokableUserCommand]

@message_command(*args, **kwargs)[source]

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

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the message command (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • nsfw (bool) –

    Whether this command is age-restricted. Defaults to False.

    New in version 2.8.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableMessageCommand, adds it to the bot, then returns it.

Return type:

Callable[…, InvokableMessageCommand]

@event[source]

A decorator that registers an event to listen to.

You can find more info about the events on the documentation below.

The events must be a coroutine, if not, TypeError is raised.

Example

@client.event
async def on_ready():
    print('Ready!')
Raises:

TypeError – The coroutine passed is not actually a coroutine.

@group(*args, **kwargs)[source]

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

Returns:

A decorator that converts the provided method into a Group, adds it to the bot, then returns it.

Return type:

Callable[…, Group]

@listen(name=None)[source]

A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as on_ready()

The functions being listened to must be a coroutine.

Example

@bot.listen()
async def on_message(message):
    print('one')

# in some other file...

@bot.listen('on_message')
async def my_message(message):
    print('two')

# in yet another file
@bot.listen(Event.message)
async def another_message(message):
    print('three')

Would print one, two and three in an unspecified order.

Raises:

TypeError – The function being listened to is not a coroutine or a string or an Event was not passed as the name.

property activity[source]

The activity being used upon logging in.

Type:

Optional[BaseActivity]

add_app_command_check(func, *, call_once=False, slash_commands=False, user_commands=False, message_commands=False)[source]

Adds a global application command check to the bot.

This is the non-decorator interface to check(), check_once(), slash_command_check() and etc.

You must specify at least one of the bool parameters, otherwise the check won’t be added.

Parameters:
  • func – The function that will be used as a global check.

  • call_once (bool) – Whether the function should only be called once per InvokableApplicationCommand.invoke() call.

  • slash_commands (bool) – Whether this check is for slash commands.

  • user_commands (bool) – Whether this check is for user commands.

  • message_commands (bool) – Whether this check is for message commands.

add_check(func, *, call_once=False)[source]

Adds a global check to the bot.

This is for text commands only, and doesn’t apply to application commands.

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

Parameters:
  • func – The function that was used as a global check.

  • call_once (bool) – If the function should only be called once per invoke() call.

add_cog(cog, *, override=False)[source]

Adds a “cog” to the bot.

A cog is a class that has its own event listeners and commands.

Changed in version 2.0: ClientException is raised when a cog with the same name is already loaded.

Parameters:
  • cog (Cog) – The cog to register to the bot.

  • override (bool) –

    If a previously loaded cog with the same name should be ejected instead of raising an error.

    New in version 2.0.

Raises:
add_command(command)[source]

Adds a Command into the internal list of commands.

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

Changed in version 1.4: Raise CommandRegistrationError instead of generic ClientException

Parameters:

command (Command) – The command to add.

Raises:
add_listener(func, name=...)[source]

The non decorator alternative to listen().

Parameters:
  • func (coroutine) – The function to call.

  • name (Union[str, Event]) – The name of the event to listen for. Defaults to func.__name__.

Example

async def on_ready(): pass
async def my_message(message): pass
async def another_message(message): pass

bot.add_listener(on_ready)
bot.add_listener(my_message, 'on_message')
bot.add_listener(another_message, Event.message)
Raises:

TypeError – The function is not a coroutine or a string or an Event was not passed as the name.

add_message_command(message_command)[source]

Adds an InvokableMessageCommand into the internal list of message commands.

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

Parameters:

message_command (InvokableMessageCommand) – The message command to add.

Raises:
add_slash_command(slash_command)[source]

Adds an InvokableSlashCommand into the internal list of slash commands.

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

Parameters:

slash_command (InvokableSlashCommand) – The slash command to add.

Raises:
add_user_command(user_command)[source]

Adds an InvokableUserCommand into the internal list of user commands.

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

Parameters:

user_command (InvokableUserCommand) – The user command to add.

Raises:
add_view(view, *, message_id=None)[source]

Registers a View for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

New in version 2.0.

Parameters:
  • view (disnake.ui.View) – The view to register for dispatching.

  • message_id (Optional[int]) – The message ID that the view is attached to. This is currently used to refresh the view’s state during message update events. If not given then message update events are not propagated for the view.

Raises:
  • TypeError – A view was not passed.

  • ValueError – The view is not persistent. A persistent view has no timeout and all their components have an explicitly provided custom_id.

property allowed_mentions[source]

The allowed mention configuration.

New in version 1.4.

Type:

Optional[AllowedMentions]

application_command_check(*, call_once=False, slash_commands=False, user_commands=False, message_commands=False)[source]

A decorator that adds a global application command check to the bot.

A global check is similar to a check() that is applied on a per command basis except it is run before any application command checks have been verified and applies to every application command the bot has.

Note

This function can either be a regular function or a coroutine.

Similar to a command check(), this takes a single parameter of type ApplicationCommandInteraction and can only raise exceptions inherited from CommandError.

Example

@bot.application_command_check()
def check_app_commands(inter):
    return inter.channel_id in whitelisted_channels
Parameters:
  • call_once (bool) – Whether the function should only be called once per InvokableApplicationCommand.invoke() call.

  • slash_commands (bool) – Whether this check is for slash commands.

  • user_commands (bool) – Whether this check is for user commands.

  • message_commands (bool) – Whether this check is for message commands.

property application_commands[source]

A set of all application commands the bot has.

Type:

Set[InvokableApplicationCommand]

property application_flags[source]

The client’s application flags.

New in version 2.0.

Type:

ApplicationFlags

property application_id[source]

The client’s application ID.

If this is not passed via __init__ then this is retrieved through the gateway when an event contains the data. Usually after on_connect() is called.

New in version 2.0.

Type:

Optional[int]

await application_info()[source]

This function is a coroutine.

Retrieves the bot’s application information.

Raises:

HTTPException – Retrieving the information failed somehow.

Returns:

The bot’s application information.

Return type:

AppInfo

await before_identify_hook(shard_id, *, initial=False)[source]

This function is a coroutine.

A hook that is called before IDENTIFYing a session. This is useful if you wish to have more control over the synchronization of multiple IDENTIFYing clients.

The default implementation sleeps for 5 seconds.

New in version 1.4.

Parameters:
  • shard_id (int) – The shard ID that requested being IDENTIFY’d

  • initial (bool) – Whether this IDENTIFY is the first initial IDENTIFY.

await bulk_fetch_command_permissions(guild_id)[source]

This function is a coroutine.

Retrieves a list of GuildApplicationCommandPermissions configured for the guild with the given ID.

New in version 2.1.

Parameters:

guild_id (int) – The ID of the guild to inspect.

await bulk_overwrite_global_commands(application_commands)[source]

This function is a coroutine.

Overwrites several global application commands in one API request.

New in version 2.1.

Parameters:

application_commands (List[ApplicationCommand]) – A list of application commands to insert instead of the existing commands.

Returns:

A list of registered application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await bulk_overwrite_guild_commands(guild_id, application_commands)[source]

This function is a coroutine.

Overwrites several guild application commands in one API request.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the application commands should be overwritten.

  • application_commands (List[ApplicationCommand]) – A list of application commands to insert instead of the existing commands.

Returns:

A list of registered application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

property cached_messages[source]

Read-only list of messages the connected client has cached.

New in version 1.1.

Type:

Sequence[Message]

await change_presence(*, activity=None, status=None)[source]

This function is a coroutine.

Changes the client’s presence.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Example

game = disnake.Game("with the API")
await client.change_presence(status=disnake.Status.idle, activity=game)

Changed in version 2.0: Removed the afk keyword-only parameter.

Parameters:
  • activity (Optional[BaseActivity]) – The activity being done. None if no currently active activity is done.

  • status (Optional[Status]) – Indicates what status to change to. If None, then Status.online is used.

Raises:

TypeError – If the activity parameter is not the proper type.

clear()[source]

Clears the internal state of the bot.

After this, the bot can be considered “re-opened”, i.e. is_closed() and is_ready() both return False along with the bot’s internal cache cleared.

await close()[source]

This function is a coroutine.

Closes the connection to Discord.

property cogs[source]

A read-only mapping of cog name to cog.

Type:

Mapping[str, Cog]

property command_sync_flags[source]

The command sync flags configured for this bot.

New in version 2.7.

Type:

CommandSyncFlags

property commands[source]

A unique set of commands without aliases that are registered.

Type:

Set[Command]

await connect(*, reconnect=True, ignore_session_start_limit=False)[source]

This function is a coroutine.

Creates a websocket connection and lets the websocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated.

Changed in version 2.6: Added usage of SessionStartLimit when connecting to the API. Added the ignore_session_start_limit parameter.

Parameters:
  • reconnect (bool) – Whether reconnecting should be attempted, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).

  • ignore_session_start_limit (bool) –

    Whether the API provided session start limit should be ignored when connecting to the API.

    New in version 2.6.

Raises:
  • GatewayNotFound – If the gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage.

  • ConnectionClosed – The websocket connection has been terminated.

  • SessionStartLimitReached – If the client doesn’t have enough connects remaining in the current 24-hour window and ignore_session_start_limit is False this will be raised rather than connecting to the gateawy and Discord resetting the token. However, if ignore_session_start_limit is True, the client will connect regardless and this exception will not be raised.

await create_dm(user)[source]

This function is a coroutine.

Creates a DMChannel with the given user.

This should be rarely called, as this is done transparently for most people.

New in version 2.0.

Parameters:

user (Snowflake) – The user to create a DM with.

Returns:

The channel that was created.

Return type:

DMChannel

await create_global_command(application_command)[source]

This function is a coroutine.

Creates a global application command.

New in version 2.1.

Parameters:

application_command (ApplicationCommand) – An object representing the application command to create.

Returns:

The application command that was created.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await create_guild(*, name, icon=..., code=...)[source]

This function is a coroutine.

Creates a Guild.

See guild_builder() for a more comprehensive alternative.

Bot accounts in 10 or more guilds are not allowed to create guilds.

Changed in version 2.5: Removed the region parameter.

Changed in version 2.6: Raises ValueError instead of InvalidArgument.

Parameters:
Raises:
Returns:

The created guild. This is not the same guild that is added to cache.

Return type:

Guild

await create_guild_command(guild_id, application_command)[source]

This function is a coroutine.

Creates a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the application command should be created.

  • application_command (ApplicationCommand) – The application command.

Returns:

The newly created application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await delete_global_command(command_id)[source]

This function is a coroutine.

Deletes a global application command.

New in version 2.1.

Parameters:

command_id (int) – The ID of the application command to delete.

await delete_guild_command(guild_id, command_id)[source]

This function is a coroutine.

Deletes a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the applcation command should be deleted.

  • command_id (int) – The ID of the application command to delete.

await delete_invite(invite)[source]

This function is a coroutine.

Revokes an Invite, URL, or ID to an invite.

You must have manage_channels permission in the associated guild to do this.

Parameters:

invite (Union[Invite, str]) – The invite to revoke.

Raises:
  • Forbidden – You do not have permissions to revoke invites.

  • NotFound – The invite is invalid or expired.

  • HTTPException – Revoking the invite failed.

await edit_global_command(command_id, new_command)[source]

This function is a coroutine.

Edits a global application command.

New in version 2.1.

Parameters:
  • command_id (int) – The ID of the application command to edit.

  • new_command (ApplicationCommand) – An object representing the edited application command.

Returns:

The edited application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await edit_guild_command(guild_id, command_id, new_command)[source]

This function is a coroutine.

Edits a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the application command should be edited.

  • command_id (int) – The ID of the application command to edit.

  • new_command (ApplicationCommand) – An object representing the edited application command.

Returns:

The newly edited application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await edit_role_connection_metadata(records)[source]

This function is a coroutine.

Edits the ApplicationRoleConnectionMetadata records for the application.

An application can have up to 5 metadata records.

Warning

This will overwrite all existing metadata records. Consider fetching them first, and constructing the new list of metadata records based off of the returned list.

New in version 2.8.

Parameters:

records (Sequence[ApplicationRoleConnectionMetadata]) – The new metadata records.

Raises:

HTTPException – Editing the metadata records failed.

Returns:

The list of newly edited metadata records.

Return type:

List[ApplicationRoleConnectionMetadata]

property emojis[source]

The emojis that the connected client has.

Type:

List[Emoji]

property extensions[source]

A read-only mapping of extension name to extension.

Type:

Mapping[str, types.ModuleType]

await fetch_channel(channel_id, /)[source]

This function is a coroutine.

Retrieves a abc.GuildChannel, abc.PrivateChannel, or Thread with the specified ID.

Note

This method is an API call. For general usage, consider get_channel() instead.

New in version 1.2.

Parameters:

channel_id (int) – The ID of the channel to retrieve.

Raises:
  • InvalidData – An unknown channel type was received from Discord.

  • HTTPException – Retrieving the channel failed.

  • NotFound – Invalid Channel ID.

  • Forbidden – You do not have permission to fetch this channel.

Returns:

The channel from the ID.

Return type:

Union[abc.GuildChannel, abc.PrivateChannel, Thread]

await fetch_command_permissions(guild_id, command_id)[source]

This function is a coroutine.

Retrieves GuildApplicationCommandPermissions for a specific application command in the guild with the given ID.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild to inspect.

  • command_id (int) –

    The ID of the application command, or the application ID to fetch application-wide permissions.

    Changed in version 2.5: Can now also fetch application-wide permissions.

Returns:

The permissions configured for the specified application command.

Return type:

GuildApplicationCommandPermissions

await fetch_global_command(command_id)[source]

This function is a coroutine.

Retrieves a global application command.

New in version 2.1.

Parameters:

command_id (int) – The ID of the command to retrieve.

Returns:

The requested application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await fetch_global_commands(*, with_localizations=True)[source]

This function is a coroutine.

Retrieves a list of global application commands.

New in version 2.1.

Parameters:

with_localizations (bool) –

Whether to include localizations in the response. Defaults to True.

New in version 2.5.

Returns:

A list of application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await fetch_guild(guild_id, /)[source]

This function is a coroutine.

Retrieves a Guild from the given ID.

Note

Using this, you will not receive Guild.channels, Guild.members, Member.activity and Member.voice per Member.

Note

This method is an API call. For general usage, consider get_guild() instead.

Parameters:

guild_id (int) – The ID of the guild to retrieve.

Raises:
Returns:

The guild from the given ID.

Return type:

Guild

await fetch_guild_command(guild_id, command_id)[source]

This function is a coroutine.

Retrieves a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild to fetch command from.

  • command_id (int) – The ID of the application command to retrieve.

Returns:

The requested application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await fetch_guild_commands(guild_id, *, with_localizations=True)[source]

This function is a coroutine.

Retrieves a list of guild application commands.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild to fetch commands from.

  • with_localizations (bool) –

    Whether to include localizations in the response. Defaults to True.

    New in version 2.5.

Returns:

A list of application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await fetch_guild_preview(guild_id, /)[source]

This function is a coroutine.

Retrieves a GuildPreview from the given ID. Your bot does not have to be in this guild.

Note

This method may fetch any guild that has DISCOVERABLE in Guild.features, but this information can not be known ahead of time.

This will work for any guild that you are in.

Parameters:

guild_id (int) – The ID of the guild to to retrieve a preview object.

Raises:

NotFound – Retrieving the guild preview failed.

Returns:

The guild preview from the given ID.

Return type:

GuildPreview

fetch_guilds(*, limit=100, before=None, after=None)[source]

Retrieves an AsyncIterator that enables receiving your guilds.

Note

Using this, you will only receive Guild.owner, Guild.icon, Guild.id, and Guild.name per Guild.

Note

This method is an API call. For general usage, consider guilds instead.

Examples

Usage

async for guild in client.fetch_guilds(limit=150):
    print(guild.name)

Flattening into a list

guilds = await client.fetch_guilds(limit=150).flatten()
# guilds is now a list of Guild...

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of guilds to retrieve. If None, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to 100.

  • before (Union[abc.Snowflake, datetime.datetime]) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Union[abc.Snowflake, datetime.datetime]) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

Raises:

HTTPException – Retrieving the guilds failed.

Yields:

Guild – The guild with the guild data parsed.

await fetch_invite(url, *, with_counts=True, with_expiration=True, guild_scheduled_event_id=None)[source]

This function is a coroutine.

Retrieves an Invite from a discord.gg URL or ID.

Note

If the invite is for a guild you have not joined, the guild and channel attributes of the returned Invite will be PartialInviteGuild and PartialInviteChannel respectively.

Parameters:
  • url (Union[Invite, str]) – The Discord invite ID or URL (must be a discord.gg URL).

  • with_counts (bool) – Whether to include count information in the invite. This fills the Invite.approximate_member_count and Invite.approximate_presence_count fields.

  • with_expiration (bool) –

    Whether to include the expiration date of the invite. This fills the Invite.expires_at field.

    New in version 2.0.

  • guild_scheduled_event_id (int) –

    The ID of the scheduled event to include in the invite. If not provided, defaults to the event parameter in the URL if it exists, or the ID of the scheduled event contained in the provided invite object.

    New in version 2.3.

Raises:
Returns:

The invite from the URL/ID.

Return type:

Invite

await fetch_premium_sticker_packs()[source]

This function is a coroutine.

Retrieves all available premium sticker packs.

New in version 2.0.

Raises:

HTTPException – Retrieving the sticker packs failed.

Returns:

All available premium sticker packs.

Return type:

List[StickerPack]

await fetch_role_connection_metadata()[source]

This function is a coroutine.

Retrieves the ApplicationRoleConnectionMetadata records for the application.

New in version 2.8.

Raises:

HTTPException – Retrieving the metadata records failed.

Returns:

The list of metadata records.

Return type:

List[ApplicationRoleConnectionMetadata]

await fetch_stage_instance(channel_id, /)[source]

This function is a coroutine.

Retrieves a StageInstance with the given ID.

Note

This method is an API call. For general usage, consider get_stage_instance() instead.

New in version 2.0.

Parameters:

channel_id (int) – The stage channel ID.

Raises:
  • NotFound – The stage instance or channel could not be found.

  • HTTPException – Retrieving the stage instance failed.

Returns:

The stage instance from the given ID.

Return type:

StageInstance

await fetch_sticker(sticker_id, /)[source]

This function is a coroutine.

Retrieves a Sticker with the given ID.

New in version 2.0.

Parameters:

sticker_id (int) – The ID of the sticker to retrieve.

Raises:
Returns:

The sticker you requested.

Return type:

Union[StandardSticker, GuildSticker]

await fetch_template(code)[source]

This function is a coroutine.

Retrieves a Template from a discord.new URL or code.

Parameters:

code (Union[Template, str]) – The Discord Template Code or URL (must be a discord.new URL).

Raises:
Returns:

The template from the URL/code.

Return type:

Template

await fetch_user(user_id, /)[source]

This function is a coroutine.

Retrieves a User based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

This method is an API call. If you have disnake.Intents.members and member cache enabled, consider get_user() instead.

Parameters:

user_id (int) – The ID of the user to retrieve.

Raises:
Returns:

The user you requested.

Return type:

User

await fetch_voice_regions(guild_id=None)[source]

Retrieves a list of VoiceRegions.

Retrieves voice regions for the user, or a guild if provided.

New in version 2.5.

Parameters:

guild_id (Optional[int]) – The guild to get regions for, if provided.

Raises:
  • HTTPException – Retrieving voice regions failed.

  • NotFound – The provided guild_id could not be found.

await fetch_webhook(webhook_id, /)[source]

This function is a coroutine.

Retrieves a Webhook with the given ID.

Parameters:

webhook_id (int) – The ID of the webhook to retrieve.

Raises:
Returns:

The webhook you requested.

Return type:

Webhook

await fetch_widget(guild_id, /)[source]

This function is a coroutine.

Retrieves a Widget for the given guild ID.

Note

The guild must have the widget enabled to get this information.

Parameters:

guild_id (int) – The ID of the guild.

Raises:
Returns:

The guild’s widget.

Return type:

Widget

for ... in get_all_channels()[source]

A generator that retrieves every abc.GuildChannel the client can ‘access’.

This is equivalent to:

for guild in client.guilds:
    for channel in guild.channels:
        yield channel

Note

Just because you receive a abc.GuildChannel does not mean that you can communicate in said channel. abc.GuildChannel.permissions_for() should be used for that.

Yields:

abc.GuildChannel – A channel the client can ‘access’.

for ... in get_all_members()[source]

Returns a generator with every Member the client can see.

This is equivalent to:

for guild in client.guilds:
    for member in guild.members:
        yield member
Yields:

Member – A member the client can see.

get_channel(id, /)[source]

Returns a channel or thread with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The returned channel or None if not found.

Return type:

Optional[Union[abc.GuildChannel, Thread, abc.PrivateChannel]]

get_cog(name)[source]

Gets the cog instance requested.

If the cog is not found, None is returned instead.

Parameters:

name (str) – The name of the cog you are requesting. This is equivalent to the name passed via keyword argument in class creation or the class name if unspecified.

Returns:

The cog that was requested. If not found, returns None.

Return type:

Optional[Cog]

get_command(name)[source]

Get a Command from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. 'foo bar') will get the subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

Parameters:

name (str) – The name of the command to get.

Returns:

The command that was requested. If not found, returns None.

Return type:

Optional[Command]

await get_context(message, *, cls=<class 'disnake.ext.commands.context.Context'>)[source]

This function is a coroutine.

Returns the invocation context from the message.

This is a more low-level counter-part for process_commands() to allow users more fine grained control over the processing.

The returned context is not guaranteed to be a valid invocation context, Context.valid must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under invoke().

Parameters:
  • message (disnake.Message) – The message to get the invocation context from.

  • cls – The factory class that will be used to create the context. By default, this is Context. Should a custom class be provided, it must be similar enough to Context’s interface.

Returns:

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

Return type:

Context

get_emoji(id, /)[source]

Returns an emoji with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The custom emoji or None if not found.

Return type:

Optional[Emoji]

get_global_command(id)[source]

Returns a global application command with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_global_command_named(name, cmd_type=None)[source]

Returns a global application command matching the given name.

Parameters:
  • name (str) – The name to look for.

  • cmd_type (ApplicationCommandType) – The type to look for. By default, no types are checked.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild(id, /)[source]

Returns a guild with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The guild or None if not found.

Return type:

Optional[Guild]

get_guild_application_commands(guild_id)[source]

Returns a list of all application commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild_command(guild_id, id)[source]

Returns a guild application command with the given guild ID and application command ID.

Parameters:
  • guild_id (int) – The guild ID to search for.

  • id (int) – The command ID to search for.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild_command_named(guild_id, name, cmd_type=None)[source]

Returns a guild application command matching the given name.

Parameters:
  • guild_id (int) – The guild ID to search for.

  • name (str) – The command name to search for.

  • cmd_type (ApplicationCommandType) – The type to look for. By default, no types are checked.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild_message_commands(guild_id)[source]

Returns a list of all message commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of message commands.

Return type:

List[APIMessageCommand]

get_guild_slash_commands(guild_id)[source]

Returns a list of all slash commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of slash commands.

Return type:

List[APISlashCommand]

get_guild_user_commands(guild_id)[source]

Returns a list of all user commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of user commands.

Return type:

List[APIUserCommand]

get_message(id)[source]

Gets the message with the given ID from the bot’s message cache.

Parameters:

id (int) – The ID of the message to look for.

Returns:

The corresponding message.

Return type:

Optional[Message]

get_message_command(name)[source]

Gets an InvokableMessageCommand from the internal list of message commands.

Parameters:

name (str) – The name of the message command to get.

Returns:

The message command that was requested. If not found, returns None.

Return type:

Optional[InvokableMessageCommand]

await get_or_fetch_user(user_id, *, strict=False)[source]

This function is a coroutine.

Tries to get the user from the cache. If fails, it tries to fetch the user from the API.

Parameters:
  • user_id (int) – The ID to search for.

  • strict (bool) – Whether to propagate exceptions from fetch_user() instead of returning None in case of failure (e.g. if the user wasn’t found). Defaults to False.

Returns:

The user with the given ID, or None if not found and strict is set to False.

Return type:

Optional[User]

get_partial_messageable(id, *, type=None)[source]

Returns a partial messageable with the given channel ID.

This is useful if you have a channel_id but don’t want to do an API call to send messages to it.

New in version 2.0.

Parameters:
  • id (int) – The channel ID to create a partial messageable for.

  • type (Optional[ChannelType]) – The underlying channel type for the partial messageable.

Returns:

The partial messageable

Return type:

PartialMessageable

await get_prefix(message)[source]

This function is a coroutine.

Retrieves the prefix the bot is listening to with the message as a context.

Parameters:

message (disnake.Message) – The message context to get the prefix of.

Returns:

A list of prefixes or a single prefix that the bot is listening for. None if the bot isn’t listening for prefixes.

Return type:

Optional[Union[List[str], str]]

get_slash_command(name)[source]

Works like Bot.get_command, but for slash commands.

If the name contains spaces, then it will assume that you are looking for a SubCommand or a SubCommandGroup. e.g: 'foo bar' will get the sub command group, or the sub command bar of the top-level slash command foo if found, otherwise None.

Parameters:

name (str) – The name of the slash command to get.

Raises:

TypeError – The name is not a string.

Returns:

The slash command that was requested. If not found, returns None.

Return type:

Optional[Union[InvokableSlashCommand, SubCommandGroup, SubCommand]]

get_stage_instance(id, /)[source]

Returns a stage instance with the given stage channel ID.

New in version 2.0.

Parameters:

id (int) – The ID to search for.

Returns:

The returns stage instance or None if not found.

Return type:

Optional[StageInstance]

get_sticker(id, /)[source]

Returns a guild sticker with the given ID.

New in version 2.0.

Note

To retrieve standard stickers, use fetch_sticker(). or fetch_premium_sticker_packs().

Returns:

The sticker or None if not found.

Return type:

Optional[GuildSticker]

get_user(id, /)[source]

Returns a user with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The user or None if not found.

Return type:

Optional[User]

get_user_command(name)[source]

Gets an InvokableUserCommand from the internal list of user commands.

Parameters:

name (str) – The name of the user command to get.

Returns:

The user command that was requested. If not found, returns None.

Return type:

Optional[InvokableUserCommand]

await getch_user(user_id, *, strict=False)[source]

This function is a coroutine.

Tries to get the user from the cache. If fails, it tries to fetch the user from the API.

Parameters:
  • user_id (int) – The ID to search for.

  • strict (bool) – Whether to propagate exceptions from fetch_user() instead of returning None in case of failure (e.g. if the user wasn’t found). Defaults to False.

Returns:

The user with the given ID, or None if not found and strict is set to False.

Return type:

Optional[User]

property global_application_commands[source]

The client’s global application commands.

Type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]

property global_message_commands[source]

The client’s global message commands.

Type:

List[APIMessageCommand]

property global_slash_commands[source]

The client’s global slash commands.

Type:

List[APISlashCommand]

property global_user_commands[source]

The client’s global user commands.

Type:

List[APIUserCommand]

guild_builder(name)[source]

Creates a builder object that can be used to create more complex guilds.

This is a more comprehensive alternative to create_guild(). See GuildBuilder for details and examples.

Bot accounts in 10 or more guilds are not allowed to create guilds.

New in version 2.8.

Parameters:

name (str) – The name of the guild.

Returns:

The guild builder object for configuring and creating a new guild.

Return type:

GuildBuilder

property guilds[source]

The guilds that the connected client is a member of.

Type:

List[Guild]

property intents[source]

The intents configured for this connection.

New in version 1.5.

Type:

Intents

await invoke(ctx)[source]

This function is a coroutine.

Invokes the command given under the invocation context and handles all the internal event dispatch mechanisms.

Parameters:

ctx (Context) – The invocation context to invoke.

is_closed()[source]

Whether the websocket connection is closed.

Return type:

bool

await is_owner(user)[source]

This function is a coroutine.

Checks if a User or Member is the owner of this bot.

If an owner_id is not set, it is fetched automatically through the use of application_info().

Changed in version 1.3: The function also checks if the application is team-owned if owner_ids is not set.

Parameters:

user (abc.User) – The user to check for.

Returns:

Whether the user is the owner.

Return type:

bool

is_ready()[source]

Whether the client’s internal cache is ready for use.

Return type:

bool

is_ws_ratelimited()[source]

Whether the websocket is currently rate limited.

This can be useful to know when deciding whether you should query members using HTTP or via the gateway.

New in version 1.6.

Return type:

bool

property latency[source]

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.

Type:

float

load_extension(name, *, package=None)[source]

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, setup defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the bot.

Parameters:
  • name (str) – The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) –

    The package name to resolve relative imports with. This is required when loading an extension using a relative path, e.g .foo.test. Defaults to None.

    New in version 1.7.

Raises:
  • ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package parameter.

  • ExtensionAlreadyLoaded – The extension is already loaded.

  • NoEntryPointError – The extension does not have a setup function.

  • ExtensionFailed – The extension or its setup function had an execution error.

load_extensions(path)[source]

Loads all extensions in a directory.

New in version 2.4.

Parameters:

path (str) – The path to search for extensions

await login(token)[source]

This function is a coroutine.

Logs in the client with the specified credentials.

Parameters:

token (str) – The authentication token. Do not prefix this token with anything as the library will do it for you.

Raises:
  • LoginFailure – The wrong credentials are passed.

  • HTTPException – An unknown HTTP related error occurred, usually when it isn’t 200 or the known incorrect credentials passing status code.

message_command_check(func)[source]

Similar to check() but for message commands.

message_command_check_once(func)[source]

Similar to check_once() but for message commands.

property message_commands[source]

A set of all message commands the bot has.

Type:

Set[InvokableMessageCommand]

await on_command_error(context, exception)[source]

This function is a coroutine.

The default command error handler provided by the bot.

This is for text commands only, and doesn’t apply to application commands.

By default this prints to sys.stderr however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for command error.

await on_error(event_method, *args, **kwargs)[source]

This function is a coroutine.

The default error handler provided by the client.

By default this prints to sys.stderr however it could be overridden to have a different implementation. Check on_error() for more details.

await on_gateway_error(event, data, shard_id, exc, /)[source]

This function is a coroutine.

The default gateway error handler provided by the client.

By default this prints to sys.stderr however it could be overridden to have a different implementation. Check on_gateway_error() for more details.

New in version 2.6.

Note

Unlike on_error(), the exception is available as the exc parameter and cannot be obtained through sys.exc_info().

await on_message_command_error(interaction, exception)[source]

This function is a coroutine.

Similar to on_slash_command_error() but for message commands.

await on_slash_command_error(interaction, exception)[source]

This function is a coroutine.

The default slash 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 slash command error.

await on_user_command_error(interaction, exception)[source]

This function is a coroutine.

Similar to on_slash_command_error() but for user commands.

property persistent_views[source]

A sequence of persistent views added to the client.

New in version 2.0.

Type:

Sequence[View]

property private_channels[source]

The private channels that the connected client is participating on.

Note

This returns only up to 128 most recent private channels due to an internal working on how Discord deals with private channels.

Type:

List[abc.PrivateChannel]

await process_app_command_autocompletion(inter)[source]

This function is a coroutine.

This function processes the application command autocompletions. Without this coroutine, none of the autocompletions will be performed.

By default, this coroutine is called inside the on_application_command_autocomplete() event. If you choose to override the on_application_command_autocomplete() event, then you should invoke this coroutine as well.

Parameters:

inter (disnake.ApplicationCommandInteraction) – The interaction to process.

await process_application_commands(interaction)[source]

This function is a coroutine.

This function processes the application commands that have been registered to the bot and other groups. Without this coroutine, none of the application commands will be triggered.

By default, this coroutine is called inside the on_application_command() event. If you choose to override the on_application_command() event, then you should invoke this coroutine as well.

Parameters:

interaction (disnake.ApplicationCommandInteraction) – The interaction to process commands for.

await process_commands(message)[source]

This function is a coroutine.

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the on_message() event. If you choose to override the on_message() event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to get_context() followed by a call to invoke().

This also checks if the message’s author is a bot and doesn’t call get_context() or invoke() if so.

Parameters:

message (disnake.Message) – The message to process commands for.

reload_extension(name, *, package=None)[source]

Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a unload_extension() followed by a load_extension() except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.

Parameters:
  • name (str) – The extension name to reload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) –

    The package name to resolve relative imports with. This is required when reloading an extension using a relative path, e.g .foo.test. Defaults to None.

    New in version 1.7.

Raises:
  • ExtensionNotLoaded – The extension was not loaded.

  • ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package parameter.

  • NoEntryPointError – The extension does not have a setup function.

  • ExtensionFailed – The extension setup function had an execution error.

remove_app_command_check(func, *, call_once=False, slash_commands=False, user_commands=False, message_commands=False)[source]

Removes a global application command check from the bot.

This function is idempotent and will not raise an exception if the function is not in the global checks.

You must specify at least one of the bool parameters, otherwise the check won’t be removed.

Parameters:
  • func – The function to remove from the global checks.

  • call_once (bool) – Whether the function was added with call_once=True in the Bot.add_check() call or using check_once().

  • slash_commands (bool) – Whether this check was for slash commands.

  • user_commands (bool) – Whether this check was for user commands.

  • message_commands (bool) – Whether this check was for message commands.

remove_check(func, *, call_once=False)[source]

Removes a global check from the bot.

This is for text commands only, and doesn’t apply to application commands.

This function is idempotent and will not raise an exception if the function is not in the global checks.

Parameters:
  • func – The function to remove from the global checks.

  • call_once (bool) – If the function was added with call_once=True in the Bot.add_check() call or using check_once().

remove_cog(name)[source]

Removes a cog from the bot and returns it.

All registered commands and event listeners that the cog has registered will be removed as well.

If no cog is found then this method has no effect.

Parameters:

name (str) – The name of the cog to remove.

Returns:

The cog that was removed. Returns None if not found.

Return type:

Optional[Cog]

remove_command(name)[source]

Remove a Command from the internal list of commands.

This could also be used as a way to remove aliases.

Parameters:

name (str) – The name of the command to remove.

Returns:

The command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[Command]

remove_listener(func, name=...)[source]

Removes a listener from the pool of listeners.

Parameters:
  • func – The function that was used as a listener to remove.

  • name (Union[str, Event]) – The name of the event we want to remove. Defaults to func.__name__.

Raises:

TypeError – The name passed was not a string or an Event.

remove_message_command(name)[source]

Removes an InvokableMessageCommand from the internal list of message commands.

Parameters:

name (str) – The name of the message command to remove.

Returns:

The message command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[InvokableMessageCommand]

remove_slash_command(name)[source]

Removes an InvokableSlashCommand from the internal list of slash commands.

Parameters:

name (str) – The name of the slash command to remove.

Returns:

The slash command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[InvokableSlashCommand]

remove_user_command(name)[source]

Removes an InvokableUserCommand from the internal list of user commands.

Parameters:

name (str) – The name of the user command to remove.

Returns:

The user command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[InvokableUserCommand]

run(*args, **kwargs)[source]

A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use start() coroutine or connect() + login().

Roughly Equivalent to:

try:
    loop.run_until_complete(start(*args, **kwargs))
except KeyboardInterrupt:
    loop.run_until_complete(close())
    # cancel all tasks lingering
finally:
    loop.close()

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.

slash_command_check(func)[source]

Similar to check() but for slash commands.

slash_command_check_once(func)[source]

Similar to check_once() but for slash commands.

property slash_commands[source]

A set of all slash commands the bot has.

Type:

Set[InvokableSlashCommand]

await start(token, *, reconnect=True, ignore_session_start_limit=False)[source]

This function is a coroutine.

A shorthand coroutine for login() + connect().

Raises:

TypeError – An unexpected keyword argument was received.

property status[source]

The status being used upon logging on to Discord.

New in version 2.0.

Type:

Status

property stickers[source]

The stickers that the connected client has.

New in version 2.0.

Type:

List[GuildSticker]

unload_extension(name, *, package=None)[source]

Unloads an extension.

When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported.

The extension can provide an optional global function, teardown, to do miscellaneous clean-up if necessary. This function takes a single parameter, the bot, similar to setup from load_extension().

Parameters:
  • name (str) – The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) –

    The package name to resolve relative imports with. This is required when unloading an extension using a relative path, e.g .foo.test. Defaults to None.

    New in version 1.7.

Raises:
property user[source]

Represents the connected client. None if not logged in.

Type:

Optional[ClientUser]

user_command_check(func)[source]

Similar to check() but for user commands.

user_command_check_once(func)[source]

Similar to check_once() but for user commands.

property user_commands[source]

A set of all user commands the bot has.

Type:

Set[InvokableUserCommand]

property users[source]

Returns a list of all the users the bot can see.

Type:

List[User]

property voice_clients[source]

Represents a list of voice connections.

These are usually VoiceClient instances.

Type:

List[VoiceProtocol]

wait_for(event, *, check=None, timeout=None)[source]

This function is a coroutine.

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The timeout parameter is passed onto asyncio.wait_for(). By default, it does not timeout. Note that this does propagate the asyncio.TimeoutError for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a tuple containing those arguments is returned instead. Please check the documentation for a list of events and their parameters.

This function returns the first event that meets the requirements.

Examples

Waiting for a user reply:

@client.event
async def on_message(message):
    if message.content.startswith('$greet'):
        channel = message.channel
        await channel.send('Say hello!')

        def check(m):
            return m.content == 'hello' and m.channel == channel

        msg = await client.wait_for('message', check=check)
        await channel.send(f'Hello {msg.author}!')

# using events enums:
@client.event
async def on_message(message):
    if message.content.startswith('$greet'):
        channel = message.channel
        await channel.send('Say hello!')

        def check(m):
            return m.content == 'hello' and m.channel == channel

        msg = await client.wait_for(Event.message, check=check)
        await channel.send(f'Hello {msg.author}!')

Waiting for a thumbs up reaction from the message author:

@client.event
async def on_message(message):
    if message.content.startswith('$thumb'):
        channel = message.channel
        await channel.send('Send me that 👍 reaction, mate')

        def check(reaction, user):
            return user == message.author and str(reaction.emoji) == '👍'

        try:
            reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
        except asyncio.TimeoutError:
            await channel.send('👎')
        else:
            await channel.send('👍')
Parameters:
  • event (Union[str, Event]) – The event name, similar to the event reference, but without the on_ prefix, to wait for. It’s recommended to use Event.

  • check (Optional[Callable[…, bool]]) – A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for.

  • timeout (Optional[float]) – The number of seconds to wait before timing out and raising asyncio.TimeoutError.

Raises:

asyncio.TimeoutError – If a timeout is provided and it was reached.

Returns:

Returns no arguments, a single argument, or a tuple of multiple arguments that mirrors the parameters passed in the event reference.

Return type:

Any

await wait_until_first_connect()[source]

This function is a coroutine.

Waits until the first connect.

await wait_until_ready()[source]

This function is a coroutine.

Waits until the client’s internal cache is all ready.

for ... in walk_commands()[source]

An iterator that recursively walks through all commands and subcommands.

Changed in version 1.4: Duplicates due to aliases are no longer returned

Yields:

Union[Command, Group] – A command or group from the internal list of commands.

AutoShardedBot

class disnake.ext.commands.AutoShardedBot(command_prefix=None, help_command=<default-help-command>, description=None, *, strip_after_prefix=False, **options)[source]

This is similar to Bot except that it is inherited from disnake.AutoShardedClient instead.

InteractionBot

Methods
class disnake.ext.commands.InteractionBot(*, command_sync_flags=None, sync_commands=..., sync_commands_debug=..., sync_commands_on_cog_unload=..., test_guilds=None, **options)[source]

Represents a discord bot for application commands only.

This class is a subclass of disnake.Client and as a result anything that you can do with a disnake.Client you can do with this bot.

This class also subclasses InteractionBotBase to provide the functionality to manage application commands.

Parameters:
  • test_guilds (List[int]) –

    The list of IDs of the guilds where you’re going to test your application commands. Defaults to None, which means global registration of commands across all guilds.

    New in version 2.1.

  • command_sync_flags (ext.commands.CommandSyncFlags) –

    The command sync flags for the session. This is a way of controlling when and how application commands will be synced with the Discord API. If not given, defaults to CommandSyncFlags.default().

    New in version 2.7.

  • sync_commands (bool) –

    Whether to enable automatic synchronization of application commands in your code. Defaults to True, which means that commands in API are automatically synced with the commands in your code.

    New in version 2.1.

    Deprecated since version 2.7: Replaced with command_sync_flags.

  • sync_commands_on_cog_unload (bool) –

    Whether to sync the application commands on cog unload / reload. Defaults to True.

    New in version 2.1.

    Deprecated since version 2.7: Replaced with command_sync_flags.

  • sync_commands_debug (bool) –

    Whether to always show sync debug logs (uses INFO log level if it’s enabled, prints otherwise). If disabled, uses the default DEBUG log level which isn’t shown unless the log level is changed manually. Useful for tracking the commands being registered in the API. Defaults to False.

    New in version 2.1.

    Changed in version 2.4: Changes the log level of corresponding messages from DEBUG to INFO or prints them, instead of controlling whether they are enabled at all.

    Deprecated since version 2.7: Replaced with command_sync_flags.

  • localization_provider (LocalizationProtocol) –

    An implementation of LocalizationProtocol to use for localization of application commands. If not provided, the default LocalizationStore implementation is used.

    New in version 2.5.

  • strict_localization (bool) –

    Whether to raise an exception when localizations for a specific key couldn’t be found. This is mainly useful for testing/debugging, consider disabling this eventually as missing localized names will automatically fall back to the default/base name without it. Only applicable if the localization_provider parameter is not provided. Defaults to False.

    New in version 2.5.

owner_id

The user ID that owns the bot. If this is not set and is then queried via is_owner() then it is fetched automatically using application_info().

This can be provided as a parameter at creation.

Type:

Optional[int]

owner_ids

The user IDs that owns the bot. This is similar to owner_id. If this is not set and the application is team based, then it is fetched automatically using application_info(). For performance reasons it is recommended to use a set for the collection. You cannot set both owner_id and owner_ids.

This can be provided as a parameter at creation.

Type:

Optional[Collection[int]]

reload

Whether to enable automatic extension reloading on file modification for debugging. Whenever you save an extension with reloading enabled the file will be automatically reloaded for you so you do not have to reload the extension manually. Defaults to False

This can be provided as a parameter at creation.

New in version 2.1.

Type:

bool

i18n

An implementation of LocalizationProtocol used for localization of application commands.

New in version 2.5.

Type:

LocalizationProtocol

@after_slash_command_invoke[source]

Similar to Bot.after_invoke() but for slash commands, and it takes an ApplicationCommandInteraction as its only parameter.

@after_user_command_invoke[source]

Similar to Bot.after_slash_command_invoke() but for user commands.

@after_message_command_invoke[source]

Similar to Bot.after_slash_command_invoke() but for message commands.

@before_slash_command_invoke[source]

Similar to Bot.before_invoke() but for slash commands, and it takes an ApplicationCommandInteraction as its only parameter.

@before_user_command_invoke[source]

Similar to Bot.before_slash_command_invoke() but for user commands.

@before_message_command_invoke[source]

Similar to Bot.before_slash_command_invoke() but for message commands.

@application_command_check[source]

A decorator that adds a global application command check to the bot.

A global check is similar to a check() that is applied on a per command basis except it is run before any application command checks have been verified and applies to every application command the bot has.

Note

This function can either be a regular function or a coroutine.

Similar to a command check(), this takes a single parameter of type ApplicationCommandInteraction and can only raise exceptions inherited from CommandError.

Example

@bot.application_command_check()
def check_app_commands(inter):
    return inter.channel_id in whitelisted_channels
Parameters:
  • call_once (bool) – Whether the function should only be called once per InvokableApplicationCommand.invoke() call.

  • slash_commands (bool) – Whether this check is for slash commands.

  • user_commands (bool) – Whether this check is for user commands.

  • message_commands (bool) – Whether this check is for message commands.

@slash_command_check[source]

Similar to check() but for slash commands.

@user_command_check[source]

Similar to check() but for user commands.

@message_command_check[source]

Similar to check() but for message commands.

@slash_command_check_once[source]

Similar to check_once() but for slash commands.

@user_command_check_once[source]

Similar to check_once() but for user commands.

@message_command_check_once[source]

Similar to check_once() but for message commands.

@slash_command(*args, **kwargs)[source]

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

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the slash command (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • description (Optional[Union[str, Localized]]) –

    The description of the slash command. It will be visible in Discord.

    Changed in version 2.5: Added support for localizations.

  • options (List[Option]) – The list of slash command options. The options will be visible in Discord. This is the old way of specifying options. Consider using Parameters instead.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • nsfw (bool) –

    Whether this command is age-restricted. Defaults to False.

    New in version 2.8.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • connectors (Dict[str, str]) – Binds function names to option names. If the name of an option already matches the corresponding function param, you don’t have to specify the connectors. Connectors template: {"option-name": "param_name", ...}. If you’re using Parameters, you don’t need to specify this.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableSlashCommand, adds it to the bot, then returns it.

Return type:

Callable[…, InvokableSlashCommand]

@user_command(*args, **kwargs)[source]

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

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the user command (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • nsfw (bool) –

    Whether this command is age-restricted. Defaults to False.

    New in version 2.8.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True.

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableUserCommand, adds it to the bot, then returns it.

Return type:

Callable[…, InvokableUserCommand]

@message_command(*args, **kwargs)[source]

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

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the message command (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • nsfw (bool) –

    Whether this command is age-restricted. Defaults to False.

    New in version 2.8.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableMessageCommand, adds it to the bot, then returns it.

Return type:

Callable[…, InvokableMessageCommand]

@event[source]

A decorator that registers an event to listen to.

You can find more info about the events on the documentation below.

The events must be a coroutine, if not, TypeError is raised.

Example

@client.event
async def on_ready():
    print('Ready!')
Raises:

TypeError – The coroutine passed is not actually a coroutine.

@listen(name=None)[source]

A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as on_ready()

The functions being listened to must be a coroutine.

Example

@bot.listen()
async def on_message(message):
    print('one')

# in some other file...

@bot.listen('on_message')
async def my_message(message):
    print('two')

# in yet another file
@bot.listen(Event.message)
async def another_message(message):
    print('three')

Would print one, two and three in an unspecified order.

Raises:

TypeError – The function being listened to is not a coroutine or a string or an Event was not passed as the name.

property activity[source]

The activity being used upon logging in.

Type:

Optional[BaseActivity]

add_app_command_check(func, *, call_once=False, slash_commands=False, user_commands=False, message_commands=False)[source]

Adds a global application command check to the bot.

This is the non-decorator interface to check(), check_once(), slash_command_check() and etc.

You must specify at least one of the bool parameters, otherwise the check won’t be added.

Parameters:
  • func – The function that will be used as a global check.

  • call_once (bool) – Whether the function should only be called once per InvokableApplicationCommand.invoke() call.

  • slash_commands (bool) – Whether this check is for slash commands.

  • user_commands (bool) – Whether this check is for user commands.

  • message_commands (bool) – Whether this check is for message commands.

add_cog(cog, *, override=False)[source]

Adds a “cog” to the bot.

A cog is a class that has its own event listeners and commands.

Changed in version 2.0: ClientException is raised when a cog with the same name is already loaded.

Parameters:
  • cog (Cog) – The cog to register to the bot.

  • override (bool) –

    If a previously loaded cog with the same name should be ejected instead of raising an error.

    New in version 2.0.

Raises:
add_listener(func, name=...)[source]

The non decorator alternative to listen().

Parameters:
  • func (coroutine) – The function to call.

  • name (Union[str, Event]) – The name of the event to listen for. Defaults to func.__name__.

Example

async def on_ready(): pass
async def my_message(message): pass
async def another_message(message): pass

bot.add_listener(on_ready)
bot.add_listener(my_message, 'on_message')
bot.add_listener(another_message, Event.message)
Raises:

TypeError – The function is not a coroutine or a string or an Event was not passed as the name.

add_message_command(message_command)[source]

Adds an InvokableMessageCommand into the internal list of message commands.

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

Parameters:

message_command (InvokableMessageCommand) – The message command to add.

Raises:
add_slash_command(slash_command)[source]

Adds an InvokableSlashCommand into the internal list of slash commands.

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

Parameters:

slash_command (InvokableSlashCommand) – The slash command to add.

Raises:
add_user_command(user_command)[source]

Adds an InvokableUserCommand into the internal list of user commands.

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

Parameters:

user_command (InvokableUserCommand) – The user command to add.

Raises:
add_view(view, *, message_id=None)[source]

Registers a View for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

New in version 2.0.

Parameters:
  • view (disnake.ui.View) – The view to register for dispatching.

  • message_id (Optional[int]) – The message ID that the view is attached to. This is currently used to refresh the view’s state during message update events. If not given then message update events are not propagated for the view.

Raises:
  • TypeError – A view was not passed.

  • ValueError – The view is not persistent. A persistent view has no timeout and all their components have an explicitly provided custom_id.

property allowed_mentions[source]

The allowed mention configuration.

New in version 1.4.

Type:

Optional[AllowedMentions]

property application_commands[source]

A set of all application commands the bot has.

Type:

Set[InvokableApplicationCommand]

property application_flags[source]

The client’s application flags.

New in version 2.0.

Type:

ApplicationFlags

property application_id[source]

The client’s application ID.

If this is not passed via __init__ then this is retrieved through the gateway when an event contains the data. Usually after on_connect() is called.

New in version 2.0.

Type:

Optional[int]

await application_info()[source]

This function is a coroutine.

Retrieves the bot’s application information.

Raises:

HTTPException – Retrieving the information failed somehow.

Returns:

The bot’s application information.

Return type:

AppInfo

await before_identify_hook(shard_id, *, initial=False)[source]

This function is a coroutine.

A hook that is called before IDENTIFYing a session. This is useful if you wish to have more control over the synchronization of multiple IDENTIFYing clients.

The default implementation sleeps for 5 seconds.

New in version 1.4.

Parameters:
  • shard_id (int) – The shard ID that requested being IDENTIFY’d

  • initial (bool) – Whether this IDENTIFY is the first initial IDENTIFY.

await bulk_fetch_command_permissions(guild_id)[source]

This function is a coroutine.

Retrieves a list of GuildApplicationCommandPermissions configured for the guild with the given ID.

New in version 2.1.

Parameters:

guild_id (int) – The ID of the guild to inspect.

await bulk_overwrite_global_commands(application_commands)[source]

This function is a coroutine.

Overwrites several global application commands in one API request.

New in version 2.1.

Parameters:

application_commands (List[ApplicationCommand]) – A list of application commands to insert instead of the existing commands.

Returns:

A list of registered application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await bulk_overwrite_guild_commands(guild_id, application_commands)[source]

This function is a coroutine.

Overwrites several guild application commands in one API request.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the application commands should be overwritten.

  • application_commands (List[ApplicationCommand]) – A list of application commands to insert instead of the existing commands.

Returns:

A list of registered application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

property cached_messages[source]

Read-only list of messages the connected client has cached.

New in version 1.1.

Type:

Sequence[Message]

await change_presence(*, activity=None, status=None)[source]

This function is a coroutine.

Changes the client’s presence.

Changed in version 2.6: Raises TypeError instead of InvalidArgument.

Example

game = disnake.Game("with the API")
await client.change_presence(status=disnake.Status.idle, activity=game)

Changed in version 2.0: Removed the afk keyword-only parameter.

Parameters:
  • activity (Optional[BaseActivity]) – The activity being done. None if no currently active activity is done.

  • status (Optional[Status]) – Indicates what status to change to. If None, then Status.online is used.

Raises:

TypeError – If the activity parameter is not the proper type.

clear()[source]

Clears the internal state of the bot.

After this, the bot can be considered “re-opened”, i.e. is_closed() and is_ready() both return False along with the bot’s internal cache cleared.

await close()[source]

This function is a coroutine.

Closes the connection to Discord.

property cogs[source]

A read-only mapping of cog name to cog.

Type:

Mapping[str, Cog]

property command_sync_flags[source]

The command sync flags configured for this bot.

New in version 2.7.

Type:

CommandSyncFlags

await connect(*, reconnect=True, ignore_session_start_limit=False)[source]

This function is a coroutine.

Creates a websocket connection and lets the websocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated.

Changed in version 2.6: Added usage of SessionStartLimit when connecting to the API. Added the ignore_session_start_limit parameter.

Parameters:
  • reconnect (bool) – Whether reconnecting should be attempted, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).

  • ignore_session_start_limit (bool) –

    Whether the API provided session start limit should be ignored when connecting to the API.

    New in version 2.6.

Raises:
  • GatewayNotFound – If the gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage.

  • ConnectionClosed – The websocket connection has been terminated.

  • SessionStartLimitReached – If the client doesn’t have enough connects remaining in the current 24-hour window and ignore_session_start_limit is False this will be raised rather than connecting to the gateawy and Discord resetting the token. However, if ignore_session_start_limit is True, the client will connect regardless and this exception will not be raised.

await create_dm(user)[source]

This function is a coroutine.

Creates a DMChannel with the given user.

This should be rarely called, as this is done transparently for most people.

New in version 2.0.

Parameters:

user (Snowflake) – The user to create a DM with.

Returns:

The channel that was created.

Return type:

DMChannel

await create_global_command(application_command)[source]

This function is a coroutine.

Creates a global application command.

New in version 2.1.

Parameters:

application_command (ApplicationCommand) – An object representing the application command to create.

Returns:

The application command that was created.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await create_guild(*, name, icon=..., code=...)[source]

This function is a coroutine.

Creates a Guild.

See guild_builder() for a more comprehensive alternative.

Bot accounts in 10 or more guilds are not allowed to create guilds.

Changed in version 2.5: Removed the region parameter.

Changed in version 2.6: Raises ValueError instead of InvalidArgument.

Parameters:
Raises:
Returns:

The created guild. This is not the same guild that is added to cache.

Return type:

Guild

await create_guild_command(guild_id, application_command)[source]

This function is a coroutine.

Creates a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the application command should be created.

  • application_command (ApplicationCommand) – The application command.

Returns:

The newly created application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await delete_global_command(command_id)[source]

This function is a coroutine.

Deletes a global application command.

New in version 2.1.

Parameters:

command_id (int) – The ID of the application command to delete.

await delete_guild_command(guild_id, command_id)[source]

This function is a coroutine.

Deletes a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the applcation command should be deleted.

  • command_id (int) – The ID of the application command to delete.

await delete_invite(invite)[source]

This function is a coroutine.

Revokes an Invite, URL, or ID to an invite.

You must have manage_channels permission in the associated guild to do this.

Parameters:

invite (Union[Invite, str]) – The invite to revoke.

Raises:
  • Forbidden – You do not have permissions to revoke invites.

  • NotFound – The invite is invalid or expired.

  • HTTPException – Revoking the invite failed.

await edit_global_command(command_id, new_command)[source]

This function is a coroutine.

Edits a global application command.

New in version 2.1.

Parameters:
  • command_id (int) – The ID of the application command to edit.

  • new_command (ApplicationCommand) – An object representing the edited application command.

Returns:

The edited application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await edit_guild_command(guild_id, command_id, new_command)[source]

This function is a coroutine.

Edits a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild where the application command should be edited.

  • command_id (int) – The ID of the application command to edit.

  • new_command (ApplicationCommand) – An object representing the edited application command.

Returns:

The newly edited application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await edit_role_connection_metadata(records)[source]

This function is a coroutine.

Edits the ApplicationRoleConnectionMetadata records for the application.

An application can have up to 5 metadata records.

Warning

This will overwrite all existing metadata records. Consider fetching them first, and constructing the new list of metadata records based off of the returned list.

New in version 2.8.

Parameters:

records (Sequence[ApplicationRoleConnectionMetadata]) – The new metadata records.

Raises:

HTTPException – Editing the metadata records failed.

Returns:

The list of newly edited metadata records.

Return type:

List[ApplicationRoleConnectionMetadata]

property emojis[source]

The emojis that the connected client has.

Type:

List[Emoji]

property extensions[source]

A read-only mapping of extension name to extension.

Type:

Mapping[str, types.ModuleType]

await fetch_channel(channel_id, /)[source]

This function is a coroutine.

Retrieves a abc.GuildChannel, abc.PrivateChannel, or Thread with the specified ID.

Note

This method is an API call. For general usage, consider get_channel() instead.

New in version 1.2.

Parameters:

channel_id (int) – The ID of the channel to retrieve.

Raises:
  • InvalidData – An unknown channel type was received from Discord.

  • HTTPException – Retrieving the channel failed.

  • NotFound – Invalid Channel ID.

  • Forbidden – You do not have permission to fetch this channel.

Returns:

The channel from the ID.

Return type:

Union[abc.GuildChannel, abc.PrivateChannel, Thread]

await fetch_command_permissions(guild_id, command_id)[source]

This function is a coroutine.

Retrieves GuildApplicationCommandPermissions for a specific application command in the guild with the given ID.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild to inspect.

  • command_id (int) –

    The ID of the application command, or the application ID to fetch application-wide permissions.

    Changed in version 2.5: Can now also fetch application-wide permissions.

Returns:

The permissions configured for the specified application command.

Return type:

GuildApplicationCommandPermissions

await fetch_global_command(command_id)[source]

This function is a coroutine.

Retrieves a global application command.

New in version 2.1.

Parameters:

command_id (int) – The ID of the command to retrieve.

Returns:

The requested application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await fetch_global_commands(*, with_localizations=True)[source]

This function is a coroutine.

Retrieves a list of global application commands.

New in version 2.1.

Parameters:

with_localizations (bool) –

Whether to include localizations in the response. Defaults to True.

New in version 2.5.

Returns:

A list of application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await fetch_guild(guild_id, /)[source]

This function is a coroutine.

Retrieves a Guild from the given ID.

Note

Using this, you will not receive Guild.channels, Guild.members, Member.activity and Member.voice per Member.

Note

This method is an API call. For general usage, consider get_guild() instead.

Parameters:

guild_id (int) – The ID of the guild to retrieve.

Raises:
Returns:

The guild from the given ID.

Return type:

Guild

await fetch_guild_command(guild_id, command_id)[source]

This function is a coroutine.

Retrieves a guild application command.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild to fetch command from.

  • command_id (int) – The ID of the application command to retrieve.

Returns:

The requested application command.

Return type:

Union[APIUserCommand, APIMessageCommand, APISlashCommand]

await fetch_guild_commands(guild_id, *, with_localizations=True)[source]

This function is a coroutine.

Retrieves a list of guild application commands.

New in version 2.1.

Parameters:
  • guild_id (int) – The ID of the guild to fetch commands from.

  • with_localizations (bool) –

    Whether to include localizations in the response. Defaults to True.

    New in version 2.5.

Returns:

A list of application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

await fetch_guild_preview(guild_id, /)[source]

This function is a coroutine.

Retrieves a GuildPreview from the given ID. Your bot does not have to be in this guild.

Note

This method may fetch any guild that has DISCOVERABLE in Guild.features, but this information can not be known ahead of time.

This will work for any guild that you are in.

Parameters:

guild_id (int) – The ID of the guild to to retrieve a preview object.

Raises:

NotFound – Retrieving the guild preview failed.

Returns:

The guild preview from the given ID.

Return type:

GuildPreview

fetch_guilds(*, limit=100, before=None, after=None)[source]

Retrieves an AsyncIterator that enables receiving your guilds.

Note

Using this, you will only receive Guild.owner, Guild.icon, Guild.id, and Guild.name per Guild.

Note

This method is an API call. For general usage, consider guilds instead.

Examples

Usage

async for guild in client.fetch_guilds(limit=150):
    print(guild.name)

Flattening into a list

guilds = await client.fetch_guilds(limit=150).flatten()
# guilds is now a list of Guild...

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of guilds to retrieve. If None, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to 100.

  • before (Union[abc.Snowflake, datetime.datetime]) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Union[abc.Snowflake, datetime.datetime]) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

Raises:

HTTPException – Retrieving the guilds failed.

Yields:

Guild – The guild with the guild data parsed.

await fetch_invite(url, *, with_counts=True, with_expiration=True, guild_scheduled_event_id=None)[source]

This function is a coroutine.

Retrieves an Invite from a discord.gg URL or ID.

Note

If the invite is for a guild you have not joined, the guild and channel attributes of the returned Invite will be PartialInviteGuild and PartialInviteChannel respectively.

Parameters:
  • url (Union[Invite, str]) – The Discord invite ID or URL (must be a discord.gg URL).

  • with_counts (bool) – Whether to include count information in the invite. This fills the Invite.approximate_member_count and Invite.approximate_presence_count fields.

  • with_expiration (bool) –

    Whether to include the expiration date of the invite. This fills the Invite.expires_at field.

    New in version 2.0.

  • guild_scheduled_event_id (int) –

    The ID of the scheduled event to include in the invite. If not provided, defaults to the event parameter in the URL if it exists, or the ID of the scheduled event contained in the provided invite object.

    New in version 2.3.

Raises:
Returns:

The invite from the URL/ID.

Return type:

Invite

await fetch_premium_sticker_packs()[source]

This function is a coroutine.

Retrieves all available premium sticker packs.

New in version 2.0.

Raises:

HTTPException – Retrieving the sticker packs failed.

Returns:

All available premium sticker packs.

Return type:

List[StickerPack]

await fetch_role_connection_metadata()[source]

This function is a coroutine.

Retrieves the ApplicationRoleConnectionMetadata records for the application.

New in version 2.8.

Raises:

HTTPException – Retrieving the metadata records failed.

Returns:

The list of metadata records.

Return type:

List[ApplicationRoleConnectionMetadata]

await fetch_stage_instance(channel_id, /)[source]

This function is a coroutine.

Retrieves a StageInstance with the given ID.

Note

This method is an API call. For general usage, consider get_stage_instance() instead.

New in version 2.0.

Parameters:

channel_id (int) – The stage channel ID.

Raises:
  • NotFound – The stage instance or channel could not be found.

  • HTTPException – Retrieving the stage instance failed.

Returns:

The stage instance from the given ID.

Return type:

StageInstance

await fetch_sticker(sticker_id, /)[source]

This function is a coroutine.

Retrieves a Sticker with the given ID.

New in version 2.0.

Parameters:

sticker_id (int) – The ID of the sticker to retrieve.

Raises:
Returns:

The sticker you requested.

Return type:

Union[StandardSticker, GuildSticker]

await fetch_template(code)[source]

This function is a coroutine.

Retrieves a Template from a discord.new URL or code.

Parameters:

code (Union[Template, str]) – The Discord Template Code or URL (must be a discord.new URL).

Raises:
Returns:

The template from the URL/code.

Return type:

Template

await fetch_user(user_id, /)[source]

This function is a coroutine.

Retrieves a User based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

This method is an API call. If you have disnake.Intents.members and member cache enabled, consider get_user() instead.

Parameters:

user_id (int) – The ID of the user to retrieve.

Raises:
Returns:

The user you requested.

Return type:

User

await fetch_voice_regions(guild_id=None)[source]

Retrieves a list of VoiceRegions.

Retrieves voice regions for the user, or a guild if provided.

New in version 2.5.

Parameters:

guild_id (Optional[int]) – The guild to get regions for, if provided.

Raises:
  • HTTPException – Retrieving voice regions failed.

  • NotFound – The provided guild_id could not be found.

await fetch_webhook(webhook_id, /)[source]

This function is a coroutine.

Retrieves a Webhook with the given ID.

Parameters:

webhook_id (int) – The ID of the webhook to retrieve.

Raises:
Returns:

The webhook you requested.

Return type:

Webhook

await fetch_widget(guild_id, /)[source]

This function is a coroutine.

Retrieves a Widget for the given guild ID.

Note

The guild must have the widget enabled to get this information.

Parameters:

guild_id (int) – The ID of the guild.

Raises:
Returns:

The guild’s widget.

Return type:

Widget

for ... in get_all_channels()[source]

A generator that retrieves every abc.GuildChannel the client can ‘access’.

This is equivalent to:

for guild in client.guilds:
    for channel in guild.channels:
        yield channel

Note

Just because you receive a abc.GuildChannel does not mean that you can communicate in said channel. abc.GuildChannel.permissions_for() should be used for that.

Yields:

abc.GuildChannel – A channel the client can ‘access’.

for ... in get_all_members()[source]

Returns a generator with every Member the client can see.

This is equivalent to:

for guild in client.guilds:
    for member in guild.members:
        yield member
Yields:

Member – A member the client can see.

get_channel(id, /)[source]

Returns a channel or thread with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The returned channel or None if not found.

Return type:

Optional[Union[abc.GuildChannel, Thread, abc.PrivateChannel]]

get_cog(name)[source]

Gets the cog instance requested.

If the cog is not found, None is returned instead.

Parameters:

name (str) – The name of the cog you are requesting. This is equivalent to the name passed via keyword argument in class creation or the class name if unspecified.

Returns:

The cog that was requested. If not found, returns None.

Return type:

Optional[Cog]

get_emoji(id, /)[source]

Returns an emoji with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The custom emoji or None if not found.

Return type:

Optional[Emoji]

get_global_command(id)[source]

Returns a global application command with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_global_command_named(name, cmd_type=None)[source]

Returns a global application command matching the given name.

Parameters:
  • name (str) – The name to look for.

  • cmd_type (ApplicationCommandType) – The type to look for. By default, no types are checked.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild(id, /)[source]

Returns a guild with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The guild or None if not found.

Return type:

Optional[Guild]

get_guild_application_commands(guild_id)[source]

Returns a list of all application commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of application commands.

Return type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild_command(guild_id, id)[source]

Returns a guild application command with the given guild ID and application command ID.

Parameters:
  • guild_id (int) – The guild ID to search for.

  • id (int) – The command ID to search for.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild_command_named(guild_id, name, cmd_type=None)[source]

Returns a guild application command matching the given name.

Parameters:
  • guild_id (int) – The guild ID to search for.

  • name (str) – The command name to search for.

  • cmd_type (ApplicationCommandType) – The type to look for. By default, no types are checked.

Returns:

The application command.

Return type:

Optional[Union[APIUserCommand, APIMessageCommand, APISlashCommand]]

get_guild_message_commands(guild_id)[source]

Returns a list of all message commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of message commands.

Return type:

List[APIMessageCommand]

get_guild_slash_commands(guild_id)[source]

Returns a list of all slash commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of slash commands.

Return type:

List[APISlashCommand]

get_guild_user_commands(guild_id)[source]

Returns a list of all user commands in the guild with the given ID.

Parameters:

guild_id (int) – The ID to search for.

Returns:

The list of user commands.

Return type:

List[APIUserCommand]

get_message(id)[source]

Gets the message with the given ID from the bot’s message cache.

Parameters:

id (int) – The ID of the message to look for.

Returns:

The corresponding message.

Return type:

Optional[Message]

get_message_command(name)[source]

Gets an InvokableMessageCommand from the internal list of message commands.

Parameters:

name (str) – The name of the message command to get.

Returns:

The message command that was requested. If not found, returns None.

Return type:

Optional[InvokableMessageCommand]

await get_or_fetch_user(user_id, *, strict=False)[source]

This function is a coroutine.

Tries to get the user from the cache. If fails, it tries to fetch the user from the API.

Parameters:
  • user_id (int) – The ID to search for.

  • strict (bool) – Whether to propagate exceptions from fetch_user() instead of returning None in case of failure (e.g. if the user wasn’t found). Defaults to False.

Returns:

The user with the given ID, or None if not found and strict is set to False.

Return type:

Optional[User]

get_partial_messageable(id, *, type=None)[source]

Returns a partial messageable with the given channel ID.

This is useful if you have a channel_id but don’t want to do an API call to send messages to it.

New in version 2.0.

Parameters:
  • id (int) – The channel ID to create a partial messageable for.

  • type (Optional[ChannelType]) – The underlying channel type for the partial messageable.

Returns:

The partial messageable

Return type:

PartialMessageable

get_slash_command(name)[source]

Works like Bot.get_command, but for slash commands.

If the name contains spaces, then it will assume that you are looking for a SubCommand or a SubCommandGroup. e.g: 'foo bar' will get the sub command group, or the sub command bar of the top-level slash command foo if found, otherwise None.

Parameters:

name (str) – The name of the slash command to get.

Raises:

TypeError – The name is not a string.

Returns:

The slash command that was requested. If not found, returns None.

Return type:

Optional[Union[InvokableSlashCommand, SubCommandGroup, SubCommand]]

get_stage_instance(id, /)[source]

Returns a stage instance with the given stage channel ID.

New in version 2.0.

Parameters:

id (int) – The ID to search for.

Returns:

The returns stage instance or None if not found.

Return type:

Optional[StageInstance]

get_sticker(id, /)[source]

Returns a guild sticker with the given ID.

New in version 2.0.

Note

To retrieve standard stickers, use fetch_sticker(). or fetch_premium_sticker_packs().

Returns:

The sticker or None if not found.

Return type:

Optional[GuildSticker]

get_user(id, /)[source]

Returns a user with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The user or None if not found.

Return type:

Optional[User]

get_user_command(name)[source]

Gets an InvokableUserCommand from the internal list of user commands.

Parameters:

name (str) – The name of the user command to get.

Returns:

The user command that was requested. If not found, returns None.

Return type:

Optional[InvokableUserCommand]

await getch_user(user_id, *, strict=False)[source]

This function is a coroutine.

Tries to get the user from the cache. If fails, it tries to fetch the user from the API.

Parameters:
  • user_id (int) – The ID to search for.

  • strict (bool) – Whether to propagate exceptions from fetch_user() instead of returning None in case of failure (e.g. if the user wasn’t found). Defaults to False.

Returns:

The user with the given ID, or None if not found and strict is set to False.

Return type:

Optional[User]

property global_application_commands[source]

The client’s global application commands.

Type:

List[Union[APIUserCommand, APIMessageCommand, APISlashCommand]

property global_message_commands[source]

The client’s global message commands.

Type:

List[APIMessageCommand]

property global_slash_commands[source]

The client’s global slash commands.

Type:

List[APISlashCommand]

property global_user_commands[source]

The client’s global user commands.

Type:

List[APIUserCommand]

guild_builder(name)[source]

Creates a builder object that can be used to create more complex guilds.

This is a more comprehensive alternative to create_guild(). See GuildBuilder for details and examples.

Bot accounts in 10 or more guilds are not allowed to create guilds.

New in version 2.8.

Parameters:

name (str) – The name of the guild.

Returns:

The guild builder object for configuring and creating a new guild.

Return type:

GuildBuilder

property guilds[source]

The guilds that the connected client is a member of.

Type:

List[Guild]

property intents[source]

The intents configured for this connection.

New in version 1.5.

Type:

Intents

is_closed()[source]

Whether the websocket connection is closed.

Return type:

bool

await is_owner(user)[source]

This function is a coroutine.

Checks if a User or Member is the owner of this bot.

If an owner_id is not set, it is fetched automatically through the use of application_info().

Changed in version 1.3: The function also checks if the application is team-owned if owner_ids is not set.

Parameters:

user (abc.User) – The user to check for.

Returns:

Whether the user is the owner.

Return type:

bool

is_ready()[source]

Whether the client’s internal cache is ready for use.

Return type:

bool

is_ws_ratelimited()[source]

Whether the websocket is currently rate limited.

This can be useful to know when deciding whether you should query members using HTTP or via the gateway.

New in version 1.6.

Return type:

bool

property latency[source]

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.

Type:

float

load_extension(name, *, package=None)[source]

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, setup defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the bot.

Parameters:
  • name (str) – The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) –

    The package name to resolve relative imports with. This is required when loading an extension using a relative path, e.g .foo.test. Defaults to None.

    New in version 1.7.

Raises:
  • ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package parameter.

  • ExtensionAlreadyLoaded – The extension is already loaded.

  • NoEntryPointError – The extension does not have a setup function.

  • ExtensionFailed – The extension or its setup function had an execution error.

load_extensions(path)[source]

Loads all extensions in a directory.

New in version 2.4.

Parameters:

path (str) – The path to search for extensions

await login(token)[source]

This function is a coroutine.

Logs in the client with the specified credentials.

Parameters:

token (str) – The authentication token. Do not prefix this token with anything as the library will do it for you.

Raises:
  • LoginFailure – The wrong credentials are passed.

  • HTTPException – An unknown HTTP related error occurred, usually when it isn’t 200 or the known incorrect credentials passing status code.

property message_commands[source]

A set of all message commands the bot has.

Type:

Set[InvokableMessageCommand]

await on_error(event_method, *args, **kwargs)[source]

This function is a coroutine.

The default error handler provided by the client.

By default this prints to sys.stderr however it could be overridden to have a different implementation. Check on_error() for more details.

await on_gateway_error(event, data, shard_id, exc, /)[source]

This function is a coroutine.

The default gateway error handler provided by the client.

By default this prints to sys.stderr however it could be overridden to have a different implementation. Check on_gateway_error() for more details.

New in version 2.6.

Note

Unlike on_error(), the exception is available as the exc parameter and cannot be obtained through sys.exc_info().

await on_message_command_error(interaction, exception)[source]

This function is a coroutine.

Similar to on_slash_command_error() but for message commands.

await on_slash_command_error(interaction, exception)[source]

This function is a coroutine.

The default slash 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 slash command error.

await on_user_command_error(interaction, exception)[source]

This function is a coroutine.

Similar to on_slash_command_error() but for user commands.

property persistent_views[source]

A sequence of persistent views added to the client.

New in version 2.0.

Type:

Sequence[View]

property private_channels[source]

The private channels that the connected client is participating on.

Note

This returns only up to 128 most recent private channels due to an internal working on how Discord deals with private channels.

Type:

List[abc.PrivateChannel]

await process_app_command_autocompletion(inter)[source]

This function is a coroutine.

This function processes the application command autocompletions. Without this coroutine, none of the autocompletions will be performed.

By default, this coroutine is called inside the on_application_command_autocomplete() event. If you choose to override the on_application_command_autocomplete() event, then you should invoke this coroutine as well.

Parameters:

inter (disnake.ApplicationCommandInteraction) – The interaction to process.

await process_application_commands(interaction)[source]

This function is a coroutine.

This function processes the application commands that have been registered to the bot and other groups. Without this coroutine, none of the application commands will be triggered.

By default, this coroutine is called inside the on_application_command() event. If you choose to override the on_application_command() event, then you should invoke this coroutine as well.

Parameters:

interaction (disnake.ApplicationCommandInteraction) – The interaction to process commands for.

reload_extension(name, *, package=None)[source]

Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a unload_extension() followed by a load_extension() except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.

Parameters:
  • name (str) – The extension name to reload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) –

    The package name to resolve relative imports with. This is required when reloading an extension using a relative path, e.g .foo.test. Defaults to None.

    New in version 1.7.

Raises:
  • ExtensionNotLoaded – The extension was not loaded.

  • ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package parameter.

  • NoEntryPointError – The extension does not have a setup function.

  • ExtensionFailed – The extension setup function had an execution error.

remove_app_command_check(func, *, call_once=False, slash_commands=False, user_commands=False, message_commands=False)[source]

Removes a global application command check from the bot.

This function is idempotent and will not raise an exception if the function is not in the global checks.

You must specify at least one of the bool parameters, otherwise the check won’t be removed.

Parameters:
  • func – The function to remove from the global checks.

  • call_once (bool) – Whether the function was added with call_once=True in the Bot.add_check() call or using check_once().

  • slash_commands (bool) – Whether this check was for slash commands.

  • user_commands (bool) – Whether this check was for user commands.

  • message_commands (bool) – Whether this check was for message commands.

remove_cog(name)[source]

Removes a cog from the bot and returns it.

All registered commands and event listeners that the cog has registered will be removed as well.

If no cog is found then this method has no effect.

Parameters:

name (str) – The name of the cog to remove.

Returns:

The cog that was removed. Returns None if not found.

Return type:

Optional[Cog]

remove_listener(func, name=...)[source]

Removes a listener from the pool of listeners.

Parameters:
  • func – The function that was used as a listener to remove.

  • name (Union[str, Event]) – The name of the event we want to remove. Defaults to func.__name__.

Raises:

TypeError – The name passed was not a string or an Event.

remove_message_command(name)[source]

Removes an InvokableMessageCommand from the internal list of message commands.

Parameters:

name (str) – The name of the message command to remove.

Returns:

The message command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[InvokableMessageCommand]

remove_slash_command(name)[source]

Removes an InvokableSlashCommand from the internal list of slash commands.

Parameters:

name (str) – The name of the slash command to remove.

Returns:

The slash command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[InvokableSlashCommand]

remove_user_command(name)[source]

Removes an InvokableUserCommand from the internal list of user commands.

Parameters:

name (str) – The name of the user command to remove.

Returns:

The user command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[InvokableUserCommand]

run(*args, **kwargs)[source]

A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use start() coroutine or connect() + login().

Roughly Equivalent to:

try:
    loop.run_until_complete(start(*args, **kwargs))
except KeyboardInterrupt:
    loop.run_until_complete(close())
    # cancel all tasks lingering
finally:
    loop.close()

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.

property slash_commands[source]

A set of all slash commands the bot has.

Type:

Set[InvokableSlashCommand]

await start(token, *, reconnect=True, ignore_session_start_limit=False)[source]

This function is a coroutine.

A shorthand coroutine for login() + connect().

Raises:

TypeError – An unexpected keyword argument was received.

property status[source]

The status being used upon logging on to Discord.

New in version 2.0.

Type:

Status

property stickers[source]

The stickers that the connected client has.

New in version 2.0.

Type:

List[GuildSticker]

unload_extension(name, *, package=None)[source]

Unloads an extension.

When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported.

The extension can provide an optional global function, teardown, to do miscellaneous clean-up if necessary. This function takes a single parameter, the bot, similar to setup from load_extension().

Parameters:
  • name (str) – The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) –

    The package name to resolve relative imports with. This is required when unloading an extension using a relative path, e.g .foo.test. Defaults to None.

    New in version 1.7.

Raises:
property user[source]

Represents the connected client. None if not logged in.

Type:

Optional[ClientUser]

property user_commands[source]

A set of all user commands the bot has.

Type:

Set[InvokableUserCommand]

property users[source]

Returns a list of all the users the bot can see.

Type:

List[User]

property voice_clients[source]

Represents a list of voice connections.

These are usually VoiceClient instances.

Type:

List[VoiceProtocol]

wait_for(event, *, check=None, timeout=None)[source]

This function is a coroutine.

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The timeout parameter is passed onto asyncio.wait_for(). By default, it does not timeout. Note that this does propagate the asyncio.TimeoutError for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a tuple containing those arguments is returned instead. Please check the documentation for a list of events and their parameters.

This function returns the first event that meets the requirements.

Examples

Waiting for a user reply:

@client.event
async def on_message(message):
    if message.content.startswith('$greet'):
        channel = message.channel
        await channel.send('Say hello!')

        def check(m):
            return m.content == 'hello' and m.channel == channel

        msg = await client.wait_for('message', check=check)
        await channel.send(f'Hello {msg.author}!')

# using events enums:
@client.event
async def on_message(message):
    if message.content.startswith('$greet'):
        channel = message.channel
        await channel.send('Say hello!')

        def check(m):
            return m.content == 'hello' and m.channel == channel

        msg = await client.wait_for(Event.message, check=check)
        await channel.send(f'Hello {msg.author}!')

Waiting for a thumbs up reaction from the message author:

@client.event
async def on_message(message):
    if message.content.startswith('$thumb'):
        channel = message.channel
        await channel.send('Send me that 👍 reaction, mate')

        def check(reaction, user):
            return user == message.author and str(reaction.emoji) == '👍'

        try:
            reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
        except asyncio.TimeoutError:
            await channel.send('👎')
        else:
            await channel.send('👍')
Parameters:
  • event (Union[str, Event]) – The event name, similar to the event reference, but without the on_ prefix, to wait for. It’s recommended to use Event.

  • check (Optional[Callable[…, bool]]) – A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for.

  • timeout (Optional[float]) – The number of seconds to wait before timing out and raising asyncio.TimeoutError.

Raises:

asyncio.TimeoutError – If a timeout is provided and it was reached.

Returns:

Returns no arguments, a single argument, or a tuple of multiple arguments that mirrors the parameters passed in the event reference.

Return type:

Any

await wait_until_first_connect()[source]

This function is a coroutine.

Waits until the first connect.

await wait_until_ready()[source]

This function is a coroutine.

Waits until the client’s internal cache is all ready.

AutoShardedInteractionBot

class disnake.ext.commands.AutoShardedInteractionBot(*, command_sync_flags=None, sync_commands=..., sync_commands_debug=..., sync_commands_on_cog_unload=..., test_guilds=None, **options)[source]

This is similar to InteractionBot except that it is inherited from disnake.AutoShardedClient instead.

Command Sync

CommandSyncFlags

class disnake.ext.commands.CommandSyncFlags[source]

Controls the library’s application command syncing policy.

This allows for finer grained control over what commands are synced automatically and in what cases.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

If command sync is disabled (see the docs of sync_commands for more info), other options will have no effect.

New in version 2.7.

x == y

Checks if two CommandSyncFlags instances are equal.

x != y

Checks if two CommandSyncFlags instances are not equal.

x <= y

Checks if an CommandSyncFlags instance is a subset of another CommandSyncFlags instance.

x >= y

Checks if an CommandSyncFlags instance is a superset of another CommandSyncFlags instance.

x < y

Checks if an CommandSyncFlags instance is a strict subset of another CommandSyncFlags instance.

x > y

Checks if an CommandSyncFlags instance is a strict superset of another CommandSyncFlags instance.

x | y, x |= y

Returns a new CommandSyncFlags instance with all enabled flags from both x and y. (Using |= will update in place).

x & y, x &= y

Returns a new CommandSyncFlags instance with only flags enabled on both x and y. (Using &= will update in place).

x ^ y, x ^= y

Returns a new CommandSyncFlags instance with only flags enabled on one of x or y, but not both. (Using ^= will update in place).

~x

Returns a new CommandSyncFlags instance with all flags from x inverted.

hash(x)

Return the flag’s hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

Additionally supported are a few operations on class attributes.

CommandSyncFlags.y | CommandSyncFlags.z, CommandSyncFlags(y=True) | CommandSyncFlags.z

Returns a CommandSyncFlags instance with all provided flags enabled.

~CommandSyncFlags.y

Returns a CommandSyncFlags instance with all flags except y inverted from their default value.

value

The raw value. You should query flags via the properties rather than using this raw value.

Type:

int

classmethod all()[source]

A factory method that creates a CommandSyncFlags with everything enabled.

classmethod none()[source]

A factory method that creates a CommandSyncFlags with everything disabled.

classmethod default()[source]

A factory method that creates a CommandSyncFlags with the default settings.

The default is all flags enabled except for sync_commands_debug.

sync_commands

Whether to sync global and guild app commands.

This controls the sync_global_commands and sync_guild_commands attributes.

Note that it is possible for sync to be enabled for guild or global commands yet this will return False.

Type:

bool

sync_commands_debug

Whether or not to show app command sync debug messages.

Type:

bool

sync_on_cog_actions

Whether or not to sync app commands on cog load, unload, or reload.

Type:

bool

allow_command_deletion

Whether to allow commands to be deleted by automatic command sync.

Current implementation of commands sync of renamed commands means that a rename of a command will result in the old one being deleted and a new command being created.

Type:

bool

sync_global_commands

Whether to sync global commands.

Type:

bool

sync_guild_commands

Whether to sync per-guild commands.

Type:

bool

Prefix Helpers

disnake.ext.commands.when_mentioned(bot, msg)[source]

A callable that implements a command prefix equivalent to being mentioned.

These are meant to be passed into the Bot.command_prefix attribute.

disnake.ext.commands.when_mentioned_or(*prefixes)[source]

A callable that implements when mentioned or other prefixes provided.

These are meant to be passed into the Bot.command_prefix attribute.

Example

bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))

Note

This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example:

async def get_prefix(bot, message):
    extras = await prefixes_for(message.guild) # returns a list
    return commands.when_mentioned_or(*extras)(bot, message)

See also

when_mentioned()

Event Reference

These events function similar to the regular events, except they are custom to the command extension module.

disnake.ext.commands.on_command_error(ctx, error)

An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

A default one is provided (Bot.on_command_error()).

Parameters:
  • ctx (Context) – The invocation context.

  • error (CommandError derived) – The error that was raised.

disnake.ext.commands.on_slash_command_error(inter, error)

An error handler that is called when an error is raised inside a slash command either through user input error, check failure, or an error in your own code.

A default one is provided (Bot.on_slash_command_error()).

Parameters:
disnake.ext.commands.on_user_command_error(inter, error)

An error handler that is called when an error is raised inside a user command either through check failure, or an error in your own code.

A default one is provided (Bot.on_user_command_error()).

Parameters:
disnake.ext.commands.on_message_command_error(inter, error)

An error handler that is called when an error is raised inside a message command either through check failure, or an error in your own code.

A default one is provided (Bot.on_message_command_error()).

Parameters:
disnake.ext.commands.on_command(ctx)

An event that is called when a command is found and is about to be invoked.

This event is called regardless of whether the command itself succeeds via error or completes.

Parameters:

ctx (Context) – The invocation context.

disnake.ext.commands.on_slash_command(inter)

An event that is called when a slash command is found and is about to be invoked.

This event is called regardless of whether the slash command itself succeeds via error or completes.

Parameters:

inter (ApplicationCommandInteraction) – The interaction that invoked this slash command.

disnake.ext.commands.on_user_command(inter)

An event that is called when a user command is found and is about to be invoked.

This event is called regardless of whether the user command itself succeeds via error or completes.

Parameters:

inter (ApplicationCommandInteraction) – The interaction that invoked this user command.

disnake.ext.commands.on_message_command(inter)

An event that is called when a message command is found and is about to be invoked.

This event is called regardless of whether the message command itself succeeds via error or completes.

Parameters:

inter (ApplicationCommandInteraction) – The interaction that invoked this message command.

disnake.ext.commands.on_command_completion(ctx)

An event that is called when a command has completed its invocation.

This event is called only if the command succeeded, i.e. all checks have passed and the user input it correctly.

Parameters:

ctx (Context) – The invocation context.

disnake.ext.commands.on_slash_command_completion(inter)

An event that is called when a slash command has completed its invocation.

This event is called only if the slash command succeeded, i.e. all checks have passed and command handler ran successfully.

Parameters:

inter (ApplicationCommandInteraction) – The interaction that invoked this slash command.

disnake.ext.commands.on_user_command_completion(inter)

An event that is called when a user command has completed its invocation.

This event is called only if the user command succeeded, i.e. all checks have passed and command handler ran successfully.

Parameters:

inter (ApplicationCommandInteraction) – The interaction that invoked this user command.

disnake.ext.commands.on_message_command_completion(inter)

An event that is called when a message command has completed its invocation.

This event is called only if the message command succeeded, i.e. all checks have passed and command handler ran successfully.

Parameters:

inter (ApplicationCommandInteraction) – The interaction that invoked this message command.

Commands

Decorators

@disnake.ext.commands.command(name=..., cls=..., **attrs)[source]

A decorator that transforms a function into a Command or if called with group(), Group.

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

All checks added using the check() & co. decorators are added into the function. There is no way to supply your own checks through this decorator.

Parameters:
  • name (str) – The name to create the command with. By default this uses the function name unchanged.

  • cls – The class to construct with. By default this is Command. You usually do not change this.

  • attrs – Keyword arguments to pass into the construction of the class denoted by cls.

Raises:

TypeError – If the function is not a coroutine or is already a command.

@disnake.ext.commands.slash_command(*, name=None, description=None, dm_permission=None, default_member_permissions=None, nsfw=None, options=None, guild_ids=None, connectors=None, auto_sync=None, extras=None, **kwargs)[source]

A decorator that builds a slash command.

Parameters:
  • auto_sync (bool) – Whether to automatically register the command. Defaults to True.

  • name (Optional[Union[str, Localized]]) –

    The name of the slash command (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • description (Optional[Union[str, Localized]]) –

    The description of the slash command. It will be visible in Discord.

    Changed in version 2.5: Added support for localizations.

  • nsfw (bool) –

    Whether this command is age-restricted. Defaults to False.

    New in version 2.8.

  • options (List[Option]) – The list of slash command options. The options will be visible in Discord. This is the old way of specifying options. Consider using Parameters instead.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • guild_ids (List[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • connectors (Dict[str, str]) – Binds function names to option names. If the name of an option already matches the corresponding function param, you don’t have to specify the connectors. Connectors template: {"option-name": "param_name", ...}. If you’re using Parameters, you don’t need to specify this.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableSlashCommand and returns it.

Return type:

Callable[…, InvokableSlashCommand]

@disnake.ext.commands.user_command(*, name=None, dm_permission=None, default_member_permissions=None, nsfw=None, guild_ids=None, auto_sync=None, extras=None, **kwargs)[source]

A shortcut decorator that builds a user command.

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the user command (defaults to the function name).

    Changed in version 2.5: Added support for localizations.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • nsfw (bool) –

    Whether this command is age-restricted. Defaults to False.

    New in version 2.8.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True.

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableUserCommand and returns it.

Return type:

Callable[…, InvokableUserCommand]

@disnake.ext.commands.message_command(*, name=None, dm_permission=None, default_member_permissions=None, nsfw=None, guild_ids=None, auto_sync=None, extras=None, **kwargs)[source]

A shortcut decorator that builds a message command.

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the message command (defaults to the function name).

    Changed in version 2.5: Added support for localizations.

  • dm_permission (bool) – Whether this command can be used in DMs. Defaults to True.

  • default_member_permissions (Optional[Union[Permissions, int]]) –

    The default required permissions for this command. See ApplicationCommand.default_member_permissions for details.

    New in version 2.5.

  • nsfw (bool) –

    Whether this command is age-restricted. Defaults to False.

    New in version 2.8.

  • auto_sync (bool) – Whether to automatically register the command. Defaults to True.

  • guild_ids (Sequence[int]) – If specified, the client will register the command in these guilds. Otherwise, this command will be registered globally.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the command.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into an InvokableMessageCommand and then returns it.

Return type:

Callable[…, InvokableMessageCommand]

@disnake.ext.commands.group(name=..., cls=..., **attrs)[source]

A decorator that transforms a function into a Group.

This is similar to the command() decorator but the cls parameter is set to Group by default.

Changed in version 1.1: The cls parameter can now be passed.

Helper Functions

disnake.ext.commands.Param(default=Ellipsis, *, name=None, description=None, choices=None, converter=None, convert_defaults=False, autocomplete=None, channel_types=None, lt=None, le=None, gt=None, ge=None, large=False, min_length=None, max_length=None, **kwargs)[source]

A special function that creates an instance of ParamInfo that contains some information about a slash command option. This instance should be assigned to a parameter of a function representing your slash command.

See Parameters for more info.

Parameters:
  • default (Union[Any, Callable[[ApplicationCommandInteraction], Any]]) – The actual default value of the function parameter that should be passed instead of the ParamInfo instance. Can be a sync/async callable taking an interaction and returning a dynamic default value, if the user didn’t pass a value for this parameter.

  • name (Optional[Union[str, Localized]]) –

    The name of the option. By default, the option name is the parameter name.

    Changed in version 2.5: Added support for localizations.

  • description (Optional[Union[str, Localized]]) –

    The description of the option. You can skip this kwarg and use docstrings. See Parameters. Kwarg aliases: desc.

    Changed in version 2.5: Added support for localizations.

  • choices (Union[List[OptionChoice], List[Union[str, int]], Dict[str, Union[str, int]]]) – A list of choices for this option.

  • converter (Callable[[ApplicationCommandInteraction, Any], Any]) – A function that will convert the original input to a desired format. Kwarg aliases: conv.

  • convert_defaults (bool) –

    Whether to also apply the converter to the provided default value. Defaults to False.

    New in version 2.3.

  • autocomplete (Callable[[ApplicationCommandInteraction, str], Any]) – A function that will suggest possible autocomplete options while typing. See Parameters. Kwarg aliases: autocomp.

  • channel_types (Iterable[ChannelType]) – A list of channel types that should be allowed. By default these are discerned from the annotation.

  • lt (float) – The (exclusive) upper bound of values for this option (less-than).

  • le (float) – The (inclusive) upper bound of values for this option (less-than-or-equal). Kwarg aliases: max_value.

  • gt (float) – The (exclusive) lower bound of values for this option (greater-than).

  • ge (float) – The (inclusive) lower bound of values for this option (greater-than-or-equal). Kwarg aliases: min_value.

  • large (bool) –

    Whether to accept large int values (if this is False, only values in the range (-2^53, 2^53) would be accepted due to an API limitation).

    New in version 2.3.

  • min_length (int) –

    The minimum length for this option if this is a string option.

    New in version 2.6.

  • max_length (int) –

    The maximum length for this option if this is a string option.

    New in version 2.6.

Raises:

TypeError – Unexpected keyword arguments were provided.

Returns:

An instance with the option info.

Note

In terms of typing, this returns Any to avoid typing issues, but at runtime this is always a ParamInfo instance. You can find a more in-depth explanation here.

Return type:

ParamInfo

disnake.ext.commands.option_enum(choices, **kwargs)[source]

A utility function to create an enum type. Returns a new Enum based on the provided parameters.

New in version 2.1.

Parameters:
  • choices (Union[Dict[str, Any], List[Any]]) – A name/value mapping of choices, or a list of values whose stringified representations will be used as the names.

  • **kwargs – Name/value pairs to use instead of the choices parameter.

@disnake.ext.commands.converter_method(function)[source]

A decorator to register a method as the converter method.

New in version 2.3.

Application Command

class disnake.ext.commands.InvokableApplicationCommand(*args, **kwargs)[source]

A base class that implements the protocol for a bot application command.

These are not created manually, instead they are created via the decorator or functional interface.

The following classes implement this ABC:

name

The name of the command.

Type:

str

qualified_name

The full command name, including parent names in the case of slash subcommands or groups. For example, the qualified name for /one two three would be one two three.

Type:

str

body

An object being registered in the API.

Type:

ApplicationCommand

callback[source]

The coroutine that is executed when the command is called.

Type:

coroutine

cog

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

Type:

Optional[Cog]

checks

A list of predicates that verifies if the command could be executed with the given ApplicationCommandInteraction as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_slash_command_error() event.

Type:

List[Callable[[ApplicationCommandInteraction], bool]]

guild_ids

The list of IDs of the guilds where the command is synced. None if this command is global.

Type:

Optional[Tuple[int, …]]

auto_sync

Whether to automatically register the command.

Type:

bool

extras

A dict of user provided extras to attach to the command.

New in version 2.5.

Type:

Dict[str, Any]

@before_invoke[source]

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

A pre-invoke hook is called directly before the command is called.

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

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@after_invoke[source]

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

A post-invoke hook is called directly after the command is called.

This post-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@error[source]

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

A local error handler is an error event limited to a single application command.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

copy()[source]

Create a copy of this application command.

Returns:

A new instance of this application command.

Return type:

InvokableApplicationCommand

property dm_permission[source]

Whether this command can be used in DMs.

Type:

bool

property default_member_permissions[source]

The default required member permissions for this command. A member must have all these permissions to be able to invoke the command in a guild.

This is a default value, the set of users/roles that may invoke this command can be overridden by moderators on a guild-specific basis, disregarding this setting.

If None is returned, it means everyone can use the command by default. If an empty Permissions object is returned (that is, all permissions set to False), this means no one can use the command.

New in version 2.5.

Type:

Optional[Permissions]

add_check(func)[source]

Adds a check to the application command.

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

Parameters:

func – The function that will be used as a check.

remove_check(func)[source]

Removes a check from the application 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.

is_on_cooldown(inter)[source]

Checks whether the application command is currently on cooldown.

Parameters:

inter (ApplicationCommandInteraction) – The interaction with the application command currently being invoked.

Returns:

A boolean indicating if the application command is on cooldown.

Return type:

bool

reset_cooldown(inter)[source]

Resets the cooldown on this application command.

Parameters:

inter (ApplicationCommandInteraction) – The interaction with this application command

get_cooldown_retry_after(inter)[source]

Retrieves the amount of seconds before this application command can be tried again.

Parameters:

inter (ApplicationCommandInteraction) – The interaction with this application command.

Returns:

The amount of time left on this command’s cooldown in seconds. If this is 0.0 then the command isn’t on cooldown.

Return type:

float

await invoke(inter, *args, **kwargs)[source]

This method isn’t really usable in this class, but it’s usable in subclasses.

has_error_handler()[source]

Checks whether the application command has an error handler registered.

property cog_name[source]

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

Type:

Optional[str]

await can_run(inter)[source]

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute.

Parameters:

inter (ApplicationCommandInteraction) – The interaction with the application command currently being invoked.

Raises:

CommandError – Any application command error that was raised during a check call will be propagated by this function.

Returns:

A boolean indicating if the application command can be invoked.

Return type:

bool

Slash Command

class disnake.ext.commands.InvokableSlashCommand(*args, **kwargs)[source]

A class that implements the protocol for a bot slash command.

These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the command.

Type:

str

qualified_name

The full command name, including parent names in the case of slash subcommands or groups. For example, the qualified name for /one two three would be one two three.

Type:

str

body

An object being registered in the API.

Type:

SlashCommand

callback[source]

The coroutine that is executed when the command is called.

Type:

coroutine

cog

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

Type:

Optional[Cog]

checks

A list of predicates that verifies if the command could be executed with the given ApplicationCommandInteraction as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_slash_command_error() event.

Type:

List[Callable[[ApplicationCommandInteraction], bool]]

guild_ids

The list of IDs of the guilds where the command is synced. None if this command is global.

Type:

Optional[Tuple[int, …]]

connectors

A mapping of option names to function parameter names, mainly for internal processes.

Type:

Dict[str, str]

auto_sync

Whether to automatically register the command.

Type:

bool

extras

A dict of user provided extras to attach to the command.

Note

This object may be copied by the library.

New in version 2.5.

Type:

Dict[str, Any]

parent

This exists for consistency with SubCommand and SubCommandGroup. Always None.

New in version 2.6.

Type:

None

@sub_command(*args, **kwargs)[source]

A decorator that creates a subcommand under the base command.

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the subcommand (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • description (Optional[Union[str, Localized]]) –

    The description of the subcommand.

    Changed in version 2.5: Added support for localizations.

  • options (List[Option]) – the options of the subcommand for registration in API

  • connectors (Dict[str, str]) – which function param states for each option. If the name of an option already matches the corresponding function param, you don’t have to specify the connectors. Connectors template: {"option-name": "param_name", ...}

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the subcommand.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into a SubCommand, adds it to the bot, then returns it.

Return type:

Callable[…, SubCommand]

@sub_command_group(*args, **kwargs)[source]

A decorator that creates a subcommand group under the base command.

Parameters:
  • name (Optional[Union[str, Localized]]) –

    The name of the subcommand group (defaults to function name).

    Changed in version 2.5: Added support for localizations.

  • extras (Dict[str, Any]) –

    A dict of user provided extras to attach to the subcommand group.

    Note

    This object may be copied by the library.

    New in version 2.5.

Returns:

A decorator that converts the provided method into a SubCommandGroup, adds it to the bot, then returns it.

Return type:

Callable[…, SubCommandGroup]

@after_invoke[source]

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

A post-invoke hook is called directly after the command is called.

This post-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke[source]

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

A pre-invoke hook is called directly before the command is called.

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

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@error[source]

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

A local error handler is an error event limited to a single application command.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

property root_parent[source]

This is for consistency with SubCommand and SubCommandGroup.

New in version 2.6.

Type:

None

property parents[source]

This is mainly for consistency with SubCommand, and is equivalent to an empty tuple.

New in version 2.6.

Type:

Tuple[()]

autocomplete(option_name)[source]

A decorator that registers an autocomplete function for the specified option.

Parameters:

option_name (str) – The name of the slash command option.

await invoke(inter)[source]

This method isn’t really usable in this class, but it’s usable in subclasses.

Slash Subcommand

class disnake.ext.commands.SubCommand(*args, **kwargs)[source]

A class that implements the protocol for a bot slash subcommand.

These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the subcommand.

Type:

str

qualified_name

The full command name, including parent names in the case of slash subcommands or groups. For example, the qualified name for /one two three would be one two three.

Type:

str

parent

The parent command or group this subcommand belongs to.

New in version 2.6.

Type:

Union[InvokableSlashCommand, SubCommandGroup]

option

API representation of this subcommand.

Type:

Option

callback[source]

The coroutine that is executed when the subcommand is called.

Type:

coroutine

cog

The cog that this subcommand belongs to. None if there isn’t one.

Type:

Optional[Cog]

checks

A list of predicates that verifies if the subcommand could be executed with the given ApplicationCommandInteraction as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_slash_command_error() event.

Type:

List[Callable[[ApplicationCommandInteraction], bool]]

connectors

A mapping of option names to function parameter names, mainly for internal processes.

Type:

Dict[str, str]

extras

A dict of user provided extras to attach to the subcommand.

Note

This object may be copied by the library.

New in version 2.5.

Type:

Dict[str, Any]

@after_invoke[source]

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

A post-invoke hook is called directly after the command is called.

This post-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke[source]

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

A pre-invoke hook is called directly before the command is called.

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

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@error[source]

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

A local error handler is an error event limited to a single application command.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

property root_parent[source]

Returns the top-level slash command containing this subcommand, even if the parent is a SubCommandGroup.

New in version 2.6.

Type:

InvokableSlashCommand

property parents[source]

Union[Tuple[InvokableSlashCommand], Tuple[SubCommandGroup, InvokableSlashCommand]]: Returns all parents of this subcommand.

For example, the parents of the c subcommand in /a b c are (b, a).

New in version 2.6.

await invoke(inter, *args, **kwargs)[source]

This method isn’t really usable in this class, but it’s usable in subclasses.

autocomplete(option_name)[source]

A decorator that registers an autocomplete function for the specified option.

Parameters:

option_name (str) – The name of the slash command option.

Slash Subcommand Group

class disnake.ext.commands.SubCommandGroup(*args, **kwargs)[source]

A class that implements the protocol for a bot slash command group.

These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the group.

Type:

str

qualified_name

The full command name, including parent names in the case of slash subcommands or groups. For example, the qualified name for /one two three would be one two three.

Type:

str

parent

The parent command this group belongs to.

New in version 2.6.

Type:

InvokableSlashCommand

option

API representation of this subcommand.

Type:

Option

callback[source]

The coroutine that is executed when the command group is invoked.

Type:

coroutine

cog

The cog that this group belongs to. None if there isn’t one.

Type:

Optional[Cog]

checks

A list of predicates that verifies if the group could be executed with the given ApplicationCommandInteraction as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_slash_command_error() event.

Type:

List[Callable[[ApplicationCommandInteraction], bool]]

extras

A dict of user provided extras to attach to the subcommand group.

Note

This object may be copied by the library.

New in version 2.5.

Type:

Dict[str, Any]

@sub_command(*args, **kwargs)[source]

A decorator that creates a subcommand in the subcommand group. Parameters are the same as in InvokableSlashCommand.sub_command

Returns:

A decorator that converts the provided method into a SubCommand, adds it to the bot, then returns it.

Return type:

Callable[…, SubCommand]

@after_invoke[source]

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

A post-invoke hook is called directly after the command is called.

This post-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke[source]

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

A pre-invoke hook is called directly before the command is called.

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

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@error[source]

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

A local error handler is an error event limited to a single application command.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

property root_parent[source]

Returns the slash command containing this group. This is mainly for consistency with SubCommand, and is equivalent to parent.

New in version 2.6.

Type:

InvokableSlashCommand

property parents[source]

Returns all parents of this group.

New in version 2.6.

Type:

Tuple[InvokableSlashCommand]

ParamInfo

class disnake.ext.commands.ParamInfo(default=Ellipsis, *, name=None, description=None, converter=None, convert_default=False, autocomplete=None, choices=None, type=None, channel_types=None, lt=None, le=None, gt=None, ge=None, large=False, min_length=None, max_length=None)[source]

A class that basically connects function params with slash command options. The instances of this class are not created manually, but via the functional interface instead. See Param().

Parameters:
  • default (Union[Any, Callable[[ApplicationCommandInteraction], Any]]) – The actual default value for the corresponding function param. Can be a sync/async callable taking an interaction and returning a dynamic default value, if the user didn’t pass a value for this parameter.

  • name (Optional[Union[str, Localized]]) –

    The name of this slash command option.

    Changed in version 2.5: Added support for localizations.

  • description (Optional[Union[str, Localized]]) –

    The description of this slash command option.

    Changed in version 2.5: Added support for localizations.

  • choices (Union[List[OptionChoice], List[Union[str, int]], Dict[str, Union[str, int]]]) – The list of choices of this slash command option.

  • ge (float) – The lowest allowed value for this option.

  • le (float) – The greatest allowed value for this option.

  • type (Any) – The type of the parameter.

  • channel_types (List[ChannelType]) – The list of channel types supported by this slash command option.

  • autocomplete (Callable[[ApplicationCommandInteraction, str], Any]) – The function that will suggest possible autocomplete options while typing.

  • converter (Callable[[ApplicationCommandInteraction, Any], Any]) – The function that will convert the original input to a desired format.

  • min_length (int) –

    The minimum length for this option, if it is a string option.

    New in version 2.6.

  • max_length (int) –

    The maximum length for this option, if it is a string option.

    New in version 2.6.

Injections

Methods
class disnake.ext.commands.Injection(function, *, autocompleters=None)[source]

Represents a slash command injection.

New in version 2.3.

Changed in version 2.6: Added keyword-only argument autocompleters.

function

The underlying injection function.

Type:

Callable

autocompleters

A mapping of injection’s option names to their respective autocompleters.

New in version 2.6.

Type:

Dict[str, Callable]

@autocomplete(option_name)[source]

A decorator that registers an autocomplete function for the specified option.

New in version 2.6.

Parameters:

option_name (str) – The name of the option.

Raises:
  • ValueError – This injection already has an autocompleter set for the given option

  • TypeErroroption_name is not str

__call__(*args, **kwargs)[source]

Calls the underlying function that the injection holds.

New in version 2.6.

disnake.ext.commands.inject(function, *, autocompleters=None)[source]

A special function to use the provided function for injections. This should be assigned to a parameter of a function representing your slash command.

New in version 2.3.

Changed in version 2.6: Added autocompleters keyword-only argument.

Parameters:
  • function (Callable) – The injection function.

  • autocompleters (Dict[str, Callable]) –

    A mapping of the injection’s option names to their respective autocompleters.

    See also Injection.autocomplete().

    New in version 2.6.

Returns:

The resulting injection

Note

The return type is annotated with Any to avoid typing issues caused by how this extension works, but at runtime this is always an Injection instance. You can find more in-depth explanation here.

Return type:

Injection

@disnake.ext.commands.register_injection(function, *, autocompleters=None)[source]

A decorator to register a global injection.

New in version 2.3.

Changed in version 2.6: Now returns disnake.ext.commands.Injection.

Changed in version 2.6: Added autocompleters keyword-only argument.

Raises:

TypeError – Injection doesn’t have a return annotation, or tries to overwrite builtin types.

Returns:

The injection being registered.

Return type:

Injection

@disnake.ext.commands.injection(*, autocompleters=None)[source]

Decorator interface for inject(). You can then assign this value to your slash commands’ parameters.

New in version 2.6.

Parameters:

autocompleters (Dict[str, Callable]) –

A mapping of the injection’s option names to their respective autocompleters.

See also Injection.autocomplete().

Returns:

Decorator which turns your injection function into actual Injection.

Note

The decorator return type is annotated with Any to avoid typing issues caused by how this extension works, but at runtime this is always an Injection instance. You can find more in-depth explanation here.

Return type:

Callable[[Callable[…, Any]], Injection]

User Command

class disnake.ext.commands.InvokableUserCommand(*args, **kwargs)[source]

A class that implements the protocol for a bot user command (context menu).

These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the user command.

Type:

str

qualified_name

The full command name, equivalent to name for this type of command.

Type:

str

body

An object being registered in the API.

Type:

UserCommand

callback[source]

The coroutine that is executed when the user command is called.

Type:

coroutine

cog

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

Type:

Optional[Cog]

checks

A list of predicates that verifies if the command could be executed with the given ApplicationCommandInteraction as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_user_command_error() event.

Type:

List[Callable[[ApplicationCommandInteraction], bool]]

guild_ids

The list of IDs of the guilds where the command is synced. None if this command is global.

Type:

Optional[Tuple[int, …]]

auto_sync

Whether to automatically register the command.

Type:

bool

extras

A dict of user provided extras to attach to the command.

Note

This object may be copied by the library.

New in version 2.5.

Type:

Dict[str, Any]

@after_invoke[source]

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

A post-invoke hook is called directly after the command is called.

This post-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke[source]

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

A pre-invoke hook is called directly before the command is called.

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

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@error[source]

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

A local error handler is an error event limited to a single application command.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

await __call__(interaction, target=None, *args, **kwargs)[source]

This function is a coroutine.

Calls the internal callback that the application command holds.

Note

This bypasses all mechanisms – including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments and types to this function.

Message Command

class disnake.ext.commands.InvokableMessageCommand(*args, **kwargs)[source]

A class that implements the protocol for a bot message command (context menu).

These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the message command.

Type:

str

qualified_name

The full command name, equivalent to name for this type of command.

Type:

str

body

An object being registered in the API.

Type:

MessageCommand

callback[source]

The coroutine that is executed when the message command is called.

Type:

coroutine

cog

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

Type:

Optional[Cog]

checks

A list of predicates that verifies if the command could be executed with the given ApplicationCommandInteraction as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_message_command_error() event.

Type:

List[Callable[[ApplicationCommandInteraction], bool]]

guild_ids

The list of IDs of the guilds where the command is synced. None if this command is global.

Type:

Optional[Tuple[int, …]]

auto_sync

Whether to automatically register the command.

Type:

bool

extras

A dict of user provided extras to attach to the command.

Note

This object may be copied by the library.

New in version 2.5.

Type:

Dict[str, Any]

@after_invoke[source]

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

A post-invoke hook is called directly after the command is called.

This post-invoke hook takes a sole parameter, a ApplicationCommandInteraction.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke[source]

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

A pre-invoke hook is called directly before the command is called.

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

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@error[source]

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

A local error handler is an error event limited to a single application command.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

await __call__(interaction, target=None, *args, **kwargs)[source]

This function is a coroutine.

Calls the internal callback that the application command holds.

Note

This bypasses all mechanisms – including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments and types to this function.

Command

class disnake.ext.commands.Command(*args, **kwargs)[source]

A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the command.

Type:

str

callback[source]

The coroutine that is executed when the command is called.

Type:

coroutine

help

The long help text for the command.

Type:

Optional[str]

brief

The short help text for the command.

Type:

Optional[str]

usage

A replacement for arguments in the default help text.

Type:

Optional[str]

aliases

The list of aliases the command can be invoked under.

Type:

Union[List[str], Tuple[str]]

enabled

Whether the command is currently enabled. If the command is invoked while it is disabled, then DisabledCommand is raised to the on_command_error() event. Defaults to True.

Type:

bool

parent

The parent group that this command belongs to. None if there isn’t one.

Type:

Optional[Group]

cog

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

Type:

Optional[Cog]

checks

A list of predicates that verifies if the command could be executed with the given Context as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_command_error() event.

Type:

List[Callable[[Context], bool]]

description

The message prefixed into the default help command.

Type:

str

hidden

If True, the default help command does not show this in the help output.

Type:

bool

rest_is_raw

If False and a keyword-only argument is provided then the keyword only argument is stripped and handled as if it was a regular argument that handles MissingRequiredArgument and default values in a regular matter rather than passing the rest completely raw. If True then the keyword-only argument will pass in the rest of the arguments in a completely raw matter. Defaults to False.

Type:

bool

invoked_subcommand

The subcommand that was invoked, if any.

Type:

Optional[Command]

require_var_positional

If True and a variadic positional argument is specified, requires the user to specify at least one argument. Defaults to False.

New in version 1.5.

Type:

bool

ignore_extra

If True, ignores extraneous strings passed to a command if all its requirements are met (e.g. ?foo a b c when only expecting a and b). Otherwise on_command_error() and local error handlers are called with TooManyArguments. Defaults to True.

Type:

bool

cooldown_after_parsing

If True, cooldown processing is done after argument parsing, which calls converters. If False then cooldown processing is done first and then the converters are called second. Defaults to False.

Type:

bool

extras

A dict of user provided extras to attach to the Command.

Note

This object may be copied by the library.

New in version 2.0.

Type:

dict

@after_invoke[source]

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

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

This post-invoke hook takes a sole parameter, a Context.

See Bot.after_invoke() for more info.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke[source]

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

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

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

See Bot.before_invoke() for more info.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@error[source]

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

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

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

add_check(func)[source]

Adds a check to the command.

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

New in version 1.3.

Parameters:

func – The function that will be used as a check.

remove_check(func)[source]

Removes a check from the command.

This function is idempotent and will not raise an exception if the function is not in the command’s checks.

New in version 1.3.

Parameters:

func – The function to remove from the checks.

update(**kwargs)[source]

Updates Command instance with updated attribute.

This works similarly to the command() decorator in terms of parameters in that they are passed to the Command or subclass constructors, sans the name and callback.

await __call__(context, *args, **kwargs)[source]

This function is a coroutine.

Calls the internal callback that the command holds.

Note

This bypasses all mechanisms – including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments and types to this function.

New in version 1.3.

copy()[source]

Creates a copy of this command.

Returns:

A new instance of this command.

Return type:

Command

property clean_params[source]

Dict[str, inspect.Parameter]: Retrieves the parameter dictionary without the context or self parameters.

Useful for inspecting signature.

property full_parent_name[source]

Retrieves the fully qualified parent command name.

This the base command name required to execute it. For example, in ?one two three the parent name would be one two.

Type:

str

property parents[source]

Retrieves the parents of this command.

If the command has no parents then it returns an empty list.

For example in commands ?a b c test, the parents are [c, b, a].

New in version 1.1.

Type:

List[Group]

property root_parent[source]

Retrieves the root parent of this command.

If the command has no parents then it returns None.

For example in commands ?a b c test, the root parent is a.

Type:

Optional[Group]

property qualified_name[source]

Retrieves the fully qualified command name.

This is the full parent name with the command name as well. For example, in ?one two three the qualified name would be one two three.

Type:

str

is_on_cooldown(ctx)[source]

Checks whether the command is currently on cooldown.

Parameters:

ctx (Context) – The invocation context to use when checking the commands cooldown status.

Returns:

A boolean indicating if the command is on cooldown.

Return type:

bool

reset_cooldown(ctx)[source]

Resets the cooldown on this command.

Parameters:

ctx (Context) – The invocation context to reset the cooldown under.

get_cooldown_retry_after(ctx)[source]

Retrieves the amount of seconds before this command can be tried again.

New in version 1.4.

Parameters:

ctx (Context) – The invocation context to retrieve the cooldown from.

Returns:

The amount of time left on this command’s cooldown in seconds. If this is 0.0 then the command isn’t on cooldown.

Return type:

float

has_error_handler()[source]

Whether the command has an error handler registered.

New in version 1.7.

Return type:

bool

property cog_name[source]

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

Type:

Optional[str]

property short_doc[source]

Gets the “short” documentation of a command.

By default, this is the brief attribute. If that lookup leads to an empty string then the first line of the help attribute is used instead.

Type:

str

property signature[source]

Returns a POSIX-like signature useful for help command output.

Type:

str

await can_run(ctx)[source]

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute. This also checks whether the command is disabled.

Changed in version 1.3: Checks whether the command is disabled.

Parameters:

ctx (Context) – The ctx of the command currently being invoked.

Raises:

CommandError – Any command error that was raised during a check call will be propagated by this function.

Returns:

Whether the command can be invoked.

Return type:

bool

Group

class disnake.ext.commands.Group(*args, **kwargs)[source]

A class that implements a grouping protocol for commands to be executed as subcommands.

This class is a subclass of Command and thus all options valid in Command are valid in here as well.

invoke_without_command

Indicates if the group callback should begin parsing and invocation only if no subcommand was found. Useful for making it an error handling function to tell the user that no subcommand was found or to have different functionality in case no subcommand was found. If this is False, then the group callback will always be invoked first. This means that the checks and the parsing dictated by its parameters will be executed. Defaults to False.

Type:

bool

case_insensitive

Indicates if the group’s commands should be case insensitive. Defaults to False.

Type:

bool

@after_invoke[source]

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

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

This post-invoke hook takes a sole parameter, a Context.

See Bot.after_invoke() for more info.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke[source]

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

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

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

See Bot.before_invoke() for more info.

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@command(*args, **kwargs)[source]

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

Returns:

A decorator that converts the provided method into a Command, adds it to the bot, then returns it.

Return type:

Callable[…, Command]

@error[source]

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

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

Parameters:

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@group(*args, **kwargs)[source]

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

Returns:

A decorator that converts the provided method into a Group, adds it to the bot, then returns it.

Return type:

Callable[…, Group]

copy()[source]

Creates a copy of this Group.

Returns:

A new instance of this group.

Return type:

Group

add_check(func)[source]

Adds a check to the command.

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

New in version 1.3.

Parameters:

func – The function that will be used as a check.

add_command(command)[source]

Adds a Command into the internal list of commands.

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

Changed in version 1.4: Raise CommandRegistrationError instead of generic ClientException

Parameters:

command (Command) – The command to add.

Raises:
await can_run(ctx)[source]

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute. This also checks whether the command is disabled.

Changed in version 1.3: Checks whether the command is disabled.

Parameters:

ctx (Context) – The ctx of the command currently being invoked.

Raises:

CommandError – Any command error that was raised during a check call will be propagated by this function.

Returns:

Whether the command can be invoked.

Return type:

bool

property clean_params[source]

Dict[str, inspect.Parameter]: Retrieves the parameter dictionary without the context or self parameters.

Useful for inspecting signature.

property cog_name[source]

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

Type:

Optional[str]

property commands[source]

A unique set of commands without aliases that are registered.

Type:

Set[Command]

property full_parent_name[source]

Retrieves the fully qualified parent command name.

This the base command name required to execute it. For example, in ?one two three the parent name would be one two.

Type:

str

get_command(name)[source]

Get a Command from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. 'foo bar') will get the subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

Parameters:

name (str) – The name of the command to get.

Returns:

The command that was requested. If not found, returns None.

Return type:

Optional[Command]

get_cooldown_retry_after(ctx)[source]

Retrieves the amount of seconds before this command can be tried again.

New in version 1.4.

Parameters:

ctx (Context) – The invocation context to retrieve the cooldown from.

Returns:

The amount of time left on this command’s cooldown in seconds. If this is 0.0 then the command isn’t on cooldown.

Return type:

float

has_error_handler()[source]

Whether the command has an error handler registered.

New in version 1.7.

Return type:

bool

is_on_cooldown(ctx)[source]

Checks whether the command is currently on cooldown.

Parameters:

ctx (Context) – The invocation context to use when checking the commands cooldown status.

Returns:

A boolean indicating if the command is on cooldown.

Return type:

bool

property parents[source]

Retrieves the parents of this command.

If the command has no parents then it returns an empty list.

For example in commands ?a b c test, the parents are [c, b, a].

New in version 1.1.

Type:

List[Group]

property qualified_name[source]

Retrieves the fully qualified command name.

This is the full parent name with the command name as well. For example, in ?one two three the qualified name would be one two three.

Type:

str

remove_check(func)[source]

Removes a check from the command.

This function is idempotent and will not raise an exception if the function is not in the command’s checks.

New in version 1.3.

Parameters:

func – The function to remove from the checks.

remove_command(name)[source]

Remove a Command from the internal list of commands.

This could also be used as a way to remove aliases.

Parameters:

name (str) – The name of the command to remove.

Returns:

The command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[Command]

reset_cooldown(ctx)[source]

Resets the cooldown on this command.

Parameters:

ctx (Context) – The invocation context to reset the cooldown under.

property root_parent[source]

Retrieves the root parent of this command.

If the command has no parents then it returns None.

For example in commands ?a b c test, the root parent is a.

Type:

Optional[Group]

property short_doc[source]

Gets the “short” documentation of a command.

By default, this is the brief attribute. If that lookup leads to an empty string then the first line of the help attribute is used instead.

Type:

str

property signature[source]

Returns a POSIX-like signature useful for help command output.

Type:

str

update(**kwargs)[source]

Updates Command instance with updated attribute.

This works similarly to the command() decorator in terms of parameters in that they are passed to the Command or subclass constructors, sans the name and callback.

for ... in walk_commands()[source]

An iterator that recursively walks through all commands and subcommands.

Changed in version 1.4: Duplicates due to aliases are no longer returned

Yields:

Union[Command, Group] – A command or group from the internal list of commands.

GroupMixin

class disnake.ext.commands.GroupMixin(*args, case_insensitive=False, **kwargs)[source]

A mixin that implements common functionality for classes that behave similar to Group and are allowed to register commands.

all_commands

A mapping of command name to Command objects.

Type:

dict

case_insensitive

Whether the commands should be case insensitive. Defaults to False.

Type:

bool

@command(*args, **kwargs)[source]

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

Returns:

A decorator that converts the provided method into a Command, adds it to the bot, then returns it.

Return type:

Callable[…, Command]

@group(*args, **kwargs)[source]

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

Returns:

A decorator that converts the provided method into a Group, adds it to the bot, then returns it.

Return type:

Callable[…, Group]

property commands[source]

A unique set of commands without aliases that are registered.

Type:

Set[Command]

add_command(command)[source]

Adds a Command into the internal list of commands.

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

Changed in version 1.4: Raise CommandRegistrationError instead of generic ClientException

Parameters:

command (Command) – The command to add.

Raises:
remove_command(name)[source]

Remove a Command from the internal list of commands.

This could also be used as a way to remove aliases.

Parameters:

name (str) – The name of the command to remove.

Returns:

The command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[Command]

for ... in walk_commands()[source]

An iterator that recursively walks through all commands and subcommands.

Changed in version 1.4: Duplicates due to aliases are no longer returned

Yields:

Union[Command, Group] – A command or group from the internal list of commands.

get_command(name)[source]

Get a Command from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. 'foo bar') will get the subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

Parameters:

name (str) – The name of the command to get.

Returns:

The command that was requested. If not found, returns None.

Return type:

Optional[Command]

LargeInt

class disnake.ext.commands.LargeInt[source]

Type for large integers in slash commands.

This is a class which inherits from int to allow large numbers in slash commands, meant to be used only for annotations.

Range

class disnake.ext.commands.Range[source]

Type depicting a limited range of allowed values.

See Number Ranges for more information.

New in version 2.4.

String

class disnake.ext.commands.String[source]

Type depicting a string option with limited length.

See String Lengths for more information.

New in version 2.6.

Cogs

Cog

class disnake.ext.commands.Cog(*args, **kwargs)[source]

The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the Cogs page.

When inheriting from this class, the options shown in CogMeta are equally valid here.

get_commands()[source]

Returns a list of commands the cog has.

Returns:

A list of Commands that are defined inside this cog.

Note

This does not include subcommands.

Return type:

List[Command]

get_application_commands()[source]

Returns a list of application commands the cog has.

Returns:

A list of InvokableApplicationCommands that are defined inside this cog.

Note

This does not include subcommands.

Return type:

List[InvokableApplicationCommand]

get_slash_commands()[source]

Returns a list of slash commands the cog has.

Returns:

A list of InvokableSlashCommands that are defined inside this cog.

Note

This does not include subcommands.

Return type:

List[InvokableSlashCommand]

get_user_commands()[source]

Returns a list of user commands the cog has.

Returns:

A list of InvokableUserCommands that are defined inside this cog.

Return type:

List[InvokableUserCommand]

get_message_commands()[source]

Returns a list of message commands the cog has.

Returns:

A list of InvokableMessageCommands that are defined inside this cog.

Return type:

List[InvokableMessageCommand]

property qualified_name[source]

Returns the cog’s specified name, not the class name.

Type:

str

property description[source]

Returns the cog’s description, typically the cleaned docstring.

Type:

str

for ... in walk_commands()[source]

An iterator that recursively walks through this cog’s commands and subcommands.

Yields:

Union[Command, Group] – A command or group from the cog.

get_listeners()[source]

Returns a list of (name, function) listener pairs the cog has.

Returns:

The listeners defined in this cog.

Return type:

List[Tuple[str, coroutine]]

classmethod listener(name=...)[source]

A decorator that marks a function as a listener.

This is the cog equivalent of Bot.listen().

Parameters:

name (Union[str, Event]) – The name of the event being listened to. If not provided, it defaults to the function’s name.

Raises:

TypeError – The function is not a coroutine function or a string or an Event enum member was not passed as the name.

has_error_handler()[source]

Whether the cog has an error handler.

New in version 1.7.

Return type:

bool

has_slash_error_handler()[source]

Whether the cog has a slash command error handler.

Return type:

bool

has_user_error_handler()[source]

Whether the cog has a user command error handler.

Return type:

bool

has_message_error_handler()[source]

Whether the cog has a message command error handler.

Return type:

bool

await cog_load()[source]

A special method that is called as a task when the cog is added.

cog_unload()[source]

A special method that is called when the cog gets removed.

This function cannot be a coroutine. It must be a regular function.

Subclasses must replace this if they want special unloading behaviour.

bot_check_once(ctx)[source]

A special method that registers as a Bot.check_once() check.

This is for text commands only, and doesn’t apply to application commands.

This function can be a coroutine and must take a sole parameter, ctx, to represent the Context.

bot_check(ctx)[source]

A special method that registers as a Bot.check() check.

This is for text commands only, and doesn’t apply to application commands.

This function can be a coroutine and must take a sole parameter, ctx, to represent the Context.

bot_slash_command_check_once(inter)[source]

A special method that registers as a Bot.slash_command_check_once() check.

This function can be a coroutine and must take a sole parameter, inter, to represent the ApplicationCommandInteraction.

bot_slash_command_check(inter)[source]

A special method that registers as a Bot.slash_command_check() check.

This function can be a coroutine and must take a sole parameter, inter, to represent the ApplicationCommandInteraction.

bot_user_command_check_once(inter)[source]

Similar to Bot.slash_command_check_once() but for user commands.

bot_user_command_check(inter)[source]

Similar to Bot.slash_command_check() but for user commands.

bot_message_command_check_once(inter)[source]

Similar to Bot.slash_command_check_once() but for message commands.

bot_message_command_check(inter)[source]

Similar to Bot.slash_command_check() but for message commands.

cog_check(ctx)[source]

A special method that registers as a check() for every text command and subcommand in this cog.

This is for text commands only, and doesn’t apply to application commands.

This function can be a coroutine and must take a sole parameter, ctx, to represent the Context.

cog_slash_command_check(inter)[source]

A special method that registers as a check() for every slash command and subcommand in this cog.

This function can be a coroutine and must take a sole parameter, inter, to represent the ApplicationCommandInteraction.

cog_user_command_check(inter)[source]

Similar to Cog.cog_slash_command_check() but for user commands.

cog_message_command_check(inter)[source]

Similar to Cog.cog_slash_command_check() but for message commands.

await cog_command_error(ctx, error)[source]

A special method that is called whenever an error is dispatched inside this cog.

This is for text commands only, and doesn’t apply to application commands.

This is similar to on_command_error() except only applying to the commands inside this cog.

This must be a coroutine.

Parameters:
  • ctx (Context) – The invocation context where the error happened.

  • error (CommandError) – The error that was raised.

await cog_slash_command_error(inter, error)[source]

A special method that is called whenever an error is dispatched inside this cog.

This is similar to on_slash_command_error() except only applying to the slash commands inside this cog.

This must be a coroutine.

Parameters:
await cog_user_command_error(inter, error)[source]

Similar to cog_slash_command_error() but for user commands.

await cog_message_command_error(inter, error)[source]

Similar to cog_slash_command_error() but for message commands.

await cog_before_invoke(ctx)[source]

A special method that acts as a cog local pre-invoke hook, similar to Command.before_invoke().

This is for text commands only, and doesn’t apply to application commands.

This must be a coroutine.

Parameters:

ctx (Context) – The invocation context.

await cog_after_invoke(ctx)[source]

A special method that acts as a cog local post-invoke hook, similar to Command.after_invoke().

This is for text commands only, and doesn’t apply to application commands.

This must be a coroutine.

Parameters:

ctx (Context) – The invocation context.

await cog_before_slash_command_invoke(inter)[source]

A special method that acts as a cog local pre-invoke hook.

This is similar to Command.before_invoke() but for slash commands.

This must be a coroutine.

Parameters:

inter (ApplicationCommandInteraction) – The interaction of the slash command.

await cog_after_slash_command_invoke(inter)[source]

A special method that acts as a cog local post-invoke hook.

This is similar to Command.after_invoke() but for slash commands.

This must be a coroutine.

Parameters:

inter (ApplicationCommandInteraction) – The interaction of the slash command.

await cog_before_user_command_invoke(inter)[source]

Similar to cog_before_slash_command_invoke() but for user commands.

await cog_after_user_command_invoke(inter)[source]

Similar to cog_after_slash_command_invoke() but for user commands.

await cog_before_message_command_invoke(inter)[source]

Similar to cog_before_slash_command_invoke() but for message commands.

await cog_after_message_command_invoke(inter)[source]

Similar to cog_after_slash_command_invoke() but for message commands.

CogMeta

class disnake.ext.commands.CogMeta(*args, **kwargs)[source]

A metaclass for defining a cog.

Note that you should probably not use this directly. It is exposed purely for documentation purposes along with making custom metaclasses to intermix with other metaclasses such as the abc.ABCMeta metaclass.

For example, to create an abstract cog mixin class, the following would be done.

import abc

class CogABCMeta(commands.CogMeta, abc.ABCMeta):
    pass

class SomeMixin(metaclass=abc.ABCMeta):
    pass

class SomeCogMixin(SomeMixin, commands.Cog, metaclass=CogABCMeta):
    pass

Note

When passing an attribute of a metaclass that is documented below, note that you must pass it as a keyword-only argument to the class creation like the following example:

class MyCog(commands.Cog, name='My Cog'):
    pass
name

The cog name. By default, it is the name of the class with no modification.

Type:

str

description

The cog description. By default, it is the cleaned docstring of the class.

New in version 1.6.

Type:

str

command_attrs

A list of attributes to apply to every command inside this cog. The dictionary is passed into the Command options at __init__. If you specify attributes inside the command attribute in the class, it will override the one specified inside this attribute. For example:

class MyCog(commands.Cog, command_attrs=dict(hidden=True)):
    @commands.command()
    async def foo(self, ctx):
        pass # hidden -> True

    @commands.command(hidden=False)
    async def bar(self, ctx):
        pass # hidden -> False
Type:

Dict[str, Any]

slash_command_attrs

A list of attributes to apply to every slash command inside this cog. The dictionary is passed into the options of every InvokableSlashCommand at __init__. Usage of this kwarg is otherwise the same as with command_attrs.

Note

This does not apply to instances of SubCommand or SubCommandGroup.

New in version 2.5.

Type:

Dict[str, Any]

user_command_attrs

A list of attributes to apply to every user command inside this cog. The dictionary is passed into the options of every InvokableUserCommand at __init__. Usage of this kwarg is otherwise the same as with command_attrs.

New in version 2.5.

Type:

Dict[str, Any]

message_command_attrs

A list of attributes to apply to every message command inside this cog. The dictionary is passed into the options of every InvokableMessageCommand at __init__. Usage of this kwarg is otherwise the same as with command_attrs.

New in version 2.5.

Type:

Dict[str, Any]

Help Commands

HelpCommand

class disnake.ext.commands.HelpCommand(*args, **kwargs)[source]

The base implementation for help command formatting.

Note

Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in #2123.

This means that relying on the state of this class to be the same between command invocations would not work as expected.

context

The context that invoked this help formatter. This is generally set after the help command assigned, command_callback(), has been called.

Type:

Optional[Context]

show_hidden

Specifies if hidden commands should be shown in the output. Defaults to False.

Type:

bool

verify_checks

Specifies if commands should have their Command.checks called and verified. If True, always calls Command.checks. If None, only calls Command.checks in a guild setting. If False, never calls Command.checks. Defaults to True.

Changed in version 1.7.

Type:

Optional[bool]

command_attrs

A dictionary of options to pass in for the construction of the help command. This allows you to change the command behaviour without actually changing the implementation of the command. The attributes will be the same as the ones passed in the Command constructor.

Type:

dict

add_check(func)[source]

Adds a check to the help command.

New in version 1.4.

Parameters:

func – The function that will be used as a check.

remove_check(func)[source]

Removes a check from the help command.

This function is idempotent and will not raise an exception if the function is not in the command’s checks.

New in version 1.4.

Parameters:

func – The function to remove from the checks.

get_bot_mapping()[source]

Retrieves the bot mapping passed to send_bot_help().

property invoked_with[source]

Similar to Context.invoked_with except properly handles the case where Context.send_help() is used.

If the help command was used regularly then this returns the Context.invoked_with attribute. Otherwise, if it the help command was called using Context.send_help() then it returns the internal command name of the help command.

Returns:

The command name that triggered this invocation.

Return type:

str

get_command_signature(command)[source]

Retrieves the signature portion of the help page.

Parameters:

command (Command) – The command to get the signature of.

Returns:

The signature for the command.

Return type:

str

remove_mentions(string)[source]

Removes mentions from the string to prevent abuse.

This includes @everyone, @here, member mentions and role mentions.

Returns:

The string with mentions removed.

Return type:

str

property cog[source]

A property for retrieving or setting the cog for the help command.

When a cog is set for the help command, it is as-if the help command belongs to that cog. All cog special methods will apply to the help command and it will be automatically unset on unload.

To unbind the cog from the help command, you can set it to None.

Returns:

The cog that is currently set for the help command.

Return type:

Optional[Cog]

command_not_found(string)[source]

This function could be a coroutine.

A method called when a command is not found in the help command. This is useful to override for i18n.

Defaults to No command called {0} found.

Parameters:

string (str) – The string that contains the invalid command. Note that this has had mentions removed to prevent abuse.

Returns:

The string to use when a command has not been found.

Return type:

str

subcommand_not_found(command, string)[source]

This function could be a coroutine.

A method called when a command did not have a subcommand requested in the help command. This is useful to override for i18n.

Defaults to either:

  • 'Command "{command.qualified_name}" has no subcommands.'
    • If there is no subcommand in the command parameter.

  • 'Command "{command.qualified_name}" has no subcommand named {string}'
    • If the command parameter has subcommands but not one named string.

Parameters:
  • command (Command) – The command that did not have the subcommand requested.

  • string (str) – The string that contains the invalid subcommand. Note that this has had mentions removed to prevent abuse.

Returns:

The string to use when the command did not have the subcommand requested.

Return type:

str

await filter_commands(commands, *, sort=False, key=None)[source]

This function is a coroutine.

Returns a filtered list of commands and optionally sorts them.

This takes into account the verify_checks and show_hidden attributes.

Parameters:
  • commands (Iterable[Command]) – An iterable of commands that are getting filtered.

  • sort (bool) – Whether to sort the result.

  • key (Optional[Callable[Command, Any]]) – An optional key function to pass to sorted() that takes a Command as its sole parameter. If sort is passed as True then this will default as the command name.

Returns:

A list of commands that passed the filter.

Return type:

List[Command]

get_max_size(commands)[source]

Returns the largest name length of the specified command list.

Parameters:

commands (Sequence[Command]) – A sequence of commands to check for the largest size.

Returns:

The maximum width of the commands.

Return type:

int

get_destination()[source]

Returns the Messageable where the help command will be output.

You can override this method to customise the behaviour.

By default this returns the context’s channel.

Returns:

The destination where the help command will be output.

Return type:

abc.Messageable

await send_error_message(error)[source]

This function is a coroutine.

Handles the implementation when an error happens in the help command. For example, the result of command_not_found() will be passed here.

You can override this method to customise the behaviour.

By default, this sends the error message to the destination specified by get_destination().

Note

You can access the invocation context with HelpCommand.context.

Parameters:

error (str) – The error message to display to the user. Note that this has had mentions removed to prevent abuse.

await on_help_command_error(ctx, error)[source]

This function is a coroutine.

The help command’s error handler, as specified by Error Handling.

Useful to override if you need some specific behaviour when the error handler is called.

By default this method does nothing and just propagates to the default error handlers.

Parameters:
  • ctx (Context) – The invocation context.

  • error (CommandError) – The error that was raised.

await send_bot_help(mapping)[source]

This function is a coroutine.

Handles the implementation of the bot command page in the help command. This function is called when the help command is called with no arguments.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

Note

You can access the invocation context with HelpCommand.context.

Also, the commands in the mapping are not filtered. To do the filtering you will have to call filter_commands() yourself.

Parameters:

mapping (Mapping[Optional[Cog], List[Command]]) – A mapping of cogs to commands that have been requested by the user for help. The key of the mapping is the Cog that the command belongs to, or None if there isn’t one, and the value is a list of commands that belongs to that cog.

await send_cog_help(cog)[source]

This function is a coroutine.

Handles the implementation of the cog page in the help command. This function is called when the help command is called with a cog as the argument.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

Note

You can access the invocation context with HelpCommand.context.

To get the commands that belong to this cog see Cog.get_commands(). The commands returned not filtered. To do the filtering you will have to call filter_commands() yourself.

Parameters:

cog (Cog) – The cog that was requested for help.

await send_group_help(group)[source]

This function is a coroutine.

Handles the implementation of the group page in the help command. This function is called when the help command is called with a group as the argument.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

Note

You can access the invocation context with HelpCommand.context.

To get the commands that belong to this group without aliases see Group.commands. The commands returned are not filtered. To do the filtering you will have to call filter_commands() yourself.

Parameters:

group (Group) – The group that was requested for help.

await send_command_help(command)[source]

This function is a coroutine.

Handles the implementation of the single command page in the help command.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

Note

You can access the invocation context with HelpCommand.context.

Showing Help

There are certain attributes and methods that are helpful for a help command to show such as the following:

There are more than just these attributes but feel free to play around with these to help you get started to get the output that you want.

Parameters:

command (Command) – The command that was requested for help.

await prepare_help_command(ctx, command=None)[source]

This function is a coroutine.

A low level method that can be used to prepare the help command before it does anything. For example, if you need to prepare some state in your subclass before the command does its processing then this would be the place to do it.

The default implementation does nothing.

Note

This is called inside the help command callback body. So all the usual rules that happen inside apply here as well.

Parameters:
  • ctx (Context) – The invocation context.

  • command (Optional[str]) – The argument passed to the help command.

await command_callback(ctx, *, command=None)[source]

This function is a coroutine.

The actual implementation of the help command.

It is not recommended to override this method and instead change the behaviour through the methods that actually get dispatched.

DefaultHelpCommand

class disnake.ext.commands.DefaultHelpCommand(*args, **kwargs)[source]

The implementation of the default help command.

This inherits from HelpCommand.

It extends it with the following attributes.

width

The maximum number of characters that fit in a line. Defaults to 80.

Type:

int

sort_commands

Whether to sort the commands in the output alphabetically. Defaults to True.

Type:

bool

dm_help

A tribool that indicates if the help command should DM the user instead of sending it to the channel it received it from. If the boolean is set to True, then all help output is DM’d. If False, none of the help output is DM’d. If None, then the bot will only DM when the help message becomes too long (dictated by more than dm_help_threshold characters). Defaults to False.

Type:

Optional[bool]

dm_help_threshold

The number of characters the paginator must accumulate before getting DM’d to the user if dm_help is set to None. Defaults to 1000.

Type:

Optional[int]

indent

How much to indent the commands from a heading. Defaults to 2.

Type:

int

commands_heading

The command list’s heading string used when the help command is invoked with a category name. Useful for i18n. Defaults to "Commands:"

Type:

str

no_category

The string used when there is a command which does not belong to any category(cog). Useful for i18n. Defaults to "No Category"

Type:

str

paginator

The paginator used to paginate the help command output.

Type:

Paginator

shorten_text(text)[source]

Shortens text to fit into the width.

Return type:

str

get_ending_note()[source]

Returns help command’s ending note. This is mainly useful to override for i18n purposes.

Return type:

str

add_indented_commands(commands, *, heading, max_size=None)[source]

Indents a list of commands after the specified heading.

The formatting is added to the paginator.

The default implementation is the command name indented by indent spaces, padded to max_size followed by the command’s Command.short_doc and then shortened to fit into the width.

Parameters:
  • commands (Sequence[Command]) – A list of commands to indent for output.

  • heading (str) – The heading to add to the output. This is only added if the list of commands is greater than 0.

  • max_size (Optional[int]) – The max size to use for the gap between indents. If unspecified, calls get_max_size() on the commands parameter.

await send_pages()[source]

A helper utility to send the page output from paginator to the destination.

add_command_formatting(command)[source]

A utility function to format the non-indented block of commands and groups.

Parameters:

command (Command) – The command to format.

get_destination()[source]

Returns the Messageable where the help command will be output.

You can override this method to customise the behaviour.

By default this returns the context’s channel.

Returns:

The destination where the help command will be output.

Return type:

abc.Messageable

MinimalHelpCommand

class disnake.ext.commands.MinimalHelpCommand(*args, **kwargs)[source]

An implementation of a help command with minimal output.

This inherits from HelpCommand.

sort_commands

Whether to sort the commands in the output alphabetically. Defaults to True.

Type:

bool

commands_heading

The command list’s heading string used when the help command is invoked with a category name. Useful for i18n. Defaults to "Commands"

Type:

str

aliases_heading

The alias list’s heading string used to list the aliases of the command. Useful for i18n. Defaults to "Aliases:".

Type:

str

dm_help

A tribool that indicates if the help command should DM the user instead of sending it to the channel it received it from. If the boolean is set to True, then all help output is DM’d. If False, none of the help output is DM’d. If None, then the bot will only DM when the help message becomes too long (dictated by more than dm_help_threshold characters). Defaults to False.

Type:

Optional[bool]

dm_help_threshold

The number of characters the paginator must accumulate before getting DM’d to the user if dm_help is set to None. Defaults to 1000.

Type:

Optional[int]

no_category

The string used when there is a command which does not belong to any category(cog). Useful for i18n. Defaults to "No Category"

Type:

str

paginator

The paginator used to paginate the help command output.

Type:

Paginator

await send_pages()[source]

A helper utility to send the page output from paginator to the destination.

get_opening_note()[source]

Returns help command’s opening note. This is mainly useful to override for i18n purposes.

The default implementation returns

Use `{prefix}{command_name} [command]` for more info on a command.
You can also use `{prefix}{command_name} [category]` for more info on a category.
Returns:

The help command opening note.

Return type:

str

get_command_signature(command)[source]

Retrieves the signature portion of the help page.

Parameters:

command (Command) – The command to get the signature of.

Returns:

The signature for the command.

Return type:

str

get_ending_note()[source]

Return the help command’s ending note. This is mainly useful to override for i18n purposes.

The default implementation does nothing.

Returns:

The help command ending note.

Return type:

str

add_bot_commands_formatting(commands, heading)[source]

Adds the minified bot heading with commands to the output.

The formatting should be added to the paginator.

The default implementation is a bold underline heading followed by commands separated by an EN SPACE (U+2002) in the next line.

Parameters:
  • commands (Sequence[Command]) – A list of commands that belong to the heading.

  • heading (str) – The heading to add to the line.

add_subcommand_formatting(command)[source]

Adds formatting information on a subcommand.

The formatting should be added to the paginator.

The default implementation is the prefix and the Command.qualified_name optionally followed by an En dash and the command’s Command.short_doc.

Parameters:

command (Command) – The command to show information of.

add_aliases_formatting(aliases)[source]

Adds the formatting information on a command’s aliases.

The formatting should be added to the paginator.

The default implementation is the aliases_heading bolded followed by a comma separated list of aliases.

This is not called if there are no aliases to format.

Parameters:

aliases (Sequence[str]) – A list of aliases to format.

add_command_formatting(command)[source]

A utility function to format commands and groups.

Parameters:

command (Command) – The command to format.

get_destination()[source]

Returns the Messageable where the help command will be output.

You can override this method to customise the behaviour.

By default this returns the context’s channel.

Returns:

The destination where the help command will be output.

Return type:

abc.Messageable

Paginator

Methods
class disnake.ext.commands.Paginator(prefix='```', suffix='```', max_size=2000, linesep='\n')[source]

A class that aids in paginating code blocks for Discord messages.

len(x)

Returns the total number of characters in the paginator.

prefix

The prefix inserted to every page. e.g. three backticks.

Type:

str

suffix

The suffix appended at the end of every page. e.g. three backticks.

Type:

str

max_size

The maximum amount of codepoints allowed in a page.

Type:

int

linesep
The character string inserted between lines. e.g. a newline character.

New in version 1.7.

Type:

str

clear()[source]

Clears the paginator to have no pages.

add_line(line='', *, empty=False)[source]

Adds a line to the current page.

If the line exceeds the max_size then an exception is raised.

Parameters:
  • line (str) – The line to add.

  • empty (bool) – Whether another empty line should be added.

Raises:

RuntimeError – The line was too big for the current max_size.

close_page()[source]

Prematurely terminate a page.

property pages[source]

Returns the rendered list of pages.

Type:

List[str]

Enums

class disnake.ext.commands.BucketType[source]

Specifies a type of bucket for, e.g. a cooldown.

default

The default bucket operates on a global basis.

user

The user bucket operates on a per-user basis.

guild

The guild bucket operates on a per-guild basis.

channel

The channel bucket operates on a per-channel basis.

member

The member bucket operates on a per-member basis.

category

The category bucket operates on a per-category basis.

role

The role bucket operates on a per-role basis.

New in version 1.3.

Checks

@disnake.ext.commands.check(predicate)[source]

A decorator that adds a check to the Command or its subclasses. These checks could be accessed via Command.checks.

These checks should be predicates that take in a single parameter taking a Context. If the check returns a False-like value then during invocation a CheckFailure exception is raised and sent to the on_command_error() event.

If an exception should be thrown in the predicate then it should be a subclass of CommandError. Any exception not subclassed from it will be propagated while those subclassed will be sent to on_command_error().

A special attribute named predicate is bound to the value returned by this decorator to retrieve the predicate passed to the decorator. This allows the following introspection and chaining to be done:

def owner_or_permissions(**perms):
    original = commands.has_permissions(**perms).predicate
    async def extended_check(ctx):
        if ctx.guild is None:
            return False
        return ctx.guild.owner_id == ctx.author.id or await original(ctx)
    return commands.check(extended_check)

Note

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

Changed in version 1.3: The predicate attribute was added.

Examples

Creating a basic check to see if the command invoker is you.

def check_if_it_is_me(ctx):
    return ctx.message.author.id == 85309593344815104

@bot.command()
@commands.check(check_if_it_is_me)
async def only_for_me(ctx):
    await ctx.send('I know you!')

Transforming common checks into its own decorator:

def is_me():
    def predicate(ctx):
        return ctx.message.author.id == 85309593344815104
    return commands.check(predicate)

@bot.command()
@is_me()
async def only_me(ctx):
    await ctx.send('Only you!')
Parameters:

predicate (Callable[[Context], bool]) – The predicate to check if the command should be invoked.

@disnake.ext.commands.check_any(*checks)[source]

A check() that is added that checks if any of the checks passed will pass, i.e. using logical OR.

If all checks fail then CheckAnyFailure is raised to signal the failure. It inherits from CheckFailure.

Note

The predicate attribute for this function is a coroutine.

New in version 1.3.

Parameters:

*checks (Callable[[Context], 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.

Examples

Creating a basic check to see if it’s the bot owner or the server owner:

def is_guild_owner():
    def predicate(ctx):
        return ctx.guild is not None and ctx.guild.owner_id == ctx.author.id
    return commands.check(predicate)

@bot.command()
@commands.check_any(commands.is_owner(), is_guild_owner())
async def only_for_owners(ctx):
    await ctx.send('Hello mister owner!')
@disnake.ext.commands.has_role(item)[source]

A check() that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return False.

This check raises one of two special exceptions, MissingRole if the user is missing a role, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

Changed in version 1.1: Raise MissingRole or NoPrivateMessage instead of generic CheckFailure

Parameters:

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

@disnake.ext.commands.has_permissions(**perms)[source]

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 disnake.Permissions.

This check raises a special exception, MissingPermissions that is inherited from CheckFailure.

Changed in version 2.6: Considers if the author is timed out.

Parameters:

perms – An argument list of permissions to check for.

Example

@bot.command()
@commands.has_permissions(manage_messages=True)
async def test(ctx):
    await ctx.send('You can manage messages.')
@disnake.ext.commands.has_guild_permissions(**perms)[source]

Similar to has_permissions(), but operates on guild wide permissions instead of the current channel permissions.

If this check is called in a DM context, it will raise an exception, NoPrivateMessage.

New in version 1.3.

@disnake.ext.commands.has_any_role(*items)[source]

A check() that is added that checks if the member invoking the command has any of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.

Similar to has_role(), the names or IDs passed in must be exact.

This check raises one of two special exceptions, MissingAnyRole if the user is missing all roles, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

Changed in version 1.1: Raise MissingAnyRole or NoPrivateMessage instead of generic CheckFailure

Parameters:

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

Example

@bot.command()
@commands.has_any_role('Library Devs', 'Moderators', 492212595072434186)
async def cool(ctx):
    await ctx.send('You are cool indeed')
@disnake.ext.commands.bot_has_role(item)[source]

Similar to has_role() except checks if the bot itself has the role.

This check raises one of two special exceptions, BotMissingRole if the bot is missing the role, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

Changed in version 1.1: Raise BotMissingRole or NoPrivateMessage instead of generic CheckFailure

@disnake.ext.commands.bot_has_permissions(**perms)[source]

Similar to has_permissions() except checks if the bot itself has the permissions listed.

This check raises a special exception, BotMissingPermissions that is inherited from CheckFailure.

Changed in version 2.6: Considers if the author is timed out.

@disnake.ext.commands.bot_has_guild_permissions(**perms)[source]

Similar to has_guild_permissions(), but checks the bot members guild permissions.

New in version 1.3.

@disnake.ext.commands.bot_has_any_role(*items)[source]

Similar to has_any_role() except checks if the bot itself has any of the roles listed.

This check raises one of two special exceptions, BotMissingAnyRole if the bot is missing all roles, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

Changed in version 1.1: Raise BotMissingAnyRole or NoPrivateMessage instead of generic checkfailure

@disnake.ext.commands.cooldown(rate, per, type=disnake.ext.commands.BucketType.default)[source]

A decorator that adds a cooldown to a Command

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

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

A command can only have a single cooldown.

Parameters:
  • rate (int) – The number of times a command can be used before triggering a cooldown.

  • per (float) – The amount of seconds to wait for a cooldown when it’s been triggered.

  • type (Union[BucketType, Callable[[Message], Any]]) –

    The type of cooldown to have. If callable, should return a key for the mapping.

    Changed in version 1.7: Callables are now supported for custom bucket types.

@disnake.ext.commands.dynamic_cooldown(cooldown, type=BucketType.default)[source]

A decorator that adds a dynamic cooldown to a Command

This differs from cooldown() in that it takes a function that accepts a single parameter of type disnake.Message and must return a Cooldown or None. If None is returned then that cooldown is effectively bypassed.

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

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

A command can only have a single cooldown.

New in version 2.0.

Parameters:
  • cooldown (Callable[[disnake.Message], Optional[Cooldown]]) – A function that takes a message and returns a cooldown that will apply to this invocation or None if the cooldown should be bypassed.

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

@disnake.ext.commands.max_concurrency(number, per=disnake.ext.commands.BucketType.default, *, wait=False)[source]

A decorator that adds a maximum concurrency to a Command or its subclasses.

This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket – only a set number of people can run the command.

New in version 1.3.

Parameters:
  • number (int) – The maximum number of invocations of this command that can be running at the same time.

  • per (BucketType) – The bucket that this concurrency is based on, e.g. BucketType.guild would allow it to be used up to number times per guild.

  • wait (bool) – Whether the command should wait for the queue to be over. If this is set to False then instead of waiting until the command can run again, the command raises MaxConcurrencyReached to its error handler. If this is set to True then the command waits until it can be executed.

@disnake.ext.commands.before_invoke(coro)[source]

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

This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog.

New in version 1.4.

Example

async def record_usage(ctx):
    print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at)

@bot.command()
@commands.before_invoke(record_usage)
async def who(ctx): # Output: <User> used who at <Time>
    await ctx.send('i am a bot')

class What(commands.Cog):

    @commands.before_invoke(record_usage)
    @commands.command()
    async def when(self, ctx): # Output: <User> used when at <Time>
        await ctx.send(f'and i have existed since {ctx.bot.user.created_at}')

    @commands.command()
    async def where(self, ctx): # Output: <Nothing>
        await ctx.send('on Discord')

    @commands.command()
    async def why(self, ctx): # Output: <Nothing>
        await ctx.send('because someone made me')

bot.add_cog(What())
@disnake.ext.commands.after_invoke(coro)[source]

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

This allows you to refer to one after invoke hook for several commands that do not have to be within the same cog.

New in version 1.4.

@disnake.ext.commands.guild_only()[source]

A check() that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

This check raises a special exception, NoPrivateMessage that is inherited from CheckFailure.

@disnake.ext.commands.dm_only()[source]

A check() that indicates this command must only be used in a DM context. Only private messages are allowed when using the command.

This check raises a special exception, PrivateMessageOnly that is inherited from CheckFailure.

New in version 1.1.

@disnake.ext.commands.is_owner()[source]

A check() that checks if the person invoking this command is the owner of the bot.

This is powered by Bot.is_owner().

This check raises a special exception, NotOwner that is derived from CheckFailure.

@disnake.ext.commands.is_nsfw()[source]

A check() that checks if the channel is a NSFW channel.

This check raises a special exception, NSFWChannelRequired that is derived from CheckFailure.

Changed in version 1.1: Raise NSFWChannelRequired instead of generic CheckFailure. DM channels will also now pass this check.

@disnake.ext.commands.default_member_permissions(value=0, **permissions)[source]

A decorator that sets default required member permissions for the command. Unlike has_permissions(), this decorator does not add any checks. Instead, it prevents the command from being run by members without all required permissions, if not overridden by moderators on a guild-specific basis.

See also the default_member_permissions parameter for application command decorators.

Note

This does not work with slash subcommands/groups.

Example

This would only allow members with manage_messages and view_audit_log permissions to use the command by default, however moderators can override this and allow/disallow specific users and roles to use the command in their guilds regardless of this setting.

@bot.slash_command()
@commands.default_member_permissions(manage_messages=True, view_audit_log=True)
async def purge(inter, num: int):
    ...
Parameters:
  • value (int) – A raw permission bitfield of an integer representing the required permissions. May be used instead of specifying kwargs.

  • **permissions (bool) – The required permissions for a command. A member must have all these permissions to be able to invoke the command. Setting a permission to False does not affect the result.

Cooldown

Attributes
class disnake.ext.commands.Cooldown(rate, per)[source]

Represents a cooldown for a command.

rate

The total number of tokens available per per seconds.

Type:

int

per

The length of the cooldown period in seconds.

Type:

float

get_tokens(current=None)[source]

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 then time.time() is used.

Returns:

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

Return type:

int

get_retry_after(current=None)[source]

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, then time.time() is used.

Returns:

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

Return type:

float

update_rate_limit(current=None)[source]

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, then time.time() is used.

Returns:

The retry-after time in seconds if rate limited.

Return type:

Optional[float]

reset()[source]

Reset the cooldown to its initial state.

copy()[source]

Creates a copy of this cooldown.

Returns:

A new instance of this cooldown.

Return type:

Cooldown

Context

class disnake.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, subcommand_passed=None, command_failed=False, current_parameter=None)[source]

Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the abc.Messageable ABC.

message

The message that triggered the command being executed.

Type:

Message

bot

The bot that contains the command being executed.

Type:

Bot

args

The list of transformed arguments that were passed into the command. If this is accessed during the on_command_error() event then this list could be incomplete.

Type:

list

kwargs

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

Type:

dict

current_parameter

The parameter that is currently being inspected and converted. This is only of use for within converters.

New in version 2.0.

Type:

Optional[inspect.Parameter]

prefix

The prefix that was used to invoke the command.

Type:

Optional[str]

command

The command that is being invoked currently.

Type:

Optional[Command]

invoked_with

The command name that triggered this invocation. Useful for finding out which alias called the command.

Type:

Optional[str]

invoked_parents

The command names of the parents that triggered this invocation. Useful for finding out which aliases called the command.

For example in commands ?a b c test, the invoked parents are ['a', 'b', 'c'].

New in version 1.7.

Type:

List[str]

invoked_subcommand

The subcommand that was invoked. If no valid subcommand was invoked then this is equal to None.

Type:

Optional[Command]

subcommand_passed

The string that was attempted to call a subcommand. This does not have to point to a valid registered subcommand and could just point to a nonsense string. If nothing was passed to attempt a call to a subcommand then this is set to None.

Type:

Optional[str]

command_failed

Whether the command failed to be parsed, checked, or invoked.

Type:

bool

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]

Returns an AsyncIterator that enables receiving the destination’s message history.

You must have Permissions.read_message_history permission 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. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[abc.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[abc.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[abc.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.

Yields:

Message – The message with the message data parsed.

async with typing()[source]

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 and async with work with this.

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
await invoke(command, /, *args, **kwargs)[source]

This function is a coroutine.

Calls a command with the arguments given.

This is useful if you want to just call the callback that a Command holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function.

Parameters:
  • command (Command) – The command that is going to be called.

  • *args – The arguments to use.

  • **kwargs – The keyword arguments to use.

Raises:

TypeError – The command argument to invoke is missing.

await reinvoke(*, call_hooks=False, restart=True)[source]

This function is a coroutine.

Calls the command again.

This is similar to invoke() except that it bypasses checks, cooldowns, and error handlers.

Note

If you want to bypass UserInputError derived exceptions, it is recommended to use the regular invoke() as it will work more naturally. After all, this will end up using the old arguments the user has used and will thus just fail again.

Parameters:
  • call_hooks (bool) – Whether to call the before and after invoke hooks.

  • restart (bool) – Whether to start the call chain from the very beginning or where we left off (i.e. the command that caused the error). The default is to start where we left off.

Raises:

ValueError – The context to reinvoke is not valid.

property valid[source]

Whether the invocation context is valid to be invoked with.

Type:

bool

property clean_prefix[source]

The cleaned up invoke prefix. i.e. mentions are @name instead of <@id>.

New in version 2.0.

Type:

str

property cog[source]

Returns the cog associated with this context’s command. Returns None if it does not exist.

Type:

Optional[Cog]

guild

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

Type:

Optional[Guild]

channel

Returns the channel associated with this context’s command. Shorthand for Message.channel.

Type:

Union[abc.Messageable]

author

Union[User, Member]: Returns the author associated with this context’s command. Shorthand for Message.author

me

Union[Member, ClientUser]: Similar to Guild.me except it may return the ClientUser in private message contexts.

property voice_client[source]

A shortcut to Guild.voice_client, if applicable.

Type:

Optional[VoiceProtocol]

await send_help(entity=<bot>)[source]

This function is a coroutine.

Shows the help command for the specified entity if given. The entity can be a command or a cog.

If no entity is given, then it’ll show help for the entire bot.

If the entity is a string, then it looks up whether it’s a Cog or a Command.

Note

Due to the way this function works, instead of returning something similar to command_not_found() this returns None on bad input or no help command.

Parameters:

entity (Optional[Union[Command, Cog, str]]) – The entity to show help for.

Returns:

The result of the help command, if any.

Return type:

Any

await reply(content=None, *, fail_if_not_exists=True, **kwargs)[source]

This function is a coroutine.

A shortcut method to abc.Messageable.send() to reply to the Message.

New in version 1.6.

Changed in version 2.3: Added fail_if_not_exists keyword argument. Defaults to True.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:

fail_if_not_exists (bool) –

Whether replying using the message reference should raise HTTPException if the message no longer exists or Discord could not fetch the message.

New in version 2.3.

Raises:
  • HTTPException – Sending the message failed.

  • Forbidden – You do not have the proper permissions to send the message.

  • TypeError – You specified both embed and embeds, or file and files, or view and components.

  • ValueError – The files or embeds list is too large.

Returns:

The message that was sent.

Return type:

Message

await fetch_message(id, /)[source]

This function is a coroutine.

Retrieves a single Message from the destination.

Parameters:

id (int) – The message ID to look for.

Raises:
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

await pins()[source]

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

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

Raises:

HTTPException – Retrieving the pinned messages failed.

Returns:

The messages that are currently pinned.

Return type:

List[Message]

await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None)[source]

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content).

At least one of content, embed/embeds, file/files, stickers, components, or view must be provided.

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

Parameters:
  • content (Optional[str]) – The content of the message to send.

  • tts (bool) – Whether the message should be sent using text-to-speech.

  • embed (Embed) – The rich embed for the content to send. This cannot be mixed with the embeds parameter.

  • embeds (List[Embed]) –

    A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the embed parameter.

    New in version 2.0.

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

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    New in version 2.0.

  • nonce (Union[str, int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.allowed_mentions are used instead.

    New in version 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message to which you are replying, this can be created using Message.to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the AllowedMentions.replied_user attribute of allowed_mentions or by setting mention_author.

    New in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the AllowedMentions.replied_user attribute of allowed_mentions.

    New in version 1.6.

  • view (ui.View) –

    A Discord UI View to add to the message. This cannot be mixed with components.

    New in version 2.0.

  • components (Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow, disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –

    A list of components to include in the message. This cannot be mixed with view.

    New in version 2.4.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This hides all the embeds from the UI if set to True.

    New in version 2.5.

Raises:
Returns:

The message that was sent.

Return type:

Message

await trigger_typing()[source]

This function is a coroutine.

Triggers a typing indicator to the destination.

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

Converters

class disnake.ext.commands.Converter(*args, **kwargs)[source]

The base class of custom converters that require the Context or ApplicationCommandInteraction to be passed to be useful.

This allows you to implement converters that function similar to the special cased disnake classes.

Classes that derive from this should override the convert() method to do its conversion logic. This method must be a coroutine.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.ObjectConverter(*args, **kwargs)[source]

Converts to a Object.

The argument must follow the valid ID or mention formats (e.g. <@80088516616269824>).

New in version 2.0.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by member, role, or channel mention.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.MemberConverter(*args, **kwargs)[source]

Converts to a Member.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name#discrim

  4. Lookup by name

  5. Lookup by nickname

Changed in version 1.5: Raise MemberNotFound instead of generic BadArgument

Changed in version 1.5.1: This converter now lazily fetches members from the gateway and HTTP APIs, optionally caching the result if MemberCacheFlags.joined is enabled.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.UserConverter(*args, **kwargs)[source]

Converts to a User.

All lookups are via the global user cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name#discrim

  4. Lookup by name

Changed in version 1.5: Raise UserNotFound instead of generic BadArgument

Changed in version 1.6: This converter now lazily fetches users from the HTTP APIs if an ID is passed and it’s not available in cache.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.MessageConverter(*args, **kwargs)[source]

Converts to a Message.

New in version 1.1.

The lookup strategy is as follows (in order):

  1. Lookup by “{channel ID}-{message ID}” (retrieved by shift-clicking on “Copy ID”)

  2. Lookup by message ID (the message must be in the context channel)

  3. Lookup by message URL

Changed in version 1.5: Raise ChannelNotFound, MessageNotFound or ChannelNotReadable instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.PartialMessageConverter(*args, **kwargs)[source]

Converts to a PartialMessage.

New in version 1.7.

The creation strategy is as follows (in order):

  1. By “{channel ID}-{message ID}” (retrieved by shift-clicking on “Copy ID”)

  2. By message ID (The message is assumed to be in the context channel.)

  3. By message URL

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.GuildChannelConverter(*args, **kwargs)[source]

Converts to a abc.GuildChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name.

New in version 2.0.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.TextChannelConverter(*args, **kwargs)[source]

Converts to a TextChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

Changed in version 1.5: Raise ChannelNotFound instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.VoiceChannelConverter(*args, **kwargs)[source]

Converts to a VoiceChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

Changed in version 1.5: Raise ChannelNotFound instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.StageChannelConverter(*args, **kwargs)[source]

Converts to a StageChannel.

New in version 1.7.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.CategoryChannelConverter(*args, **kwargs)[source]

Converts to a CategoryChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

Changed in version 1.5: Raise ChannelNotFound instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.ForumChannelConverter(*args, **kwargs)[source]

Converts to a ForumChannel.

New in version 2.5.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.ThreadConverter(*args, **kwargs)[source]

Coverts to a Thread.

All lookups are via the local guild.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name.

New in version 2.0.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.ColourConverter(*args, **kwargs)[source]

Converts to a Colour.

Changed in version 1.5: Add an alias named ColorConverter

The following formats are accepted:

  • 0x<hex>

  • #<hex>

  • 0x#<hex>

  • rgb(<number>, <number>, <number>)

  • Any of the classmethod in Colour

    • The _ in the name can be optionally replaced with spaces.

Like CSS, <number> can be either 0-255 or 0-100% and <hex> can be either a 6 digit hex number or a 3 digit hex shortcut (e.g. #fff).

Changed in version 1.5: Raise BadColourArgument instead of generic BadArgument

Changed in version 1.7: Added support for rgb function and 3-digit hex shortcuts

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.RoleConverter(*args, **kwargs)[source]

Converts to a Role.

All lookups are via the local guild. If in a DM context, the converter raises NoPrivateMessage exception.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

Changed in version 1.5: Raise RoleNotFound instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.GameConverter(*args, **kwargs)[source]

Converts to Game.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.InviteConverter(*args, **kwargs)[source]

Converts to a Invite.

This is done via an HTTP request using Bot.fetch_invite().

Changed in version 1.5: Raise BadInviteArgument instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.GuildConverter(*args, **kwargs)[source]

Converts to a Guild.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by name. (There is no disambiguation for Guilds with multiple matching names).

New in version 1.7.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.EmojiConverter(*args, **kwargs)[source]

Converts to a Emoji.

All lookups are done for the local guild first, if available. If that lookup fails, then it checks the client’s global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by extracting ID from the emoji.

  3. Lookup by name

Changed in version 1.5: Raise EmojiNotFound instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.PartialEmojiConverter(*args, **kwargs)[source]

Converts to a PartialEmoji.

This is done by extracting the animated flag, name and ID from the emoji.

Changed in version 1.5: Raise PartialEmojiConversionFailure instead of generic BadArgument

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.GuildStickerConverter(*args, **kwargs)[source]

Converts to a GuildSticker.

All lookups are done for the local guild first, if available. If that lookup fails, then it checks the client’s global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID

  2. Lookup by name

New in version 2.0.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.PermissionsConverter(*args, **kwargs)[source]

Converts to a Permissions.

Accepts an integer or a string of space-separated permission names (or just a single one) as input.

New in version 2.3.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.GuildScheduledEventConverter(*args, **kwargs)[source]

Converts to a GuildScheduledEvent.

The lookup strategy is as follows (in order):

  1. Lookup by ID (in current guild)

  2. Lookup as event URL

  3. Lookup by name (in current guild; there is no disambiguation for scheduled events with multiple matching names)

New in version 2.5.

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.clean_content(*, fix_channel_mentions=False, use_nicknames=True, escape_markdown=False, remove_markdown=False)[source]

Converts the argument to mention scrubbed version of said content.

This behaves similarly to clean_content.

fix_channel_mentions

Whether to clean channel mentions.

Type:

bool

use_nicknames

Whether to use nicknames when transforming mentions.

Type:

bool

escape_markdown

Whether to also escape special markdown characters.

Type:

bool

remove_markdown

Whether to also remove special markdown characters. This option is not supported with escape_markdown

New in version 1.7.

Type:

bool

await convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class disnake.ext.commands.Greedy[source]

A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.

When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.

For example, in the following code:

@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
    await ctx.send("numbers: {0}, reason: {1}".format(numbers, reason))

An invocation of [p]test 1 2 3 4 5 6 hello would pass numbers with [1, 2, 3, 4, 5, 6] and reason with hello.

For more information, check Special Converters.

await disnake.ext.commands.run_converters(ctx, converter, argument, param)[source]

This function is a coroutine.

Runs converters for a given converter, argument, and parameter.

This function does the same work that the library does under the hood.

New in version 2.0.

Parameters:
  • ctx (Context) – The invocation context to run the converters under.

  • converter (Any) – The converter to run, this corresponds to the annotation in the function.

  • argument (str) – The argument to convert to.

  • param (inspect.Parameter) – The parameter being converted. This is mainly for error reporting.

Raises:

CommandError – The converter failed to convert.

Returns:

The resulting conversion.

Return type:

Any

Flag Converter

class disnake.ext.commands.FlagConverter[source]

A converter that allows for a user-friendly flag syntax.

The flags are defined using PEP 526 type annotations similar to the dataclasses Python module. For more information on how this converter works, check the appropriate documentation.

iter(x)

Returns an iterator of (flag_name, flag_value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

New in version 2.0.

Parameters:
  • case_insensitive (bool) – A class parameter to toggle case insensitivity of the flag parsing. If True then flags are parsed in a case insensitive manner. Defaults to False.

  • prefix (str) – The prefix that all flags must be prefixed with. By default there is no prefix.

  • delimiter (str) – The delimiter that separates a flag’s argument from the flag’s name. By default this is :.

classmethod get_flags()[source]

Dict[str, Flag]: A mapping of flag name to flag object this converter has.

classmethod await convert(ctx, argument)[source]

This function is a coroutine.

The method that actually converters an argument to the flag mapping.

Parameters:
  • cls (Type[FlagConverter]) – The flag converter class.

  • ctx (Context) – The invocation context.

  • argument (str) – The argument to convert from.

Raises:
Returns:

The flag converter instance with all flags parsed.

Return type:

FlagConverter

class disnake.ext.commands.Flag[source]

Represents a flag parameter for FlagConverter.

The flag() function helps create these flag objects, but it is not necessary to do so. These cannot be constructed manually.

name

The name of the flag.

Type:

str

aliases

The aliases of the flag name.

Type:

List[str]

attribute

The attribute in the class that corresponds to this flag.

Type:

str

default

The default value of the flag, if available.

Type:

Any

annotation

The underlying evaluated annotation of the flag.

Type:

Any

max_args

The maximum number of arguments the flag can accept. A negative value indicates an unlimited amount of arguments.

Type:

int

override

Whether multiple given values overrides the previous value.

Type:

bool

property required[source]

Whether the flag is required.

A required flag has no default value.

Type:

bool

disnake.ext.commands.flag(*, name=..., aliases=..., default=..., max_args=..., override=...)[source]

Override default functionality and parameters of the underlying FlagConverter class attributes.

Parameters:
  • name (str) – The flag name. If not given, defaults to the attribute name.

  • aliases (List[str]) – Aliases to the flag name. If not given no aliases are set.

  • default (Any) – The default parameter. This could be either a value or a callable that takes Context as its sole parameter. If not given then it defaults to the default value given to the attribute.

  • max_args (int) – The maximum number of arguments the flag can accept. A negative value indicates an unlimited amount of arguments. The default value depends on the annotation given.

  • override (bool) – Whether multiple given values overrides the previous value. The default value depends on the annotation given.

Exceptions

exception disnake.ext.commands.CommandError(message=None, *args)[source]

The base exception type for all command related errors.

This inherits from disnake.DiscordException.

This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from Bot, on_command_error().

exception disnake.ext.commands.ConversionError(converter, original)[source]

Exception raised when a Converter class raises non-CommandError.

This inherits from CommandError.

converter

The converter that failed.

Type:

disnake.ext.commands.Converter

original

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

Type:

Exception

exception disnake.ext.commands.MissingRequiredArgument(param)[source]

Exception raised when parsing a command and a parameter that is required is not encountered.

This inherits from UserInputError

param

The argument that is missing.

Type:

inspect.Parameter

exception disnake.ext.commands.ArgumentParsingError(message=None, *args)[source]

An exception raised when the parser fails to parse a user’s input.

This inherits from UserInputError.

There are child classes that implement more granular parsing errors for i18n purposes.

exception disnake.ext.commands.UnexpectedQuoteError(quote)[source]

An exception raised when the parser encounters a quote mark inside a non-quoted string.

This inherits from ArgumentParsingError.

quote

The quote mark that was found inside the non-quoted string.

Type:

str

exception disnake.ext.commands.InvalidEndOfQuotedStringError(char)[source]

An exception raised when a space is expected after the closing quote in a string but a different character is found.

This inherits from ArgumentParsingError.

char

The character found instead of the expected string.

Type:

str

exception disnake.ext.commands.ExpectedClosingQuoteError(close_quote)[source]

An exception raised when a quote character is expected but not found.

This inherits from ArgumentParsingError.

close_quote

The quote character expected.

Type:

str

exception disnake.ext.commands.BadArgument(message=None, *args)[source]

Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command.

This inherits from UserInputError

exception disnake.ext.commands.BadUnionArgument(param, converters, errors)[source]

Exception raised when a typing.Union converter fails for all its associated types.

This inherits from UserInputError

param

The parameter that failed being converted.

Type:

inspect.Parameter

converters

A tuple of converters attempted in conversion, in order of failure.

Type:

Tuple[Type, ...]

errors

A list of errors that were caught from failing the conversion.

Type:

List[CommandError]

exception disnake.ext.commands.BadLiteralArgument(param, literals, errors)[source]

Exception raised when a typing.Literal converter fails for all its associated values.

This inherits from UserInputError

New in version 2.0.

param

The parameter that failed being converted.

Type:

inspect.Parameter

literals

A tuple of values compared against in conversion, in order of failure.

Type:

Tuple[Any, ...]

errors

A list of errors that were caught from failing the conversion.

Type:

List[CommandError]

exception disnake.ext.commands.PrivateMessageOnly(message=None)[source]

Exception raised when an operation does not work outside of private message contexts.

This inherits from CheckFailure

exception disnake.ext.commands.NoPrivateMessage(message=None)[source]

Exception raised when an operation does not work in private message contexts.

This inherits from CheckFailure

exception disnake.ext.commands.CheckFailure(message=None, *args)[source]

Exception raised when the predicates in Command.checks have failed.

This inherits from CommandError

exception disnake.ext.commands.CheckAnyFailure(checks, errors)[source]

Exception raised when all predicates in check_any() fail.

This inherits from CheckFailure.

New in version 1.3.

errors

A list of errors that were caught during execution.

Type:

List[CheckFailure]

checks

A list of check predicates that failed.

Type:

List[Callable[[Context], bool]]

exception disnake.ext.commands.CommandNotFound(message=None, *args)[source]

Exception raised when a command is attempted to be invoked but no command under that name is found.

This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.

This inherits from CommandError.

exception disnake.ext.commands.DisabledCommand(message=None, *args)[source]

Exception raised when the command being invoked is disabled.

This inherits from CommandError

exception disnake.ext.commands.CommandInvokeError(e)[source]

Exception raised when the command being invoked raised an exception.

This inherits from CommandError

original

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

Type:

Exception

exception disnake.ext.commands.TooManyArguments(message=None, *args)[source]

Exception raised when the command was passed too many arguments and its Command.ignore_extra attribute was not set to True.

This inherits from UserInputError

exception disnake.ext.commands.UserInputError(message=None, *args)[source]

The base exception type for errors that involve errors regarding user input.

This inherits from CommandError.

exception disnake.ext.commands.CommandOnCooldown(cooldown, retry_after, type)[source]

Exception raised when the command being invoked is on cooldown.

This inherits from CommandError

cooldown

A class with attributes rate and per similar to the cooldown() decorator.

Type:

Cooldown

type

The type associated with the cooldown.

Type:

BucketType

retry_after

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

Type:

float

exception disnake.ext.commands.MaxConcurrencyReached(number, per)[source]

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

This inherits from CommandError.

number

The maximum number of concurrent invokers allowed.

Type:

int

per

The bucket type passed to the max_concurrency() decorator.

Type:

BucketType

exception disnake.ext.commands.NotOwner(message=None, *args)[source]

Exception raised when the message author is not the owner of the bot.

This inherits from CheckFailure

exception disnake.ext.commands.ObjectNotFound(argument)[source]

Exception raised when the argument provided did not match the format of an ID or a mention.

This inherits from BadArgument

New in version 2.0.

argument

The argument supplied by the caller that was not matched

Type:

str

exception disnake.ext.commands.MessageNotFound(argument)[source]

Exception raised when the message provided was not found in the channel.

This inherits from BadArgument

New in version 1.5.

argument

The message supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.MemberNotFound(argument)[source]

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

This inherits from BadArgument

New in version 1.5.

argument

The member supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.GuildNotFound(argument)[source]

Exception raised when the guild provided was not found in the bot’s cache.

This inherits from BadArgument

New in version 1.7.

argument

The guild supplied by the called that was not found

Type:

str

exception disnake.ext.commands.UserNotFound(argument)[source]

Exception raised when the user provided was not found in the bot’s cache.

This inherits from BadArgument

New in version 1.5.

argument

The user supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.ChannelNotFound(argument)[source]

Exception raised when the bot can not find the channel.

This inherits from BadArgument

New in version 1.5.

argument

The channel supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.ChannelNotReadable(argument)[source]

Exception raised when the bot does not have permission to read messages in the channel.

This inherits from BadArgument

New in version 1.5.

argument

The channel supplied by the caller that was not readable

Type:

Union[abc.GuildChannel, Thread]

exception disnake.ext.commands.ThreadNotFound(argument)[source]

Exception raised when the bot can not find the thread.

This inherits from BadArgument

New in version 2.0.

argument

The thread supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.BadColourArgument(argument)[source]

Exception raised when the colour is not valid.

This inherits from BadArgument

New in version 1.5.

argument

The colour supplied by the caller that was not valid

Type:

str

exception disnake.ext.commands.RoleNotFound(argument)[source]

Exception raised when the bot can not find the role.

This inherits from BadArgument

New in version 1.5.

argument

The role supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.BadInviteArgument(argument)[source]

Exception raised when the invite is invalid or expired.

This inherits from BadArgument

New in version 1.5.

exception disnake.ext.commands.EmojiNotFound(argument)[source]

Exception raised when the bot can not find the emoji.

This inherits from BadArgument

New in version 1.5.

argument

The emoji supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.PartialEmojiConversionFailure(argument)[source]

Exception raised when the emoji provided does not match the correct format.

This inherits from BadArgument

New in version 1.5.

argument

The emoji supplied by the caller that did not match the regex

Type:

str

exception disnake.ext.commands.GuildStickerNotFound(argument)[source]

Exception raised when the bot can not find the sticker.

This inherits from BadArgument

New in version 2.0.

argument

The sticker supplied by the caller that was not found

Type:

str

exception disnake.ext.commands.GuildScheduledEventNotFound(argument)[source]

Exception raised when the bot cannot find the scheduled event.

This inherits from BadArgument

New in version 2.5.

argument

The scheduled event ID/URL/name supplied by the caller that was not found.

Type:

str

exception disnake.ext.commands.BadBoolArgument(argument)[source]

Exception raised when a boolean argument was not convertable.

This inherits from BadArgument

New in version 1.5.

argument

The boolean argument supplied by the caller that is not in the predefined list

Type:

str

exception disnake.ext.commands.LargeIntConversionFailure(argument)[source]

Exception raised when a large integer argument was not able to be converted.

This inherits from BadArgument

New in version 2.5.

argument

The argument that could not be converted to an integer.

Type:

str

exception disnake.ext.commands.MissingPermissions(missing_permissions, *args)[source]

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

This inherits from CheckFailure

missing_permissions

The required permissions that are missing.

Type:

List[str]

exception disnake.ext.commands.BotMissingPermissions(missing_permissions, *args)[source]

Exception raised when the bot’s member lacks permissions to run a command.

This inherits from CheckFailure

missing_permissions

The required permissions that are missing.

Type:

List[str]

exception disnake.ext.commands.MissingRole(missing_role)[source]

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

This inherits from CheckFailure

New in version 1.1.

missing_role

The required role that is missing. This is the parameter passed to has_role().

Type:

Union[str, int]

exception disnake.ext.commands.BotMissingRole(missing_role)[source]

Exception raised when the bot’s member lacks a role to run a command.

This inherits from CheckFailure

New in version 1.1.

missing_role

The required role that is missing. This is the parameter passed to has_role().

Type:

Union[str, int]

exception disnake.ext.commands.MissingAnyRole(missing_roles)[source]

Exception raised when the command invoker lacks any of the roles specified to run a command.

This inherits from CheckFailure

New in version 1.1.

missing_roles

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

Type:

List[Union[str, int]]

exception disnake.ext.commands.BotMissingAnyRole(missing_roles)[source]

Exception raised when the bot’s member lacks any of the roles specified to run a command.

This inherits from CheckFailure

New in version 1.1.

missing_roles

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

Type:

List[Union[str, int]]

exception disnake.ext.commands.NSFWChannelRequired(channel)[source]

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

This inherits from CheckFailure.

New in version 1.1.

Parameters:

channel (Union[abc.GuildChannel, Thread]) – The channel that does not have NSFW enabled.

exception disnake.ext.commands.FlagError(message=None, *args)[source]

The base exception type for all flag parsing related errors.

This inherits from BadArgument.

New in version 2.0.

exception disnake.ext.commands.BadFlagArgument(flag)[source]

An exception raised when a flag failed to convert a value.

This inherits from FlagError

New in version 2.0.

flag

The flag that failed to convert.

Type:

Flag

exception disnake.ext.commands.MissingFlagArgument(flag)[source]

An exception raised when a flag did not get a value.

This inherits from FlagError

New in version 2.0.

flag

The flag that did not get a value.

Type:

Flag

exception disnake.ext.commands.TooManyFlags(flag, values)[source]

An exception raised when a flag has received too many values.

This inherits from FlagError.

New in version 2.0.

flag

The flag that received too many values.

Type:

Flag

values

The values that were passed.

Type:

List[str]

exception disnake.ext.commands.MissingRequiredFlag(flag)[source]

An exception raised when a required flag was not given.

This inherits from FlagError

New in version 2.0.

flag

The required flag that was not found.

Type:

Flag

exception disnake.ext.commands.ExtensionError(message=None, *args, name)[source]

Base exception for extension related errors.

This inherits from DiscordException.

name

The extension that had an error.

Type:

str

exception disnake.ext.commands.ExtensionAlreadyLoaded(name)[source]

An exception raised when an extension has already been loaded.

This inherits from ExtensionError

exception disnake.ext.commands.ExtensionNotLoaded(name)[source]

An exception raised when an extension was not loaded.

This inherits from ExtensionError

exception disnake.ext.commands.NoEntryPointError(name)[source]

An exception raised when an extension does not have a setup entry point function.

This inherits from ExtensionError

exception disnake.ext.commands.ExtensionFailed(name, original)[source]

An exception raised when an extension failed to load during execution of the module or setup entry point.

This inherits from ExtensionError

name

The extension that had the error.

Type:

str

original

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

Type:

Exception

exception disnake.ext.commands.ExtensionNotFound(name)[source]

An exception raised when an extension is not found.

This inherits from ExtensionError

Changed in version 1.3: Made the original attribute always None.

name

The extension that had the error.

Type:

str

exception disnake.ext.commands.CommandRegistrationError(name, *, alias_conflict=False)[source]

An exception raised when the command can’t be added because the name is already taken by a different command.

This inherits from disnake.ClientException

New in version 1.4.

name

The command name that had the error.

Type:

str

alias_conflict

Whether the name that conflicts is an alias of the command we try to add.

Type:

bool

Exception Hierarchy

Warnings

class disnake.ext.commands.MessageContentPrefixWarning[source]

Warning for invalid prefixes without message content.

Warning Hierarchy