API Reference

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

Bots

Bot

Methods
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)

Represents a Discord bot.

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

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

async with x

Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.

command_prefix

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

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

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

Note

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

case_insensitive

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

Type

bool

description

The content prefixed into the default help message.

Type

str

help_command

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

Type

Optional[HelpCommand]

owner_id

The user ID that owns the bot. If this is not set and is then queried via is_owner() then it will error.

Type

Optional[int]

owner_ids

The user IDs that owns the bot. This is similar to owner_id. If this is not set and and is then queried via is_owner() then it will error. For performance reasons it is recommended to use a set for the collection. You cannot set both owner_id and owner_ids.

New in version 1.3.

Type

Optional[Collection[int]]

strip_after_prefix

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

New in version 1.7.

Type

bool

@after_invoke

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

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

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

Note

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

Changed in version 2.0: coro parameter is now positional-only.

Parameters

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

Raises

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke

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

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

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

Note

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

Changed in version 2.0: coro parameter is now positional-only.

Parameters

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

Raises

TypeError – The coroutine passed is not actually a coroutine.

@check

A decorator that adds a global check to the bot.

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

Note

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

Similar to a command check(), this takes a single parameter of 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

Changed in version 2.0: func parameter is now positional-only.

@check_once

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

Unlike regular global checks, this one is called only once 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

Changed in version 2.0: func parameter is now positional-only.

@command(*args, **kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list 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]

@event

A decorator that registers an event to listen to.

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

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

Example

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

Changed in version 2.0: coro parameter is now positional-only.

Raises

TypeError – The coroutine passed is not actually a coroutine.

@group(*args, **kwargs)

A shortcut decorator that invokes group() and adds it to the internal command list 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)

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

Would print one and two in an unspecified order.

Raises

TypeError – The function being listened to is not a coroutine.

await accept_invite(url, /)

This function is a coroutine.

Uses an invite. Either joins a guild, joins a group DM, or adds a friend.

New in version 2.0.

Parameters

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

Raises

HTTPException – Using the invite failed.

Returns

The accepted invite.

Return type

Invite

property activities

Returns the activities the client is currently doing.

New in version 2.0.

Note

Due to a Discord API limitation, this may be None if the user is listening to a song on Spotify with a title longer than 128 characters. See GH-1738 for more information.

Type

Tuple[Union[BaseActivity, Spotify]]

property activity

Returns the primary activity the client is currently doing. Could be None if no activity is being done.

New in version 2.0.

Note

Due to a Discord API limitation, this may be None if the user is listening to a song on Spotify with a title longer than 128 characters. See GH-1738 for more information.

Note

The client may have multiple activities, these can be accessed under activities.

Type

Optional[Union[BaseActivity, Spotify]]

await activity_statistics()

This function is a coroutine.

Retrieves the available activity usage statistics for your owned applications.

New in version 2.0.

Raises

HTTPException – Retrieving the statistics failed.

Returns

The activity statistics.

Return type

List[ApplicationActivityStatistics]

add_check(func, /, *, call_once=False)

Adds a global check to the bot.

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

Changed in version 2.0: func parameter is now positional-only.

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

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

await add_cog(cog, /, *, override=False)

This function is a coroutine.

Adds a “cog” to the bot.

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

Note

Exceptions raised inside a Cog’s cog_load() method will be propagated to the caller.

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

Changed in version 2.0: cog parameter is now positional-only.

Changed in version 2.0: This method is now a coroutine.

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

  • override (bool) –

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

    New in version 2.0.

Raises
add_command(command, /)

Adds a Command into the internal list of commands.

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

Changed in version 1.4: Raise CommandRegistrationError instead of generic ClientException

Changed in version 2.0: command parameter is now positional-only.

Parameters

command (Command) – The command to add.

Raises
add_listener(func, /, name=...)

The non decorator alternative to listen().

Changed in version 2.0: func parameter is now positional-only.

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

  • name (str) – The name of the event to listen for. Defaults to func.__name__.

Example

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

bot.add_listener(on_ready)
bot.add_listener(my_message, 'on_message')
property allowed_mentions

The allowed mention configuration.

New in version 1.4.

Type

Optional[AllowedMentions]

await applications(*, with_team_applications=True)

This function is a coroutine.

Retrieves all applications owned by you.

New in version 2.0.

Parameters

with_team_applications (bool) – Whether to include applications owned by teams you’re a part of.

Raises

HTTPException – Retrieving the applications failed.

Returns

The applications you own.

Return type

List[Application]

await authorizations()

This function is a coroutine.

Retrieves the OAuth2 applications authorized on your account.

New in version 2.1.

Raises

HTTPException – Retrieving the authorized applications failed.

Returns

The OAuth2 applications authorized on your account.

Return type

List[OAuth2Token]

await authorize_connection(type, two_way_link_type=None, two_way_user_code=None, continuation=False)

This function is a coroutine.

Retrieves a URL to authorize a connection with a third-party service.

New in version 2.0.

Parameters
  • type (ConnectionType) – The type of connection to authorize.

  • two_way_link_type (Optional[ClientType]) – The type of two-way link to use, if any.

  • two_way_user_code (Optional[str]) – The device code to use for two-way linking, if any.

  • continuation (bool) – Whether this is a continuation of a previous authorization.

Raises

HTTPException – Authorizing the connection failed.

Returns

The URL to redirect the user to.

Return type

str

await before_identify_hook(*, initial=False)

This function is a coroutine.

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

The default implementation does nothing.

New in version 1.4.

Parameters

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

property blocked

Returns all the users that the connected client has blocked.

New in version 2.0.

Type

List[Relationship]

property cached_messages

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

New in version 1.1.

Type

Sequence[Message]

await change_presence(*, activity=..., activities=..., status=..., afk=..., idle_since=..., edit_settings=True)

This function is a coroutine.

Changes the client’s presence.

Changed in version 2.1: The default value for parameters is now the current value. None is no longer a valid value for most; you must explicitly set it to the default value if you want to reset it.

Changed in version 2.0: Edits are no longer in place. Added option to update settings.

Changed in version 2.0: This function will now raise TypeError instead of InvalidArgument.

Example

game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
Parameters
  • activity (Optional[BaseActivity]) – The activity being done. None if no activity is done.

  • activities (List[BaseActivity]) –

    A list of the activities being done. Cannot be sent with activity.

    New in version 2.0.

  • status (Status) – Indicates what status to change to.

  • afk (bool) – Indicates if you are going AFK. This allows the Discord client to know how to handle push notifications better for you in case you are away from your keyboard.

  • idle_since (Optional[datetime.datetime]) – When the client went idle. This indicates that you are truly idle and not just lying.

  • edit_settings (bool) –

    Whether to update user settings with the new status and/or custom activity. This will broadcast the change and cause all connected (official) clients to change presence as well.

    This should be set to False for idle changes.

    Required for setting/editing expires_at for custom activities. It’s not recommended to change this, as setting it to False can cause undefined behavior.

Raises
  • TypeError – The activity parameter is not the proper type. Both activity and activities were passed.

  • ValueError – More than one custom activity was passed.

await change_voice_state(*, channel, self_mute=False, self_deaf=False, self_video=False, preferred_region=...)

This function is a coroutine.

Changes client’s private channel voice state.

New in version 2.0.

Parameters
  • channel (Optional[Snowflake]) – Channel the client wants to join (must be a private channel). Use None to disconnect.

  • self_mute (bool) – Indicates if the client should be self-muted.

  • self_deaf (bool) – Indicates if the client should be self-deafened.

  • self_video (bool) – Indicates if the client is using video. Untested & unconfirmed (do not use).

  • preferred_region (Optional[str]) – The preferred region to connect to.

await check_pomelo_username(username)

This function is a coroutine.

Checks if a pomelo username is taken.

Note

This method requires you to be in the pomelo rollout.

New in version 2.1.

Parameters

username (str) – The username to check.

Raises

HTTPException – You are not in the pomelo rollout.

Returns

Whether the username is taken.

Return type

bool

clear()

Clears the internal state of the bot.

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

property client_activities

Returns the activities the client is currently doing through this library, if applicable.

New in version 2.0.

Type

Tuple[Union[BaseActivity, Spotify]]

property client_status

The library’s status.

New in version 2.0.

Type

Status

await close()

This function is a coroutine.

Closes the connection to Discord.

property cogs

A read-only mapping of cog name to cog.

Type

Mapping[str, Cog]

property commands

A unique set of commands without aliases that are registered.

Type

Set[Command]

await connect(*, reconnect=True)

This function is a coroutine.

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

Parameters

reconnect (bool) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as bad tokens).

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

  • ConnectionClosed – The websocket connection has been terminated.

property connections

The connections that the connected client has.

These connections don’t have the Connection.metadata attribute populated.

New in version 2.0.

Note

Due to a Discord limitation, removed connections may not be removed from this cache.

Type

Sequence[Connection]

property country_code

The country code of the client. None if not connected.

New in version 2.0.

Type

Optional[str]

await create_application(name, /, *, team=None)

This function is a coroutine.

Creates an application.

New in version 2.0.

Parameters
  • name (str) – The name of the application.

  • team (Snowflake) – The team to create the application under.

Raises

HTTPException – Failed to create the application.

Returns

The newly-created application.

Return type

Application

await create_authorization(application_id, /, *, scopes, response_type=None, redirect_uri=None, code_challenge_method=None, code_challenge=None, state=None, guild=..., channel=..., permissions=...)

This function is a coroutine.

Creates an OAuth2 authorization for the given application. It is recommended to instead first fetch the authorization information using fetch_authorization() and then call OAuth2Authorization.authorize().

New in version 2.1.

Parameters
  • application_id (int) – The ID of the application to create the authorization for.

  • scopes (List[str]) – The scopes to request for the authorization.

  • response_type (Optional[str]) – The response type to use for the authorization, if using the full OAuth2 flow.

  • redirect_uri (Optional[str]) – The redirect URI to use for the authorization, if using the full OAuth2 flow. If this isn’t provided and response_type is provided, then the default redirect URI for the application will be used.

  • code_challenge_method (Optional[str]) – The code challenge method to use for the PKCE authorization, if using the full OAuth2 flow.

  • code_challenge (Optional[str]) – The code challenge to use for the PKCE authorization, if using the full OAuth2 flow.

  • state (Optional[str]) – The state to use for authorization security.

  • guild (Guild) – The guild to authorize for, if authorizing with the applications.commands or bot scopes.

  • channel (Union[TextChannel, VoiceChannel, StageChannel]) – The channel to authorize for, if authorizing with the webhooks.incoming scope. See Guild.webhook_channels().

  • permissions (Permissions) – The permissions to grant, if authorizing with the bot scope.

Raises

HTTPException – Creating the authorization failed.

Returns

The URL to redirect the user to for authorization.

Return type

str

await create_connection(type, code, state, *, two_way_link_code=None, insecure=True, friend_sync=...)

This function is a coroutine.

Creates a new connection.

This is a low-level method that requires data obtained from other APIs.

New in version 2.0.

Parameters
  • type (ConnectionType) – The type of connection to add.

  • code (str) – The authorization code for the connection.

  • state (str) – The state used to authorize the connection.

  • two_way_link_code (Optional[str]) – The code to use for two-way linking, if any.

  • insecure (bool) – Whether the authorization is insecure.

  • friend_sync (bool) –

    Whether friends are synced over the connection.

    Defaults to True for ConnectionType.facebook and ConnectionType.contacts, else False.

Raises

HTTPException – Creating the connection failed.

await create_dm(user, /)

This function is a coroutine.

Creates a DMChannel with this user.

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

New in version 2.0.

Parameters

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

Returns

The channel that was created.

Return type

DMChannel

await create_group(*recipients)

This function is a coroutine.

Creates a group direct message with the recipients provided. These recipients must be have a relationship of type RelationshipType.friend.

New in version 2.0.

Parameters

*recipients (Snowflake) – An argument list of discord.User to have in your group.

Raises

HTTPException – Failed to create the group direct message.

Returns

The new group channel.

Return type

GroupChannel

await create_guild(name, icon=..., code=...)

This function is a coroutine.

Creates a Guild.

Changed in version 2.0: name and icon parameters are now keyword-only. The region parameter has been removed.

Changed in version 2.0: This function will now raise ValueError instead of InvalidArgument.

Parameters
  • name (str) – The name of the guild.

  • icon (Optional[bytes]) – The bytes-like object representing the icon. See ClientUser.edit() for more details on what is expected.

  • code (str) –

    The code for a template to create the guild with.

    New in version 1.4.

Raises
Returns

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

Return type

Guild

await create_invite()

This function is a coroutine.

Creates a new friend Invite.

New in version 2.0.

Raises

HTTPException – Creating the invite failed.

Returns

The created friend invite.

Return type

Invite

await create_payment_source(*, token, payment_gateway, billing_address, billing_address_token=..., return_url=None, bank=None)

This function is a coroutine.

Creates a payment source.

This is a low-level method that requires data obtained from other APIs.

New in version 2.0.

Parameters
  • token (str) – The payment source token.

  • payment_gateway (PaymentGateway) – The payment gateway to use.

  • billing_address (BillingAddress) – The billing address to use.

  • billing_address_token (Optional[str]) – The billing address token. If not provided, the library will fetch it for you. Not required for all payment gateways.

  • return_url (Optional[str]) – The URL to return to after the payment source is created.

  • bank (Optional[str]) – The bank information for the payment source. Not required for most payment gateways.

Raises

HTTPException – Creating the payment source failed.

Returns

The newly-created payment source.

Return type

PaymentSource

await create_subscription(items, payment_source, currency='usd', *, trial=None, payment_source_token=None, purchase_token=None, return_url=None, gateway_checkout_context=None, code=None, metadata=None, guild=None)

This function is a coroutine.

Creates a new subscription.

New in version 2.0.

Parameters
  • items (List[SubscriptionItem]) – The items in the subscription.

  • payment_source (PaymentSource) – The payment source to pay with.

  • currency (str) – The currency to pay with.

  • trial (Optional[SubscriptionTrial]) – The trial to apply to the subscription.

  • payment_source_token (Optional[str]) – The token used to authorize with the payment source.

  • purchase_token (Optional[str]) – The purchase token to use.

  • return_url (Optional[str]) – The URL to return to after the payment is complete.

  • gateway_checkout_context (Optional[str]) – The current checkout context.

  • code (Optional[str]) – Unknown.

  • metadata (Optional[Mapping[str, Any]]) – Extra metadata about the subscription.

  • guild (Optional[Guild]) – The guild the subscription’s entitlements should be applied to.

Raises

HTTPException – Creating the subscription failed.

Returns

The newly-created subscription.

Return type

Subscription

await create_team(name, /)

This function is a coroutine.

Creates a team.

New in version 2.0.

Parameters

name (str) – The name of the team.

Raises

HTTPException – Failed to create the team.

Returns

The newly-created team.

Return type

Team

await delete_invite(invite, /)

This function is a coroutine.

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

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

Changed in version 2.0: invite parameter is now positional-only.

Changed in version 2.0: The function now returns the deleted invite.

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.

Returns

The deleted invite.

Return type

Invite

await delete_recent_mention(message)

This function is a coroutine.

Acknowledges a message the current user has been mentioned in.

New in version 2.0.

Parameters

message (abc.Snowflake) – The message to delete.

Raises

HTTPException – Deleting the recent mention failed.

await detectable_applications()

This function is a coroutine.

Retrieves the list of applications detectable by the Discord client.

New in version 2.0.

Raises

HTTPException – Retrieving the applications failed.

Returns

The applications detectable by the Discord client.

Return type

List[PartialApplication]

property disclose

Upcoming changes to the user’s account.

New in version 2.1.

Type

Sequence[str]

await edit_legacy_settings(**kwargs)

This function is a coroutine.

Edits the client user’s settings.

Changed in version 2.0: The edit is no longer in-place, instead the newly edited settings are returned.

Deprecated since version 2.0.

Parameters
  • activity_restricted_guilds (List[Snowflake]) –

    A list of guilds that your current activity will not be shown in.

    New in version 2.0.

  • activity_joining_restricted_guilds (List[Snowflake]) –

    A list of guilds that will not be able to join your current activity.

    New in version 2.0.

  • afk_timeout (int) – How long (in seconds) the user needs to be AFK until Discord sends push notifications to mobile device (30-600).

  • allow_accessibility_detection (bool) – Whether to allow Discord to track screen reader usage.

  • animate_emojis (bool) – Whether to animate emojis in the chat.

  • animate_stickers (StickerAnimationOptions) – Whether to animate stickers in the chat.

  • contact_sync_enabled (bool) – Whether to enable the contact sync on Discord mobile.

  • convert_emoticons (bool) – Whether to automatically convert emoticons into emojis (e.g. :) -> 😃).

  • default_guilds_restricted (bool) – Whether to automatically disable DMs between you and members of new guilds you join.

  • detect_platform_accounts (bool) – Whether to automatically detect accounts from services like Steam and Blizzard when you open the Discord client.

  • developer_mode (bool) – Whether to enable developer mode.

  • disable_games_tab (bool) – Whether to disable the showing of the Games tab.

  • enable_tts_command (bool) – Whether to allow TTS messages to be played/sent.

  • explicit_content_filter (UserContentFilter) – The filter for explicit content in all messages.

  • friend_source_flags (FriendSourceFlags) – Who can add you as a friend.

  • friend_discovery_flags (FriendDiscoveryFlags) – How you get recommended friends.

  • gif_auto_play (bool) – Whether to automatically play GIFs that are in the chat.

  • guild_positions (List[Snowflake]) – A list of guilds in order of the guild/guild icons that are on the left hand side of the UI.

  • inline_attachment_media (bool) – Whether to display attachments when they are uploaded in chat.

  • inline_embed_media (bool) – Whether to display videos and images from links posted in chat.

  • locale (Locale) – The RFC 3066 language identifier of the locale to use for the language of the Discord client.

  • message_display_compact (bool) – Whether to use the compact Discord display mode.

  • native_phone_integration_enabled (bool) – Whether to enable the new Discord mobile phone number friend requesting features.

  • passwordless (bool) – Whether to enable passwordless login.

  • render_embeds (bool) – Whether to render embeds that are sent in the chat.

  • render_reactions (bool) – Whether to render reactions that are added to messages.

  • restricted_guilds (List[Snowflake]) – A list of guilds that you will not receive DMs from.

  • show_current_game (bool) – Whether to display the game that you are currently playing.

  • stream_notifications_enabled (bool) – Whether stream notifications for friends will be received.

  • theme (Theme) – The overall theme of the Discord UI.

  • timezone_offset (int) – The timezone offset to use.

  • view_nsfw_commands (bool) –

    Whether to show NSFW application commands in DMs.

    New in version 2.0.

  • view_nsfw_guilds (bool) –

    Whether to show NSFW guilds on iOS.

    New in version 2.0.

Raises

HTTPException – Editing the settings failed.

Returns

The client user’s updated settings.

Return type

UserSettings

await email_settings()

This function is a coroutine.

Retrieves your email settings.

New in version 2.0.

Raises

HTTPException – Getting the email settings failed.

Returns

The email settings.

Return type

EmailSettings

property emojis

The emojis that the connected client has.

Type

Sequence[Emoji]

await entitlements(*, with_sku=True, with_application=True, entitlement_type=None)

This function is a coroutine.

Retrieves all the entitlements for your account.

New in version 2.0.

Parameters
  • with_sku (bool) – Whether to include the SKU information in the returned entitlements.

  • with_application (bool) – Whether to include the application in the returned entitlements’ SKUs. The premium subscription application is always returned.

  • entitlement_type (Optional[EntitlementType]) – The type of entitlement to retrieve. If None then all entitlements are returned.

Raises

HTTPException – Retrieving the entitlements failed.

Returns

The entitlements for your account.

Return type

List[Entitlement]

property experiments

The experiments assignments for the connected client.

New in version 2.1.

Type

Sequence[UserExperiment]

property extensions

A read-only mapping of extension name to extension.

Type

Mapping[str, types.ModuleType]

await fetch_application(application_id, /)

This function is a coroutine.

Retrieves the application with the given ID.

The application must be owned by you or a team you are a part of.

New in version 2.0.

Parameters

application_id (int) – The ID of the application to fetch.

Raises
Returns

The retrieved application.

Return type

Application

await fetch_authorization(application_id, /, *, scopes, response_type=None, redirect_uri=None, code_challenge_method=None, code_challenge=None, state=None)

This function is a coroutine.

Retrieves an OAuth2 authorization for the given application. This provides information about the application before you authorize it.

New in version 2.1.

Parameters
  • application_id (int) – The ID of the application to fetch the authorization for.

  • scopes (List[str]) – The scopes to request for the authorization.

  • response_type (Optional[str]) – The response type that will be used for the authorization, if using the full OAuth2 flow.

  • redirect_uri (Optional[str]) – The redirect URI that will be used for the authorization, if using the full OAuth2 flow. If this isn’t provided and response_type is provided, then the default redirect URI for the application will be provided in the returned authorization.

  • code_challenge_method (Optional[str]) – The code challenge method that will be used for the PKCE authorization, if using the full OAuth2 flow.

  • code_challenge (Optional[str]) – The code challenge that will be used for the PKCE authorization, if using the full OAuth2 flow.

  • state (Optional[str]) – The state that will be used for authorization security.

Raises

HTTPException – Fetching the authorization failed.

Returns

The authorization for the application.

Return type

OAuth2Authorization

await fetch_channel(channel_id, /)

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.

Changed in version 2.0: channel_id parameter is now positional-only.

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

  • HTTPException – Retrieving the channel failed.

  • NotFound – Invalid Channel ID.

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

Returns

The channel from the ID.

Return type

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

await fetch_connections()

This function is a coroutine.

Retrieves all of your connections.

New in version 2.0.

Raises

HTTPException – Retrieving your connections failed.

Returns

All your connections.

Return type

List[Connection]

await fetch_country_code()

This function is a coroutine.

Retrieves the country code of the client.

New in version 2.0.

Raises

HTTPException – Retrieving the country code failed.

Returns

The country code of the client.

Return type

str

await fetch_entitlements(application_id, /, *, exclude_consumed=True)

This function is a coroutine.

Retrieves the entitlements this account has granted for the given application.

Parameters
  • application_id (int) – The ID of the application to fetch the entitlements for.

  • exclude_consumed (bool) – Whether to exclude consumed entitlements.

Raises

HTTPException – Fetching the entitlements failed.

Returns

The entitlements retrieved.

Return type

List[Entitlement]

await fetch_eula(eula_id, /)

This function is a coroutine.

Retrieves a EULA with the given ID.

New in version 2.0.

Parameters

eula_id (int) – The ID of the EULA to retrieve.

Raises
Returns

The retrieved EULA.

Return type

EULA

await fetch_experiments(with_guild_experiments=True)

This function is a coroutine.

Retrieves the experiment rollouts available in relation to the user.

New in version 2.1.

Note

Certain guild experiments are only available via the gateway. See guild_experiments for these.

Parameters

with_guild_experiments (bool) – Whether to include guild experiment rollouts in the response.

Raises

HTTPException – Retrieving the experiment assignments failed.

Returns

The experiment rollouts.

Return type

List[Union[UserExperiment, GuildExperiment]]

await fetch_gift(code, *, with_application=False, with_subscription_plan=True)

This function is a coroutine.

Retrieves a gift with the given code.

New in version 2.0.

Parameters
  • code (Union[Gift, str]) – The code of the gift to retrieve.

  • with_application (bool) – Whether to include the application in the response’s store listing. The premium subscription application is always returned.

  • with_subscription_plan (bool) – Whether to include the subscription plan in the response.

Raises
Returns

The retrieved gift.

Return type

Gift

await fetch_guild(guild_id, /, *, with_counts=True)

This function is a coroutine.

Retrieves a Guild from an ID.

Note

Using this, you will not receive Guild.channels and Guild.members.

Note

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

Changed in version 2.0: guild_id parameter is now positional-only.

Parameters
Raises
Returns

The guild from the ID.

Return type

Guild

await fetch_guild_preview(guild_id, /)

This function is a coroutine.

Retrieves a public Guild preview from an ID.

New in version 2.0.

Raises
  • NotFound – Guild with given ID does not exist/is not public.

  • HTTPException – Retrieving the guild failed.

Returns

The guild from the ID.

Return type

Guild

await fetch_guilds(*, with_counts=True)

This function is a coroutine.

Retrieves all your guilds.

Note

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

Changed in version 2.0: This method now returns a list of UserGuild instead of Guild.

Parameters

with_counts (bool) – Whether to fill Guild.approximate_member_count and Guild.approximate_presence_count.

Raises

HTTPException – Getting the guilds failed.

Returns

A list of all your guilds.

Return type

List[UserGuild]

await fetch_invite(url, /, *, with_counts=True, scheduled_event_id=None)

This function is a coroutine.

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

Note

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

Changed in version 2.0: url parameter is now positional-only.

Changed in version 2.1: The with_expiration parameter has been removed.

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.

  • scheduled_event_id (Optional[int]) –

    The ID of the scheduled event this invite is for.

    Note

    It is not possible to provide a url that contains an event_id parameter when using this parameter.

    New in version 2.0.

Raises
  • ValueError – The url contains an event_id, but scheduled_event_id has also been provided.

  • NotFound – The invite has expired or is invalid.

  • HTTPException – Getting the invite failed.

Returns

The invite from the URL/ID.

Return type

Invite

await fetch_live_build_ids(*branch_ids)

This function is a coroutine.

Retrieves the live build IDs for the given branch IDs.

New in version 2.0.

Parameters

*branch_ids (int) – A list of branch IDs to retrieve the live build IDs for.

Raises

HTTPException – Retrieving the live build IDs failed.

Returns

A mapping of found branch IDs to their live build ID, if any.

Return type

Dict[int, Optional[int]]

await fetch_note(user_id, /)

This function is a coroutine.

Retrieves a Note for the specified user ID.

New in version 1.9.

Changed in version 2.0: user_id parameter is now positional-only.

Parameters

user_id (int) – The ID of the user to fetch the note for.

Raises

HTTPException – Retrieving the note failed.

Returns

The note you requested.

Return type

Note

await fetch_partial_application(application_id, /)

This function is a coroutine.

Retrieves the partial application with the given ID.

New in version 2.0.

Parameters

application_id (int) – The ID of the partial application to fetch.

Raises
  • NotFound – The partial application was not found.

  • HTTPException – Retrieving the partial application failed.

Returns

The retrieved application.

Return type

PartialApplication

await fetch_payment(payment_id)

This function is a coroutine.

Retrieves the payment with the given ID.

New in version 2.0.

Parameters

payment_id (int) – The ID of the payment to fetch.

Raises

HTTPException – Fetching the payment failed.

Returns

The retrieved payment.

Return type

Payment

await fetch_payment_source(source_id, /)

This function is a coroutine.

Retrieves the payment source with the given ID.

New in version 2.0.

Parameters

source_id (int) – The ID of the payment source to fetch.

Raises
Returns

The retrieved payment source.

Return type

PaymentSource

await fetch_preferred_voice_regions()

This function is a coroutine.

Retrieves the preferred voice regions of the client.

New in version 2.0.

Raises

HTTPException – Retrieving the preferred voice regions failed.

Returns

The preferred voice regions of the client.

Return type

List[str]

await fetch_price_tier(price_tier, /)

This function is a coroutine.

Retrieves a mapping of currency to price for the given price tier.

New in version 2.0.

Parameters

price_tier (int) – The price tier to retrieve.

Raises
Returns

The retrieved price tier mapping.

Return type

Dict[str, int]

await fetch_primary_store_listing(application_id, /, *, localize=True)

This function is a coroutine.

Retrieves the primary store listing for the given application ID.

This is the public store listing of the primary SKU.

New in version 2.0.

Parameters
  • application_id (int) – The ID of the application to retrieve the listing for.

  • localize (bool) – Whether to localize the store listings to the current user’s locale. If False then all localizations are returned.

Raises
  • NotFound – The application does not exist or have a primary SKU.

  • HTTPException – Retrieving the store listing failed.

Returns

The retrieved store listing.

Return type

StoreListing

await fetch_primary_store_listings(*application_ids, localize=True)

This function is a coroutine.

Retrieves the primary store listings for the given application IDs.

This is the public store listing of the primary SKU.

New in version 2.0.

Parameters
  • *application_ids (int) – A list of application IDs to retrieve the listings for.

  • localize (bool) – Whether to localize the store listings to the current user’s locale. If False then all localizations are returned.

Raises

HTTPException – Retrieving the store listings failed.

Returns

The retrieved store listings.

Return type

List[StoreListing]

await fetch_private_channels()

This function is a coroutine.

Retrieves all your private channels.

New in version 2.0.

Note

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

Raises

HTTPException – Retrieving your private channels failed.

Returns

All your private channels.

Return type

List[abc.PrivateChannel]

await fetch_public_application(application_id, /, *, with_guild=False)

This function is a coroutine.

Retrieves the public application with the given ID.

New in version 2.0.

Parameters
  • application_id (int) – The ID of the public application to fetch.

  • with_guild (bool) – Whether to include the public guild of the application.

Raises
  • NotFound – The public application was not found.

  • HTTPException – Retrieving the public application failed.

Returns

The retrieved application.

Return type

PartialApplication

await fetch_public_applications(*application_ids)

This function is a coroutine.

Retrieves a list of public applications. Only found applications are returned.

New in version 2.0.

Parameters

*application_ids (int) – The IDs of the public applications to fetch.

Raises

HTTPException – Retrieving the applications failed.

Returns

The public applications.

Return type

List[PartialApplication]

await fetch_published_store_listing(sku_id, /, *, localize=True)

This function is a coroutine.

Retrieves a published store listing with the given SKU ID.

New in version 2.0.

Parameters
  • sku_id (int) – The ID of the SKU to retrieve the listing for.

  • localize (bool) – Whether to localize the store listings to the current user’s locale. If False then all localizations are returned.

Raises
  • NotFound – The listing does not exist or is not public.

  • HTTPException – Retrieving the listing failed.

Returns

The store listing.

Return type

StoreListing

await fetch_published_store_listings(application_id, /, localize=True)

This function is a coroutine.

Retrieves all published store listings for the given application ID.

New in version 2.0.

Parameters
  • application_id (int) – The ID of the application to retrieve the listings for.

  • localize (bool) – Whether to localize the store listings to the current user’s locale. If False then all localizations are returned.

Raises

HTTPException – Retrieving the listings failed.

Returns

The store listings.

Return type

List[StoreListing]

await fetch_relationships()

This function is a coroutine.

Retrieves all your relationships.

New in version 2.0.

Note

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

Raises

HTTPException – Retrieving your relationships failed.

Returns

All your relationships.

Return type

List[Relationship]

await fetch_settings()

This function is a coroutine.

Retrieves your user settings.

New in version 2.0.

Note

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

Raises

HTTPException – Retrieving your settings failed.

Returns

The current settings for your account.

Return type

UserSettings

await fetch_sku(sku_id, /, *, localize=True)

This function is a coroutine.

Retrieves a SKU with the given ID.

New in version 2.0.

Parameters
  • sku_id (int) – The ID of the SKU to retrieve.

  • localize (bool) – Whether to localize the SKU name and description to the current user’s locale. If False then all localizations are returned.

Raises
Returns

The retrieved SKU.

Return type

SKU

await fetch_sku_subscription_plans(sku_id, /, *, country_code=..., payment_source=..., with_unpublished=False)

This function is a coroutine.

Retrieves all subscription plans for the given SKU ID.

New in version 2.0.

Parameters
  • sku_id (int) – The ID of the SKU to retrieve the subscription plans for.

  • country_code (str) – The country code to retrieve the subscription plan prices for. Defaults to the country code of the current user.

  • payment_source (PaymentSource) – The specific payment source to retrieve the subscription plan prices for. Defaults to all payment sources of the current user.

  • with_unpublished (bool) –

    Whether to include unpublished subscription plans.

    If True, then you require access to the application.

Raises

HTTPException – Retrieving the subscription plans failed.

Returns

The subscription plans.

Return type

List[SubscriptionPlan]

await fetch_skus_subscription_plans(*sku_ids, country_code=..., payment_source=..., with_unpublished=False)

This function is a coroutine.

Retrieves all subscription plans for the given SKU IDs.

New in version 2.0.

Parameters
  • *sku_ids (int) – A list of SKU IDs to retrieve the subscription plans for.

  • country_code (str) – The country code to retrieve the subscription plan prices for. Defaults to the country code of the current user.

  • payment_source (PaymentSource) – The specific payment source to retrieve the subscription plan prices for. Defaults to all payment sources of the current user.

  • with_unpublished (bool) –

    Whether to include unpublished subscription plans.

    If True, then you require access to the application(s).

Raises

HTTPException – Retrieving the subscription plans failed.

Returns

The subscription plans.

Return type

List[SubscriptionPlan]

await fetch_stage_instance(channel_id, /)

This function is a coroutine.

Gets a StageInstance for a stage channel ID.

New in version 2.0.

Parameters

channel_id (int) – The stage channel ID.

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

  • HTTPException – Getting the stage instance failed.

Returns

The stage instance from the stage channel ID.

Return type

StageInstance

await fetch_sticker(sticker_id, /)

This function is a coroutine.

Retrieves a Sticker with the specified ID.

New in version 2.0.

Raises
Returns

The sticker you requested.

Return type

Union[StandardSticker, GuildSticker]

await fetch_sticker_pack(pack_id, /)

This function is a coroutine.

Retrieves a sticker pack with the specified ID.

New in version 2.0.

Raises
  • NotFound – A sticker pack with that ID was not found.

  • HTTPException – Retrieving the sticker packs failed.

Returns

The sticker pack you requested.

Return type

StickerPack

await fetch_store_listing(listing_id, /, *, localize=True)

This function is a coroutine.

Retrieves a store listing with the given ID.

New in version 2.0.

Parameters
  • listing_id (int) – The ID of the listing to retrieve.

  • localize (bool) – Whether to localize the store listings to the current user’s locale. If False then all localizations are returned.

Raises
Returns

The store listing.

Return type

StoreListing

await fetch_subscription(subscription_id, /)

This function is a coroutine.

Retrieves the subscription with the given ID.

New in version 2.0.

Parameters

subscription_id (int) – The ID of the subscription to fetch.

Raises
Returns

The retrieved subscription.

Return type

Subscription

await fetch_team(team_id, /)

This function is a coroutine.

Retrieves the team with the given ID.

You must be a part of the team.

New in version 2.0.

Parameters

id (int) – The ID of the team to fetch.

Raises
Returns

The retrieved team.

Return type

Team

await fetch_template(code)

This function is a coroutine.

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

Parameters

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

Raises
Returns

The template from the URL/code.

Return type

Template

await fetch_tracking_settings()

This function is a coroutine.

Retrieves your Discord tracking consents.

New in version 2.0.

Raises

HTTPException – Retrieving the tracking settings failed.

Returns

The tracking settings.

Return type

TrackingSettings

await fetch_user(user_id, /)

This function is a coroutine.

Retrieves a discord.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 member cache enabled, consider get_user() instead.

Changed in version 2.0: user_id parameter is now positional-only.

Parameters

user_id (int) – The user’s ID to fetch from.

Raises
Returns

The user you requested.

Return type

discord.User

await fetch_user_named(*args)

This function is a coroutine.

Retrieves a discord.User based on their name or legacy username. You do not have to share any guilds with the user to get this information, however you must be able to add them as a friend.

This function can be used in multiple ways.

New in version 2.1.

# Passing a username
await client.fetch_user_named('jake')

# Passing a legacy user:
await client.fetch_user_named('Jake#0001')

# Passing a legacy username and discriminator:
await client.fetch_user_named('Jake', '0001')
Parameters
  • user (str) – The user to send the friend request to.

  • username (str) – The username of the user to send the friend request to.

  • discriminator (str) – The discriminator of the user to send the friend request to.

Raises
  • Forbidden – Not allowed to send a friend request to this user.

  • HTTPException – Fetching the user failed.

  • TypeError – More than 2 parameters or less than 1 parameter was passed.

Returns

The user you requested.

Return type

discord.User

await fetch_user_profile(user_id, /, *, with_mutual_guilds=True, with_mutual_friends_count=False, with_mutual_friends=True)

This function is a coroutine.

Retrieves a UserProfile based on their user ID.

You must share a guild, be friends with this user, or have an incoming friend request from them to get this information (unless the user is a bot).

Changed in version 2.0: user_id parameter is now positional-only.

Parameters
Raises
  • NotFound – A user with this ID does not exist.

  • Forbidden – You do not have a mutual with this user, and and the user is not a bot.

  • HTTPException – Fetching the profile failed.

Returns

The profile of the user.

Return type

UserProfile

await fetch_webhook(webhook_id, /)

This function is a coroutine.

Retrieves a Webhook with the specified ID.

Changed in version 2.0: webhook_id parameter is now positional-only.

Raises
Returns

The webhook you requested.

Return type

Webhook

await fetch_widget(guild_id, /)

This function is a coroutine.

Gets a Widget from a guild ID.

Note

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

Changed in version 2.0: guild_id parameter is now positional-only.

Parameters

guild_id (int) – The ID of the guild.

Raises
Returns

The guild’s widget.

Return type

Widget

property friend_suggestion_count

The number of friend suggestions that the connected client has.

New in version 2.1.

Type

int

await friend_suggestions()

This function is a coroutine.

Retrieves all your friend suggestions.

New in version 2.1.

Raises

HTTPException – Retrieving your friend suggestions failed.

Returns

All your current friend suggestions.

Return type

List[FriendSuggestion]

property friends

Returns all the users that the connected client is friends with.

New in version 2.0.

Type

List[Relationship]

for ... in get_all_channels()

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

This is equivalent to:

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

Note

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

Yields

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

for ... in get_all_members()

Returns a generator with every Member the client can see.

This is equivalent to:

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

Member – A member the client can see.

get_channel(id, /)

Returns a channel or thread with the given ID.

Changed in version 2.0: id parameter is now positional-only.

Parameters

id (int) – The ID to search for.

Returns

The returned channel or None if not found.

Return type

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

get_cog(name, /)

Gets the cog instance requested.

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

Changed in version 2.0: name parameter is now positional-only.

Parameters

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

Returns

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

Return type

Optional[Cog]

get_command(name, /)

Get a Command from the internal list of commands.

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

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

Changed in version 2.0: name parameter is now positional-only.

Parameters

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

Returns

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

Return type

Optional[Command]

await get_context(message, /, *, cls=...)

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

Changed in version 2.0: message parameter is now positional-only.

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

  • cls – The factory class that will be used to create the context. By default, this 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, /)

Returns an emoji with the given ID.

Changed in version 2.0: id parameter is now positional-only.

Parameters

id (int) – The ID to search for.

Returns

The custom emoji or None if not found.

Return type

Optional[Emoji]

get_experiment(experiment, /)

Returns a user or guild experiment from the given experiment identifier.

New in version 2.1.

Parameters

experiment (Union[str, int]) – The experiment name or hash to search for.

Returns

The experiment, if found.

Return type

Optional[Union[UserExperiment, GuildExperiment]]

get_guild(id, /)

Returns a guild with the given ID.

Changed in version 2.0: id parameter is now positional-only.

Parameters

id (int) – The ID to search for.

Returns

The guild or None if not found.

Return type

Optional[Guild]

get_partial_messageable(id, *, guild_id=None, type=None)

Returns a partial messageable with the given channel ID.

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

New in version 2.0.

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

  • guild_id (Optional[int]) –

    The optional guild ID to create a partial messageable for.

    This is not required to actually send messages, but it does allow the jump_url() and guild properties to function properly.

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

Returns

The partial messageable

Return type

PartialMessageable

await get_prefix(message, /)

This function is a coroutine.

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

Changed in version 2.0: message parameter is now positional-only.

Parameters

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

Returns

A list of prefixes or a single prefix that the bot is listening for.

Return type

Union[List[str], str]

get_relationship(user_id, /)

Retrieves the Relationship, if applicable.

New in version 2.0.

Parameters

user_id (int) – The user ID to check if we have a relationship with them.

Returns

The relationship, if available.

Return type

Optional[Relationship]

get_stage_instance(id, /)

Returns a stage instance with the given stage channel ID.

New in version 2.0.

Parameters

id (int) – The ID to search for.

Returns

The stage instance or None if not found.

Return type

Optional[StageInstance]

get_sticker(id, /)

Returns a guild sticker with the given ID.

New in version 2.0.

Note

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

Returns

The sticker or None if not found.

Return type

Optional[GuildSticker]

get_user(id, /)

Returns a user with the given ID.

Changed in version 2.0: id parameter is now positional-only.

Parameters

id (int) – The ID to search for.

Returns

The user or None if not found.

Return type

Optional[User]

await giftable_entitlements()

This function is a coroutine.

Retrieves the giftable entitlements for your account.

These are entitlements you are able to gift to other users.

New in version 2.0.

Raises

HTTPException – Retrieving the giftable entitlements failed.

Returns

The giftable entitlements for your account.

Return type

List[Entitlement]

await guild_affinities()

This function is a coroutine.

Retrieves the guild affinities for the current user.

Guild affinities are the guilds you interact with most frecently.

New in version 2.0.

Raises

HTTPException – Retrieving the guild affinities failed.

Returns

The guild affinities.

Return type

List[GuildAffinity]

property guild_experiments

The guild experiments assignments for the connected client.

New in version 2.1.

Type

Sequence[GuildExperiment]

property guilds

The guilds that the connected client is a member of.

Type

Sequence[Guild]

await handle_captcha(exception, /)

This function is a coroutine.

Handles a CAPTCHA challenge and returns a solution.

The default implementation tries to use the CAPTCHA handler passed in the constructor.

New in version 2.1.

Parameters

exception (CaptchaRequired) – The exception that was raised.

Raises

CaptchaRequired – The CAPTCHA challenge could not be solved.

Returns

The solution to the CAPTCHA challenge.

Return type

str

property idle_since

When the client went idle.

This indicates that you are truly idle and not just lying.

New in version 2.1.

Type

Optional[datetime.datetime]

property initial_activities

The activities set upon logging in.

Type

List[BaseActivity]

property initial_activity

The primary activity set upon logging in.

Note

The client may be setting multiple activities, these can be accessed under initial_activities.

Type

Optional[BaseActivity]

property initial_status

The status set upon logging in.

New in version 2.0.

Type

Optional[Status]

await invites()

This function is a coroutine.

Gets a list of the user’s friend Invites.

New in version 2.0.

Raises

HTTPException – Getting the invites failed.

Returns

The list of invites.

Return type

List[Invite]

await invoke(ctx, /)

This function is a coroutine.

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

Changed in version 2.0: ctx parameter is now positional-only.

Parameters

ctx (Context) – The invocation context to invoke.

is_afk()

bool: Indicates if the client is currently AFK.

This allows the Discord client to know how to handle push notifications better for you in case you are away from your keyboard.

New in version 2.1.

is_closed()

bool: Indicates if the websocket connection is closed.

is_on_mobile()

bool: A helper function that determines if the user is active on a mobile device.

New in version 2.0.

await is_owner(user, /)

This function is a coroutine.

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

Changed in version 2.0: user parameter is now positional-only.

Parameters

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

Raises

AttributeError – Owners aren’t set.

Returns

Whether the user is the owner.

Return type

bool

is_ready()

bool: Specifies if the client’s internal cache is ready for use.

is_ws_ratelimited()

bool: Whether the websocket is currently rate limited.

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

New in version 1.6.

await join_active_developer_program(*, application, channel)

This function is a coroutine.

Joins the current user to the active developer program.

New in version 2.0.

Parameters
  • application (Application) – The application to join the active developer program with.

  • channel (TextChannel) – The channel to add the developer program webhook to.

Raises

HTTPException – Joining the active developer program failed.

Returns

The created webhook ID.

Return type

int

await join_guild(guild_id, /, lurking=False)

This function is a coroutine.

Joins a discoverable Guild.

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

  • lurking (bool) – Whether to lurk the guild.

Raises
  • NotFound – Guild with given ID does not exist/have discovery enabled.

  • HTTPException – Joining the guild failed.

Returns

The guild that was joined.

Return type

Guild

await join_hub(guild, email, *, code=None)

This function is a coroutine.

Joins the user to or requests a verification code for a Student Hub.

New in version 2.1.

Parameters
  • guild (Guild) – The hub to join.

  • email (str) – The email to join with.

  • code (Optional[str]) –

    The email verification code.

    Note

    If not provided, this method requests a verification code instead.

Raises

HTTPException – Joining the hub or requesting the verification code failed.

Returns

The joined hub, if a code was provided.

Return type

Optional[Guild]

await join_hub_waitlist(email, school)

This function is a coroutine.

Signs up for the Discord Student Hub waitlist.

New in version 2.1.

Parameters
  • email (str) – The email to sign up with.

  • school (str) – The school name to sign up with.

Raises

HTTPException – Signing up for the waitlist failed.

property latency

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

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

Type

float

await leave_active_developer_program()

This function is a coroutine.

Leaves the current user from the active developer program. This does not remove the created webhook.

New in version 2.0.

Raises

HTTPException – Leaving the active developer program failed.

await leave_guild(guild, /, lurking=...)

This function is a coroutine.

Leaves a guild. Equivalent to Guild.leave().

New in version 2.0.

Parameters
  • guild (Snowflake) – The guild to leave.

  • lurking (bool) – Whether you are lurking the guild.

Raises

HTTPException – Leaving the guild failed.

await legacy_settings()

This function is a coroutine.

Retrieves your legacy user settings.

New in version 2.0.

Deprecated since version 2.0.

Note

This method is no longer the recommended way to fetch your settings. Use fetch_settings() instead.

Note

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

Raises

HTTPException – Retrieving your settings failed.

Returns

The current settings for your account.

Return type

LegacyUserSettings

await library()

This function is a coroutine.

Retrieves the applications in your library.

New in version 2.0.

Raises

HTTPException – Retrieving the library failed.

Returns

The applications in your library.

Return type

List[LibraryApplication]

await load_extension(name, *, package=None)

This function is a coroutine.

Loads an extension.

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

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

Changed in version 2.0: This method is now a coroutine.

Parameters
  • name (str) – The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to 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.

await login(token)

This function is a coroutine.

Logs in the client with the specified credentials and calls the setup_hook().

Warning

Logging on with a user token is unfortunately against the Discord Terms of Service and doing so might potentially get your account banned. Use this at your own risk.

Parameters

token (str) – The authentication token.

Raises
  • LoginFailure – The wrong credentials are passed.

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

await lookup_hubs(email, /)

This function is a coroutine.

Looks up the Discord Student Hubs for the given email.

Note

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

New in version 2.1.

Parameters

email (str) – The email to look up.

Raises

HTTPException – Looking up the hubs failed.

Returns

The hubs found.

Return type

List[Guild]

await notes()

This function is a coroutine.

Retrieves a list of Note objects representing all your notes.

New in version 1.9.

Raises

HTTPException – Retrieving the notes failed.

Returns

All your notes.

Return type

List[Note]

property notification_settings

Returns the notification settings for private channels.

If not found, an instance is created with defaults applied. This follows Discord behaviour.

New in version 2.0.

Type

GuildSettings

await on_command_error(context, exception, /)

This function is a coroutine.

The default command error handler provided by the bot.

By default this logs to the library logger, however it could be overridden to have a different implementation.

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

Changed in version 2.0: context and exception parameters are now positional-only. Instead of writing to sys.stderr this now uses the library logger.

await on_error(event_method, /, *args, **kwargs)

This function is a coroutine.

The default error handler provided by the client.

By default this logs to the library logger however it could be overridden to have a different implementation. Check on_error() for more details.

Changed in version 2.0: event_method parameter is now positional-only and instead of writing to sys.stderr it logs instead.

await payment_sources()

This function is a coroutine.

Retrieves all the payment sources for your account.

New in version 2.0.

Raises

HTTPException – Retrieving the payment sources failed.

Returns

The payment sources.

Return type

List[PaymentSource]

async for ... in payments(*, limit=100, before=None, after=None, oldest_first=None)

Returns an asynchronous iterator that enables receiving your payments.

New in version 2.0.

Examples

Usage

counter = 0
async for payment in client.payments(limit=200):
    if payment.is_purchased_externally():
        counter += 1

Flattening into a list:

payments = [payment async for payment in client.payments(limit=123)]
# payments is now a list of Payment...

All parameters are optional.

Parameters
  • limit (Optional[int]) – The number of payments to retrieve. If None, retrieves every payment you have made. Note, however, that this would make it a slow operation.

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

  • after (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages after this date or payment. 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.

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

Raises

HTTPException – The request to get payments failed.

Yields

Payment – The payment made.

property pending_payments

The pending payments that the connected client has.

New in version 2.0.

Type

Sequence[Payment]

await pomelo_suggestion()

This function is a coroutine.

Gets the suggested pomelo username for your account. This username can be used with edit() to migrate your account to Discord’s new unique username system

Note

This method requires you to be in the pomelo rollout.

New in version 2.1.

Raises

HTTPException – You are not in the pomelo rollout.

Returns

The suggested username.

Return type

str

property preferred_rtc_regions

Geo-ordered list of voice regions the connected client can use.

New in version 2.0.

Changed in version 2.1: Rename from preferred_voice_regions to preferred_rtc_regions.

Type

List[str]

await premium_entitlements(*, exclude_consumed=True)

This function is a coroutine.

Retrieves the entitlements this account has granted for the premium application.

These are the entitlements used for premium subscriptions, referred to as “Nitro Credits”.

New in version 2.0.

Parameters

exclude_consumed (bool) – Whether to exclude consumed entitlements.

Raises

HTTPException – Fetching the entitlements failed.

Returns

The entitlements retrieved.

Return type

List[Entitlement]

await premium_guild_subscription_cooldown()

This function is a coroutine.

Retrieves the cooldown for your premium guild subscriptions (boosts).

New in version 2.0.

Raises

HTTPException – Retrieving the cooldown failed.

Returns

Your account’s premium guild subscription cooldown.

Return type

PremiumGuildSubscriptionCooldown

await premium_guild_subscription_slots()

This function is a coroutine.

Retrieves all the premium guild subscription (boost) slots available on your account.

New in version 2.0.

Raises

HTTPException – Retrieving the subscriptions failed.

Returns

Your account’s premium guild subscription slots.

Return type

List[PremiumGuildSubscriptionSlot]

await premium_guild_subscriptions()

This function is a coroutine.

Retrieves all the premium guild subscriptions (boosts) on your account.

New in version 2.0.

Raises

HTTPException – Retrieving the subscriptions failed.

Returns

Your account’s premium guild subscriptions.

Return type

List[PremiumGuildSubscription]

await premium_subscription_plans()

This function is a coroutine.

Retrieves all premium subscription plans.

New in version 2.0.

Raises

HTTPException – Retrieving the premium subscription plans failed.

Returns

The premium subscription plans.

Return type

List[SubscriptionPlan]

await premium_usage()

This function is a coroutine.

Retrieves the usage of the premium perks on your account.

New in version 2.0.

Raises

HTTPException – Retrieving the premium usage failed.

Returns

The premium usage.

Return type

PremiumUsage

await preview_subscription(items, *, payment_source=None, currency='usd', trial=None, apply_entitlements=True, renewal=False, code=None, metadata=None, guild=None)

This function is a coroutine.

Preview an invoice for the subscription with the given parameters.

All parameters are optional and default to the current subscription values.

New in version 2.0.

Parameters
  • items (List[SubscriptionItem]) – The items the previewed subscription should have.

  • payment_source (Optional[PaymentSource]) – The payment source the previewed subscription should be paid with.

  • currency (str) – The currency the previewed subscription should be paid in.

  • trial (Optional[SubscriptionTrial]) – The trial plan the previewed subscription should be on.

  • apply_entitlements (bool) – Whether to apply entitlements (credits) to the previewed subscription.

  • renewal (bool) – Whether the previewed subscription should be a renewal.

  • code (Optional[str]) – Unknown.

  • metadata (Optional[Mapping[str, Any]]) – Extra metadata about the subscription.

  • guild (Optional[Guild]) – The guild the previewed subscription’s entitlements should be applied to.

Raises

HTTPException – Failed to preview the invoice.

Returns

The previewed invoice.

Return type

SubscriptionInvoice

await price_tiers()

This function is a coroutine.

Retrieves all price tiers.

New in version 2.0.

Raises

HTTPException – Retrieving the price tiers failed.

Returns

The price tiers.

Return type

List[int]

await pricing_promotion()

This function is a coroutine.

Retrieves the current localized pricing promotion for your account, if any.

This also updates your current country code.

New in version 2.0.

Raises

HTTPException – Retrieving the pricing promotion failed.

Returns

The pricing promotion for your account, if any.

Return type

Optional[PricingPromotion]

property private_channels

The private channels that the connected client is participating on.

Type

Sequence[abc.PrivateChannel]

await process_commands(message, /)

This function is a coroutine.

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

By default, this coroutine is called inside the on_message() event. If you choose to override 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.

Changed in version 2.0: message parameter is now positional-only.

Parameters

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

await promotions(claimed=False)

This function is a coroutine.

Retrieves all the promotions available for your account.

New in version 2.0.

Parameters

claimed (bool) – Whether to only retrieve claimed promotions. These will have Promotion.claimed_at and Promotion.code set.

Raises

HTTPException – Retrieving the promotions failed.

Returns

The promotions available for you.

Return type

List[Promotion]

property raw_status

The user’s overall status as a string value.

New in version 2.0.

Type

str

property read_states

The read states that the connected client has.

New in version 2.1.

Type

List[ReadState]

async for ... in recent_mentions(*, limit=25, before=..., guild=..., roles=True, everyone=True)

Returns an asynchronous iterator that enables receiving your recent mentions.

New in version 2.0.

Examples

Usage

counter = 0
async for message in client.recent_mentions(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = [message async for message in client.recent_mentions(limit=123)]
# 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 recent mention received in the past week. Note, however, that this would make it a slow operation.

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

  • guild (Guild) – The guild to retrieve recent mentions from. If not provided, then the mentions are retrieved from all guilds.

  • roles (bool) – Whether to include role mentions.

  • everyone (bool) – Whether to include @everyone or @here mentions.

Raises

HTTPException – The request to get recent message history failed.

Yields

Message – The message with the message data parsed.

await relationship_activity_statistics()

This function is a coroutine.

Retrieves the available activity usage statistics for your relationships’ owned applications.

New in version 2.0.

Raises

HTTPException – Retrieving the statistics failed.

Returns

The activity statistics.

Return type

List[ApplicationActivityStatistics]

property relationships

Returns all the relationships that the connected client has.

New in version 2.0.

Type

Sequence[Relationship]

await reload_extension(name, *, package=None)

This function is a coroutine.

Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to 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_check(func, /, *, call_once=False)

Removes a global check from the bot.

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

Changed in version 2.0: func parameter is now positional-only.

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

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

await remove_cog(name, /)

This function is a coroutine.

Removes a cog from the bot and returns it.

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

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

Changed in version 2.0: name parameter is now positional-only.

Changed in version 2.0: This method is now a coroutine.

Parameters

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

Returns

The cog that was removed. None if not found.

Return type

Optional[Cog]

remove_command(name, /)

Remove a Command from the internal list of commands.

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

Changed in version 2.0: name parameter is now positional-only.

Parameters

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

Returns

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

Return type

Optional[Command]

remove_listener(func, /, name=...)

Removes a listener from the pool of listeners.

Changed in version 2.0: func parameter is now positional-only.

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

  • name (str) – The name of the event we want to remove. Defaults to func.__name__.

await report_unverified_application(name, *, icon, os, executable=..., publisher=..., distributor=..., sku=...)

This function is a coroutine.

Reports an unverified application (a game not detected by the Discord client) to Discord.

If missing, this also uploads the application icon to Discord.

New in version 2.1.

Parameters
  • name (str) – The name of the application.

  • icon (File) – The icon of the application.

  • os (OperatingSystem) – The operating system the application is found on.

  • executable (str) – The executable of the application.

  • publisher (str) – The publisher of the application.

  • distributor (Distributor) – The distributor of the application SKU.

  • sku (str) – The SKU of the application.

Raises

HTTPException – Reporting the unverified application failed.

Returns

The reported unverified application.

Return type

UnverifiedApplication

property required_action

The required action for the current user. A required action is something Discord requires you to do to continue using your account.

New in version 2.0.

Type

Optional[RequiredActionType]

await revoke_invites()

This function is a coroutine.

Revokes all of the user’s friend Invites.

New in version 2.0.

Raises

HTTPException – Revoking the invites failed.

Returns

The revoked invites.

Return type

List[Invite]

run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)

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

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

This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing None to the log_handler parameter.

Warning

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

Parameters
  • token (str) – The authentication token.

  • reconnect (bool) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as bad tokens).

  • log_handler (Optional[logging.Handler]) –

    The log handler to use for the library’s logger. If this is None then the library will not set up anything logging related. Logging will still work if None is passed, though it is your responsibility to set it up.

    The default log handler if not provided is logging.StreamHandler.

    New in version 2.0.

  • log_formatter (logging.Formatter) –

    The formatter to use with the given log handler. If not provided then it defaults to a colour based logging formatter (if available).

    New in version 2.0.

  • log_level (int) –

    The default log level for the library’s logger. This is only applied if the log_handler parameter is not None. Defaults to logging.INFO.

    New in version 2.0.

  • root_logger (bool) –

    Whether to set up the root logger rather than the library logger. By default, only the library logger ('discord') is set up. If this is set to True then the root logger is set up as well.

    Defaults to False.

    New in version 2.0.

await search_companies(query, /)

This function is a coroutine.

Query your created companies.

New in version 2.0.

Parameters

query (str) – The query to search for.

Raises

HTTPException – Searching failed.

Returns

The companies found.

Return type

List[Company]

await send_friend_request(*args)

This function is a coroutine.

Sends a friend request to another user.

This function can be used in multiple ways.

New in version 2.0.

# Passing a user object:
await client.send_friend_request(user)

# Passing a username
await client.send_friend_request('jake')

# Passing a legacy user:
await client.send_friend_request('Jake#0001')

# Passing a legacy username and discriminator:
await client.send_friend_request('Jake', '0001')
Parameters
  • user (Union[discord.User, str]) – The user to send the friend request to.

  • username (str) – The username of the user to send the friend request to.

  • discriminator (str) – The discriminator of the user to send the friend request to.

Raises
  • Forbidden – Not allowed to send a friend request to this user.

  • HTTPException – Sending the friend request failed.

  • TypeError – More than 2 parameters or less than 1 parameter was passed.

property sessions

The gateway sessions that the current user is connected in with.

When connected, this includes a representation of the library’s session and an “all” session representing the user’s overall presence.

New in version 2.0.

Type

Sequence[Session]

property settings

Returns the user’s settings.

New in version 2.0.

Type

Optional[UserSettings]

await setup_hook()

This function is a coroutine.

A coroutine to be called to setup the client, by default this is blank.

To perform asynchronous setup after the user is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in login(), and will be called before any events are dispatched, making it a better solution than doing such setup in the on_ready() event.

Warning

Since this is called before the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like wait_for() and wait_until_ready().

New in version 2.0.

await start(token, *, reconnect=True)

This function is a coroutine.

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

Parameters
  • token (str) – The authentication token.

  • reconnect (bool) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as bad tokens).

Raises

TypeError – An unexpected keyword argument was received.

property status

The user’s overall status.

New in version 2.0.

Type

Status

await sticker_packs()

This function is a coroutine.

Retrieves all available default sticker packs.

New in version 2.0.

Raises

HTTPException – Retrieving the sticker packs failed.

Returns

All available sticker packs.

Return type

List[StickerPack]

property stickers

The stickers that the connected client has.

New in version 2.0.

Type

Sequence[GuildSticker]

await subscriptions(limit=None, with_inactive=False)

This function is a coroutine.

Retrieves all the subscriptions on your account.

New in version 2.0.

Parameters
  • limit (Optional[int]) – The maximum number of subscriptions to retrieve. Defaults to all subscriptions.

  • with_inactive (bool) – Whether to include inactive subscriptions.

Raises

HTTPException – Retrieving the subscriptions failed.

Returns

Your account’s subscriptions.

Return type

List[Subscription]

await teams(*, with_payout_account_status=False)

This function is a coroutine.

Retrieves all the teams you’re a part of.

New in version 2.0.

Parameters

with_payout_account_status (bool) – Whether to return the payout account status of the teams.

Raises

HTTPException – Retrieving the teams failed.

Returns

The teams you’re a part of.

Return type

List[Team]

property tracking_settings

Returns your tracking consents, if available.

New in version 2.0.

Type

Optional[TrackingSettings]

await trial_offer()

This function is a coroutine.

Retrieves the current trial offer for your account.

New in version 2.0.

Raises
Returns

The trial offer for your account.

Return type

TrialOffer

property tutorial

The tutorial state of the connected client.

New in version 2.1.

Type

Tutorial

await unload_extension(name, *, package=None)

This function is a coroutine.

Unloads an extension.

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

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

Changed in version 2.0: This method is now a coroutine.

Parameters
  • name (str) – The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to 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

Represents the connected client. None if not logged in.

Type

Optional[ClientUser]

await user_affinities()

This function is a coroutine.

Retrieves the user affinities for the current user.

User affinities are the users you interact with most frecently.

New in version 2.0.

Raises

HTTPException – Retrieving the user affinities failed.

Returns

The user affinities.

Return type

List[UserAffinity]

property users

Returns a list of all the users the current user can see.

Type

List[User]

property voice_client

Returns the VoiceProtocol associated with private calls, if any.

Type

Optional[VoiceProtocol]

property voice_clients

Represents a list of voice connections.

These are usually VoiceClient instances.

Type

List[VoiceProtocol]

wait_for(event, /, *, check=None, timeout=None)

This function is a coroutine.

Waits for a WebSocket event to be dispatched.

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

The timeout parameter is passed 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}!')

Waiting for a thumbs up reaction from the message author:

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

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

        try:
            reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
        except asyncio.TimeoutError:
            await channel.send('👎')
        else:
            await channel.send('👍')

Changed in version 2.0: event parameter is now positional-only.

Parameters
  • event (str) – The event name, similar to the event reference, but without the on_ prefix, to wait for.

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

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

Raises

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

Returns

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

Return type

Any

await wait_until_ready()

This function is a coroutine.

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

Warning

Calling this inside setup_hook() can lead to a deadlock.

for ... in walk_commands()

An iterator that recursively walks through all commands and subcommands.

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

Yields

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

Prefix Helpers

discord.ext.commands.when_mentioned(bot, msg, /)

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

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

Changed in version 2.0: bot and msg parameters are now positional-only.

discord.ext.commands.when_mentioned_or(*prefixes)

A callable that implements when mentioned or other prefixes provided.

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

Example

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

Note

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

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

See also

when_mentioned()

Event Reference

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

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

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

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

Parameters
  • ctx (Context) – The invocation context.

  • error (CommandError derived) – The error that was raised.

discord.ext.commands.on_command(ctx)

An event that is called when a command is found and is about to be invoked.

This event is called regardless of whether the command itself succeeds via error or completes.

Parameters

ctx (Context) – The invocation context.

discord.ext.commands.on_command_completion(ctx)

An event that is called when a command has completed its invocation.

This event is called only if the command succeeded, i.e. all checks have passed and the user input it correctly.

Parameters

ctx (Context) – The invocation context.

Commands

Decorators

@discord.ext.commands.command(name=..., cls=..., **attrs)

A decorator that transforms a function into a Command or if called 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.

@discord.ext.commands.group(name=..., cls=..., **attrs)

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.

Command

class discord.ext.commands.Command(*args, **kwargs)

A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the command.

Type

str

callback

The coroutine that is executed when the command is called.

Type

coroutine

help

The long help text for the command.

Type

Optional[str]

brief

The short help text for the command.

Type

Optional[str]

usage

A replacement for arguments in the default help text.

Type

Optional[str]

aliases

The list of aliases the command can be invoked under.

Type

Union[List[str], Tuple[str]]

enabled

A boolean that indicates if the command is currently enabled. If the command is invoked while it is disabled, then DisabledCommand is raised to 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.

Type

dict

New in version 2.0.

@after_invoke

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

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

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

See Bot.after_invoke() for more info.

Changed in version 2.0: coro parameter is now positional-only.

Parameters

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

Raises

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke

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

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

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

See Bot.before_invoke() for more info.

Changed in version 2.0: coro parameter is now positional-only.

Parameters

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

Raises

TypeError – The coroutine passed is not actually a coroutine.

@error

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

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

Changed in version 2.0: coro parameter is now positional-only.

Parameters

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

Raises

TypeError – The coroutine passed is not actually a coroutine.

add_check(func, /)

Adds a check to the command.

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

New in version 1.3.

Changed in version 2.0: func parameter is now positional-only.

Parameters

func – The function that will be used as a check.

remove_check(func, /)

Removes a check from the command.

This function is idempotent and will not raise an exception if the function is not in the command’s checks.

New in version 1.3.

Changed in version 2.0: func parameter is now positional-only.

Parameters

func – The function to remove from the checks.

update(**kwargs)

Updates Command instance with updated attribute.

This works similarly to the command() decorator in terms of parameters in that they are passed to the Command or subclass constructors, sans the name and callback.

await __call__(context, /, *args, **kwargs)

This function is a coroutine.

Calls the internal callback that the command holds.

Note

This bypasses all mechanisms – including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments and types to this function.

New in version 1.3.

Changed in version 2.0: context parameter is now positional-only.

copy()

Creates a copy of this command.

Returns

A new instance of this command.

Return type

Command

property clean_params

Dict[str, Parameter]: Retrieves the parameter dictionary without the context or self parameters.

Useful for inspecting signature.

property cooldown

The cooldown of a command when invoked or None if the command doesn’t have a registered cooldown.

New in version 2.0.

Type

Optional[Cooldown]

property full_parent_name

Retrieves the fully qualified parent command name.

This the base command name required to execute it. For example, in ?one two three the parent name would be one two.

Type

str

property parents

Retrieves the parents of this command.

If the command has no parents then it returns an empty list.

For example in commands ?a b c test, the parents are [c, b, a].

New in version 1.1.

Type

List[Group]

property root_parent

Retrieves the root parent of this command.

If the command has no parents then it returns None.

For example in commands ?a b c test, the root parent is a.

Type

Optional[Group]

property qualified_name

Retrieves the fully qualified command name.

This is the full parent name with the command name as well. For example, in ?one two three the qualified name would be one two three.

Type

str

is_on_cooldown(ctx, /)

Checks whether the command is currently on cooldown.

Changed in version 2.0: ctx parameter is now positional-only.

Parameters

ctx (Context) – The invocation context to use when checking the commands cooldown status.

Returns

A boolean indicating if the command is on cooldown.

Return type

bool

reset_cooldown(ctx, /)

Resets the cooldown on this command.

Changed in version 2.0: ctx parameter is now positional-only.

Parameters

ctx (Context) – The invocation context to reset the cooldown under.

get_cooldown_retry_after(ctx, /)

Retrieves the amount of seconds before this command can be tried again.

New in version 1.4.

Changed in version 2.0: ctx parameter is now positional-only.

Parameters

ctx (Context) – The invocation context to retrieve the cooldown from.

Returns

The amount of time left on this command’s cooldown in seconds. If this is 0.0 then the command isn’t on cooldown.

Return type

float

has_error_handler()

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

New in version 1.7.

property cog_name

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

Type

Optional[str]

property short_doc

Gets the “short” documentation of a command.

By default, this is the brief attribute. If that lookup leads to an empty string then the first line of the help attribute is used instead.

Type

str

property signature

Returns a POSIX-like signature useful for help command output.

Type

str

await can_run(ctx, /)

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute. This also checks whether the command is disabled.

Changed in version 1.3: Checks whether the command is disabled or not

Changed in version 2.0: ctx parameter is now positional-only.

Parameters

ctx (Context) – The ctx of the command currently being invoked.

Raises

CommandError – Any command error that was raised during a check call will be propagated by this function.

Returns

A boolean indicating if the command can be invoked.

Return type

bool

Group

class discord.ext.commands.Group(*args, **kwargs)

A class that implements a grouping protocol for commands to be executed as subcommands.

This class is a subclass of Command and thus all options valid 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

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

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

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

See Bot.after_invoke() for more info.

Changed in version 2.0: coro parameter is now positional-only.

Parameters

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

Raises

TypeError – The coroutine passed is not actually a coroutine.

@before_invoke

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

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

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

See Bot.before_invoke() for more info.

Changed in version 2.0: coro parameter is now positional-only.

Parameters

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

Raises

TypeError – The coroutine passed is not actually a coroutine.

@command(*args, **kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list 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

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.

Changed in version 2.0: coro parameter is now positional-only.

Parameters

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

Raises

TypeError – The coroutine passed is not actually a coroutine.

@group(*args, **kwargs)

A shortcut decorator that invokes group() and adds it to the internal command list 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()

Creates a copy of this Group.

Returns

A new instance of this group.

Return type

Group

add_check(func, /)

Adds a check to the command.

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

New in version 1.3.

Changed in version 2.0: func parameter is now positional-only.

Parameters

func – The function that will be used as a check.

add_command(command, /)

Adds a Command into the internal list of commands.

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

Changed in version 1.4: Raise CommandRegistrationError instead of generic ClientException

Changed in version 2.0: command parameter is now positional-only.

Parameters

command (Command) – The command to add.

Raises
await can_run(ctx, /)

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute. This also checks whether the command is disabled.

Changed in version 1.3: Checks whether the command is disabled or not

Changed in version 2.0: ctx parameter is now positional-only.

Parameters

ctx (Context) – The ctx of the command currently being invoked.

Raises

CommandError – Any command error that was raised during a check call will be propagated by this function.

Returns

A boolean indicating if the command can be invoked.

Return type

bool

property clean_params

Dict[str, Parameter]: Retrieves the parameter dictionary without the context or self parameters.

Useful for inspecting signature.

property cog_name

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

Type

Optional[str]

property commands

A unique set of commands without aliases that are registered.

Type

Set[Command]

property cooldown

The cooldown of a command when invoked or None if the command doesn’t have a registered cooldown.

New in version 2.0.

Type

Optional[Cooldown]

property full_parent_name

Retrieves the fully qualified parent command name.

This the base command name required to execute it. For example, in ?one two three the parent name would be one two.

Type

str

get_command(name, /)

Get a Command from the internal list of commands.

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

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

Changed in version 2.0: name parameter is now positional-only.

Parameters

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

Returns

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

Return type

Optional[Command]

get_cooldown_retry_after(ctx, /)

Retrieves the amount of seconds before this command can be tried again.

New in version 1.4.

Changed in version 2.0: ctx parameter is now positional-only.

Parameters

ctx (Context) – The invocation context to retrieve the cooldown from.

Returns

The amount of time left on this command’s cooldown in seconds. If this is 0.0 then the command isn’t on cooldown.

Return type

float

has_error_handler()

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

New in version 1.7.

is_on_cooldown(ctx, /)

Checks whether the command is currently on cooldown.

Changed in version 2.0: ctx parameter is now positional-only.

Parameters

ctx (Context) – The invocation context to use when checking the commands cooldown status.

Returns

A boolean indicating if the command is on cooldown.

Return type

bool

property parents

Retrieves the parents of this command.

If the command has no parents then it returns an empty list.

For example in commands ?a b c test, the parents are [c, b, a].

New in version 1.1.

Type

List[Group]

property qualified_name

Retrieves the fully qualified command name.

This is the full parent name with the command name as well. For example, in ?one two three the qualified name would be one two three.

Type

str

remove_check(func, /)

Removes a check from the command.

This function is idempotent and will not raise an exception if the function is not in the command’s checks.

New in version 1.3.

Changed in version 2.0: func parameter is now positional-only.

Parameters

func – The function to remove from the checks.

remove_command(name, /)

Remove a Command from the internal list of commands.

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

Changed in version 2.0: name parameter is now positional-only.

Parameters

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

Returns

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

Return type

Optional[Command]

reset_cooldown(ctx, /)

Resets the cooldown on this command.

Changed in version 2.0: ctx parameter is now positional-only.

Parameters

ctx (Context) – The invocation context to reset the cooldown under.

property root_parent

Retrieves the root parent of this command.

If the command has no parents then it returns None.

For example in commands ?a b c test, the root parent is a.

Type

Optional[Group]

property short_doc

Gets the “short” documentation of a command.

By default, this is the brief attribute. If that lookup leads to an empty string then the first line of the help attribute is used instead.

Type

str

property signature

Returns a POSIX-like signature useful for help command output.

Type

str

update(**kwargs)

Updates Command instance with updated attribute.

This works similarly to the command() decorator in terms of parameters in that they are passed to the Command or subclass constructors, sans the name and callback.

for ... in walk_commands()

An iterator that recursively walks through all commands and subcommands.

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

Yields

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

GroupMixin

class discord.ext.commands.GroupMixin(*args, **kwargs)

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)

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)

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

A unique set of commands without aliases that are registered.

Type

Set[Command]

add_command(command, /)

Adds a Command into the internal list of commands.

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

Changed in version 1.4: Raise CommandRegistrationError instead of generic ClientException

Changed in version 2.0: command parameter is now positional-only.

Parameters

command (Command) – The command to add.

Raises
remove_command(name, /)

Remove a Command from the internal list of commands.

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

Changed in version 2.0: name parameter is now positional-only.

Parameters

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

Returns

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

Return type

Optional[Command]

for ... in walk_commands()

An iterator that recursively walks through all commands and subcommands.

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

Yields

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

get_command(name, /)

Get a Command from the internal list of commands.

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

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

Changed in version 2.0: name parameter is now positional-only.

Parameters

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

Returns

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

Return type

Optional[Command]

Cogs

Cog

class discord.ext.commands.Cog(*args, **kwargs)

The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the Cogs page.

When inheriting from this class, the options shown in CogMeta are equally valid here.

get_commands()
Returns

A list of Commands that are defined inside this cog.

Note

This does not include subcommands.

Return type

List[Command]

property qualified_name

Returns the cog’s specified name, not the class name.

Type

str

property description

Returns the cog’s description, typically the cleaned docstring.

Type

str

for ... in walk_commands()

An iterator that recursively walks through this cog’s commands and subcommands.

Yields

Union[Command, Group] – A command or group from the cog.

get_listeners()

Returns a list of (name, function) listener pairs that are defined in this cog.

Returns

The listeners defined in this cog.

Return type

List[Tuple[str, coroutine]]

classmethod listener(name=...)

A decorator that marks a function as a listener.

This is the cog equivalent of Bot.listen().

Parameters

name (str) – The name of the event being listened to. If not provided, it defaults to the function’s name.

Raises

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

has_error_handler()

bool: Checks whether the cog has an error handler.

New in version 1.7.

await cog_load()

This function could be a coroutine.

A special method that is called when the cog gets loaded.

Subclasses must replace this if they want special asynchronous loading behaviour. Note that the __init__ special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.

New in version 2.0.

await cog_unload()

This function could be a coroutine.

A special method that is called when the cog gets removed.

Subclasses must replace this if they want special unloading behaviour.

Exceptions raised in this method are ignored during extension unloading.

Changed in version 2.0: This method can now be a coroutine.

bot_check_once(ctx)

A special method that registers as a Bot.check_once() check.

This function can be a coroutine and must take a sole parameter, ctx, to represent the Context.

bot_check(ctx)

A special method that registers as a Bot.check() check.

This function can be a coroutine and must take a sole parameter, ctx, to represent the Context.

cog_check(ctx)

A special method that registers as a check() for every command and subcommand in this cog.

This function can be a coroutine and must take a sole parameter, ctx, to represent the Context.

await cog_command_error(ctx, error)

This function is a coroutine.

A special method that is called whenever an error is dispatched inside this cog.

This is similar to on_command_error() except only applying to the commands inside this cog.

This must be a coroutine.

Parameters
  • ctx (Context) – The invocation context where the error happened.

  • error (CommandError) – The error that happened.

await cog_before_invoke(ctx)

This function is a coroutine.

A special method that acts as a cog local pre-invoke hook.

This is similar to Command.before_invoke().

This must be a coroutine.

Parameters

ctx (Context) – The invocation context.

await cog_after_invoke(ctx)

This function is a coroutine.

A special method that acts as a cog local post-invoke hook.

This is similar to Command.after_invoke().

This must be a coroutine.

Parameters

ctx (Context) – The invocation context.

CogMeta

class discord.ext.commands.CogMeta(*args, **kwargs)

A metaclass for defining a cog.

Note that you should probably not use this directly. It is exposed purely for documentation purposes along with making custom metaclasses to intermix with other metaclasses such as 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

Help Commands

HelpCommand

class discord.ext.commands.HelpCommand(*args, **kwargs)

The base implementation for help command formatting.

Note

Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in GH-2123.

This means that relying on the state of this class to be the same between command invocations would not work as expected.

context

The context that invoked this help formatter. This is generally set after the help command assigned, command_callback(), has been called.

Type

Optional[Context]

show_hidden

Specifies if hidden commands should be shown in the output. Defaults 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, /)

Adds a check to the help command.

New in version 1.4.

Changed in version 2.0: func parameter is now positional-only.

Parameters

func – The function that will be used as a check.

remove_check(func, /)

Removes a check from the help command.

This function is idempotent and will not raise an exception if the function is not in the command’s checks.

New in version 1.4.

Changed in version 2.0: func parameter is now positional-only.

Parameters

func – The function to remove from the checks.

get_bot_mapping()

Retrieves the bot mapping passed to send_bot_help().

property invoked_with

Similar to Context.invoked_with except properly handles the case 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

Optional[str]

get_command_signature(command, /)

Retrieves the signature portion of the help page.

Changed in version 2.0: command parameter is now positional-only.

Parameters

command (Command) – The command to get the signature of.

Returns

The signature for the command.

Return type

str

remove_mentions(string, /)

Removes mentions from the string to prevent abuse.

This includes @everyone, @here, member mentions and role mentions.

Changed in version 2.0: string parameter is now positional-only.

Returns

The string with mentions removed.

Return type

str

property cog

A property for retrieving or setting the cog for the help command.

When a cog is set for the help command, it is as-if the help command belongs to that cog. All cog special methods will apply to the help command and it will be automatically unset on unload.

To unbind the cog from the help command, you can set it to None.

Returns

The cog that is currently set for the help command.

Return type

Optional[Cog]

command_not_found(string, /)

This function could be a coroutine.

A method called when a command is not found in the help command. This is useful to override for i18n.

Defaults to No command called {0} found.

Changed in version 2.0: string parameter is now positional-only.

Parameters

string (str) – The string that contains the invalid command. Note that this has had mentions removed to prevent abuse.

Returns

The string to use when a command has not been found.

Return type

str

subcommand_not_found(command, string, /)

This function could be a coroutine.

A method called when a command did not have a subcommand requested in the help command. This is useful to override for i18n.

Defaults to either:

  • 'Command "{command.qualified_name}" has no subcommands.'
    • If there is no subcommand in the command parameter.

  • 'Command "{command.qualified_name}" has no subcommand named {string}'
    • If the command parameter has subcommands but not one named string.

Changed in version 2.0: command and string parameters are now positional-only.

Parameters
  • command (Command) – The command that did not have the subcommand requested.

  • string (str) – The string that contains the invalid subcommand. Note that this has had mentions removed to prevent abuse.

Returns

The string to use when the command did not have the subcommand requested.

Return type

str

await filter_commands(commands, /, *, sort=False, key=None)

This function is a coroutine.

Returns a filtered list of commands and optionally sorts them.

This takes into account the verify_checks and show_hidden attributes.

Changed in version 2.0: commands parameter is now positional-only.

Parameters
  • commands (Iterable[Command]) – An iterable of commands that are getting filtered.

  • sort (bool) – Whether to sort the result.

  • key (Optional[Callable[[Command], Any]]) – An optional key function to pass 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, /)

Returns the largest name length of the specified command list.

Changed in version 2.0: commands parameter is now positional-only.

Parameters

commands (Sequence[Command]) – A sequence of commands to check for the largest size.

Returns

The maximum width of the commands.

Return type

int

get_destination()

Returns the Messageable where the help command will be output.

You can override this method to customise the behaviour.

By default this returns the context’s channel.

Returns

The destination where the help command will be output.

Return type

abc.Messageable

await send_error_message(error, /)

This function is a coroutine.

Handles the implementation when an error happens in the help command. For example, the result 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.

Changed in version 2.0: error parameter is now positional-only.

Parameters

error (str) – The error message to display to the user. Note that this has had mentions removed to prevent abuse.

await on_help_command_error(ctx, error, /)

This function is a coroutine.

The help command’s error handler, as specified by Error Handling.

Useful to override if you need some specific behaviour when the error handler is called.

By default this method does nothing and just propagates to the default error handlers.

Changed in version 2.0: ctx and error parameters are now positional-only.

Parameters
  • ctx (Context) – The invocation context.

  • error (CommandError) – The error that was raised.

await send_bot_help(mapping, /)

This function is a coroutine.

Handles the implementation of the bot command page in the help command. This function is called when the help command is called with no arguments.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should 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.

Changed in version 2.0: mapping parameter is now positional-only.

Parameters

mapping (Mapping[Optional[Cog], List[Command]]) – A mapping of cogs to commands that have been requested by the user for help. The key of the mapping is 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, /)

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.

Changed in version 2.0: cog parameter is now positional-only.

Parameters

cog (Cog) – The cog that was requested for help.

await send_group_help(group, /)

This function is a coroutine.

Handles the implementation of the group page in the help command. This function is called when the help command is called with a group as the argument.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

Note

You can access the invocation context with HelpCommand.context.

To get the commands that belong to this group without aliases see Group.commands. The commands returned not filtered. To do the filtering you will have to call filter_commands() yourself.

Changed in version 2.0: group parameter is now positional-only.

Parameters

group (Group) – The group that was requested for help.

await send_command_help(command, /)

This function is a coroutine.

Handles the implementation of the single command page in the help command.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should 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.

Changed in version 2.0: command parameter is now positional-only.

Parameters

command (Command) – The command that was requested for help.

await prepare_help_command(ctx, command=None, /)

This function is a coroutine.

A low level method that can be used to prepare the help command before it does anything. For example, if you need to prepare some state in your subclass before the command does its processing then this would be the place to do it.

The default implementation does nothing.

Note

This is called inside the help command callback body. So all the usual rules that happen inside apply here as well.

Changed in version 2.0: ctx and command parameters are now positional-only.

Parameters
  • ctx (Context) – The invocation context.

  • command (Optional[str]) – The argument passed to the help command.

await command_callback(ctx, /, *, command=None)

This function is a coroutine.

The actual implementation of the help command.

It is not recommended to override this method and instead change the behaviour through the methods that actually get dispatched.

Changed in version 2.0: ctx parameter is now positional-only.

DefaultHelpCommand

class discord.ext.commands.DefaultHelpCommand(*args, **kwargs)

The implementation of the default help command.

This inherits from HelpCommand.

It extends it with the following attributes.

width

The maximum number of characters that fit in a line. Defaults to 80.

Type

int

sort_commands

Whether to sort the commands in the output alphabetically. Defaults to True.

Type

bool

dm_help

A tribool that indicates if the help command should DM the user instead of sending it to the channel it received it from. If the boolean is set to True, then all help output is DM’d. 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

arguments_heading

The arguments list’s heading string used when the help command is invoked with a command name. Useful for i18n. Defaults to "Arguments:". Shown when show_parameter_descriptions is True.

New in version 2.0.

Type

str

show_parameter_descriptions

Whether to show the parameter descriptions. Defaults to True. Setting this to False will revert to showing the signature instead.

New in version 2.0.

Type

bool

commands_heading

The command list’s heading string used when the help command is invoked with a category name. Useful for i18n. Defaults to "Commands:"

Type

str

default_argument_description

The default argument description string used when the argument’s description is None. Useful for i18n. Defaults to "No description given."

New in version 2.0.

Type

str

no_category

The string used when there is a command which does not belong to any category(cog). Useful for i18n. Defaults to "No Category"

Type

str

paginator

The paginator used to paginate the help command output.

Type

Paginator

shorten_text(text, /)

str: Shortens text to fit into the width.

Changed in version 2.0: text parameter is now positional-only.

get_ending_note()

str: Returns help command’s ending note. This is mainly useful to override for i18n purposes.

get_command_signature(command, /)

Retrieves the signature portion of the help page.

Calls get_command_signature() if show_parameter_descriptions is False else returns a modified signature where the command parameters are not shown.

New in version 2.0.

Parameters

command (Command) – The command to get the signature of.

Returns

The signature for the command.

Return type

str

add_indented_commands(commands, /, *, heading, max_size=None)

Indents a list of commands after the specified heading.

The formatting is added to the paginator.

The default implementation is the command name indented by indent spaces, padded to max_size followed by the command’s Command.short_doc and then shortened to fit into the width.

Changed in version 2.0: commands parameter is now positional-only.

Parameters
  • commands (Sequence[Command]) – A list of commands to indent for output.

  • heading (str) – The heading to add to the output. This is only added if the list of commands is greater than 0.

  • max_size (Optional[int]) – The max size to use for the gap between indents. If unspecified, calls get_max_size() on the commands parameter.

add_command_arguments(command, /)

Indents a list of command arguments after the arguments_heading.

The default implementation is the argument name indented by indent spaces, padded to max_size using get_max_size() followed by the argument’s description or default_argument_description and then shortened to fit into the width and then displayed_default between () if one is present after that.

New in version 2.0.

Parameters

command (Command) – The command to list the arguments for.

await send_pages()

This function is a coroutine.

A helper utility to send the page output from paginator to the destination.

add_command_formatting(command, /)

A utility function to format the non-indented block of commands and groups.

Changed in version 2.0: command parameter is now positional-only.

Changed in version 2.0: add_command_arguments() is now called if show_parameter_descriptions is True.

Parameters

command (Command) – The command to format.

get_destination()

Returns the Messageable where the help command will be output.

You can override this method to customise the behaviour.

By default this returns the context’s channel.

Returns

The destination where the help command will be output.

Return type

abc.Messageable

MinimalHelpCommand

class discord.ext.commands.MinimalHelpCommand(*args, **kwargs)

An implementation of a help command with minimal output.

This inherits from HelpCommand.

sort_commands

Whether to sort the commands in the output alphabetically. Defaults to True.

Type

bool

commands_heading

The command list’s heading string used when the help command is invoked with a category name. Useful for i18n. Defaults to "Commands"

Type

str

aliases_heading

The alias list’s heading string used to list the aliases of the command. Useful for i18n. Defaults to "Aliases:".

Type

str

dm_help

A tribool that indicates if the help command should DM the user instead of sending it to the channel it received it from. If the boolean is set to True, then all help output is DM’d. 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()

This function is a coroutine.

A helper utility to send the page output from paginator to the destination.

get_opening_note()

Returns help command’s opening note. This is mainly useful to override for i18n purposes.

The default implementation returns

Use `{prefix}{command_name} [command]` for more info on a command.
You can also use `{prefix}{command_name} [category]` for more info on a category.
Returns

The help command opening note.

Return type

str

get_command_signature(command, /)

Retrieves the signature portion of the help page.

Changed in version 2.0: command parameter is now positional-only.

Parameters

command (Command) – The command to get the signature of.

Returns

The signature for the command.

Return type

str

get_ending_note()

Return the help command’s ending note. This is mainly useful to override for i18n purposes.

The default implementation does nothing.

Returns

The help command ending note.

Return type

str

add_bot_commands_formatting(commands, heading, /)

Adds the minified bot heading with commands to the output.

The formatting should be added to the paginator.

The default implementation is a bold underline heading followed by commands separated by an EN SPACE (U+2002) in the next line.

Changed in version 2.0: commands and heading parameters are now positional-only.

Parameters
  • commands (Sequence[Command]) – A list of commands that belong to the heading.

  • heading (str) – The heading to add to the line.

add_subcommand_formatting(command, /)

Adds formatting information on a subcommand.

The formatting should be added to the paginator.

The default implementation is the prefix and the Command.qualified_name optionally followed by an En dash and the command’s Command.short_doc.

Changed in version 2.0: command parameter is now positional-only.

Parameters

command (Command) – The command to show information of.

add_aliases_formatting(aliases, /)

Adds the formatting information on a command’s aliases.

The formatting should be added to the paginator.

The default implementation is the aliases_heading bolded followed by a comma separated list of aliases.

This is not called if there are no aliases to format.

Changed in version 2.0: aliases parameter is now positional-only.

Parameters

aliases (Sequence[str]) – A list of aliases to format.

add_command_formatting(command, /)

A utility function to format commands and groups.

Changed in version 2.0: command parameter is now positional-only.

Parameters

command (Command) – The command to format.

get_destination()

Returns the Messageable where the help command will be output.

You can override this method to customise the behaviour.

By default this returns the context’s channel.

Returns

The destination where the help command will be output.

Return type

abc.Messageable

Paginator

Methods
class discord.ext.commands.Paginator(prefix='```', suffix='```', max_size=2000, linesep='\n')

A class that aids in paginating code blocks for Discord messages.

len(x)

Returns the total number of characters in the paginator.

prefix

The prefix inserted to every page. e.g. three backticks, if any.

Type

Optional[str]

suffix

The suffix appended at the end of every page. e.g. three backticks, if any.

Type

Optional[str]

max_size

The maximum amount of codepoints allowed in a page.

Type

int

linesep
The character string inserted between lines. e.g. a newline character.

New in version 1.7.

Type

str

clear()

Clears the paginator to have no pages.

add_line(line='', *, empty=False)

Adds a line to the current page.

If the line exceeds the max_size then an exception is raised.

Parameters
  • line (str) – The line to add.

  • empty (bool) – Indicates if another empty line should be added.

Raises

RuntimeError – The line was too big for the current max_size.

close_page()

Prematurely terminate a page.

property pages

Returns the rendered list of pages.

Type

List[str]

Enums

class discord.ext.commands.BucketType

Specifies a type of bucket for, e.g. a cooldown.

default

The default bucket operates on a global basis.

user

The user bucket operates on a per-user basis.

guild

The guild bucket operates on a per-guild basis.

channel

The channel bucket operates on a per-channel basis.

member

The member bucket operates on a per-member basis.

category

The category bucket operates on a per-category basis.

role

The role bucket operates on a per-role basis.

New in version 1.3.

Checks

@discord.ext.commands.check(predicate)

A decorator that adds a check to the Command or its subclasses. These checks could be accessed 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!')

Changed in version 2.0: predicate parameter is now positional-only.

Parameters

predicate (Callable[[Context], bool]) – The predicate to check if the command should be invoked.

@discord.ext.commands.check_any(*checks)

A check() that is added that checks if any of the checks passed will pass, i.e. using logical OR.

If all checks fail then CheckAnyFailure is raised to signal the failure. It inherits 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!')
@discord.ext.commands.has_role(item)

A check() that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will 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

Changed in version 2.0: item parameter is now positional-only.

Parameters

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

@discord.ext.commands.has_permissions(**perms)

A check() that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under discord.Permissions.

This check raises a special exception, MissingPermissions that is inherited from CheckFailure.

Parameters

perms – An argument list of permissions to check for.

Example

@bot.command()
@commands.has_permissions(manage_messages=True)
async def test(ctx):
    await ctx.send('You can manage messages.')
@discord.ext.commands.has_guild_permissions(**perms)

Similar to has_permissions(), but operates on guild wide permissions instead of the current channel permissions.

If this check is called in a DM context, it will raise an exception, NoPrivateMessage.

New in version 1.3.

@discord.ext.commands.has_any_role(*items)

A check() that is added that checks if the member invoking the command has any of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.

Similar to has_role(), the names or IDs passed in must be exact.

This check raises one of two special exceptions, MissingAnyRole if the user is missing all roles, 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')
@discord.ext.commands.bot_has_role(item)

Similar to has_role() except checks if the bot itself has the role.

This check raises one of two special exceptions, BotMissingRole if the bot is missing the role, 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

Changed in version 2.0: item parameter is now positional-only.

@discord.ext.commands.bot_has_permissions(**perms)

Similar to has_permissions() except checks if the bot itself has the permissions listed.

This check raises a special exception, BotMissingPermissions that is inherited from CheckFailure.

@discord.ext.commands.bot_has_guild_permissions(**perms)

Similar to has_guild_permissions(), but checks the bot members guild permissions.

New in version 1.3.

@discord.ext.commands.bot_has_any_role(*items)

Similar to has_any_role() except checks if the bot itself has any of the roles listed.

This check raises one of two special exceptions, BotMissingAnyRole if the bot is missing all roles, 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

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)

A decorator that adds a cooldown to a Command

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument 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[[Context], Any]]) –

    The type of cooldown to have. If callable, should return a key for the mapping.

    Changed in version 1.7: Callables are now supported for custom bucket types.

    Changed in version 2.0: When passing a callable, it now needs to accept Context rather than Message as its only argument.

@discord.ext.commands.dynamic_cooldown(cooldown, type)

A decorator that adds a dynamic cooldown to a Command

This differs from cooldown() in that it takes a function that accepts a single parameter of type discord.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[[Context], 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.

@discord.ext.commands.max_concurrency(number, per=discord.ext.commands.BucketType.default, *, wait=False)

A decorator that adds a maximum concurrency to a Command or its subclasses.

This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket – only a set number of people can run the command.

New in version 1.3.

Parameters
  • number (int) – The maximum number of invocations of this command that can be running at the same time.

  • per (BucketType) – The bucket that this concurrency is based on, e.g. BucketType.guild would allow it to be used up 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.

@discord.ext.commands.before_invoke(coro)

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

This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog.

New in version 1.4.

Changed in version 2.0: coro parameter is now positional-only.

Example

async def record_usage(ctx):
    print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at)

@bot.command()
@commands.before_invoke(record_usage)
async def who(ctx): # Output: <User> used who at <Time>
    await ctx.send('i am a bot')

class What(commands.Cog):

    @commands.before_invoke(record_usage)
    @commands.command()
    async def when(self, ctx): # Output: <User> used when at <Time>
        await ctx.send(f'and i have existed since {ctx.bot.user.created_at}')

    @commands.command()
    async def where(self, ctx): # Output: <Nothing>
        await ctx.send('on Discord')

    @commands.command()
    async def why(self, ctx): # Output: <Nothing>
        await ctx.send('because someone made me')
@discord.ext.commands.after_invoke(coro)

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

This allows you to refer to one after invoke hook for several commands that do not have to be within the same cog.

New in version 1.4.

Changed in version 2.0: coro parameter is now positional-only.

@discord.ext.commands.guild_only()

A check() that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

This check raises a special exception, NoPrivateMessage that is inherited from CheckFailure.

@discord.ext.commands.dm_only()

A check() that indicates this command must only be used in a DM context. Only private messages are allowed when using the command.

This check raises a special exception, PrivateMessageOnly that is inherited from CheckFailure.

New in version 1.1.

@discord.ext.commands.is_owner()

A check() that checks if the person invoking this command is the owner of the bot.

This is powered by Bot.is_owner().

This check raises a special exception, NotOwner that is derived from CheckFailure.

@discord.ext.commands.is_nsfw()

A check() that checks if the channel is a NSFW channel.

This check raises a special exception, NSFWChannelRequired that is derived from CheckFailure.

Changed in version 1.1: Raise NSFWChannelRequired instead of generic CheckFailure. DM channels will also now pass this check.

Cooldown

Attributes
class discord.ext.commands.Cooldown(rate, per)

Represents a cooldown for a command.

rate

The total number of tokens available per per seconds.

Type

float

per

The length of the cooldown period in seconds.

Type

float

get_tokens(current=None)

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

Parameters

current (Optional[float]) – The time in seconds since Unix epoch to calculate tokens at. If not supplied 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)

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, *, tokens=1)

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.

  • tokens (int) –

    The amount of tokens to deduct from the rate limit.

    New in version 2.0.

Returns

The retry-after time in seconds if rate limited.

Return type

Optional[float]

reset()

Reset the cooldown to its initial state.

copy()

Creates a copy of this cooldown.

Returns

A new instance of this cooldown.

Return type

Cooldown

Context

class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, subcommand_passed=None, command_failed=False, current_parameter=None, current_argument=None)

Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the Messageable ABC.

message

The message that triggered the command being executed.

Type

Message

bot

The bot that contains the command being executed.

Type

Bot

args

The list of transformed arguments that were passed into the command. If this is accessed during 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[Parameter]

current_argument

The argument string of the current_parameter that is currently being converted. This is only of use for within converters.

New in version 2.0.

Type

Optional[str]

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

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

Type

bool

async with typing()

Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using await.

Example Usage:

async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(20)

await channel.send('Done!')

Example Usage:

await channel.typing()
# Do some computational magic for about 10 seconds
await channel.send('Done!')

Changed in version 2.0: This no longer works with the with syntax, async with must be used instead.

Changed in version 2.0: Added functionality to await the context manager to send a typing indicator for 10 seconds.

async for ... in slash_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)

Returns a asynchronous iterator of the slash commands available in the channel.

Deprecated since version 2.1.

Examples

Usage

async for command in channel.slash_commands():
    print(command.name)

Flattening into a list

commands = [command async for command in channel.slash_commands()]
# commands is now a list of SlashCommand...

All parameters are optional.

Parameters
  • query (Optional[str]) – The query to search for. Specifying this limits results to 25 commands max.

  • limit (Optional[int]) – The maximum number of commands to send back. If None, returns all commands.

  • command_ids (Optional[List[int]]) –

    List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.

    If limit is passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up to limit more, if available.

  • application (Optional[Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.

  • with_applications (bool) – Whether to include applications in the response.

Raises
  • TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.

  • ValueError – The limit was not greater than or equal to 0. Could not resolve the channel’s guild ID.

  • HTTPException – Getting the commands failed.

  • Forbidden – You do not have permissions to get the commands.

  • HTTPException – The request to get the commands failed.

Yields

SlashCommand – A slash command.

async for ... in user_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)

Returns a asynchronous iterator of the user commands available to use on the user.

Deprecated since version 2.1.

Examples

Usage

async for command in user.user_commands():
    print(command.name)

Flattening into a list

commands = [command async for command in user.user_commands()]
# commands is now a list of UserCommand...

All parameters are optional.

Parameters
  • query (Optional[str]) – The query to search for. Specifying this limits results to 25 commands max.

  • limit (Optional[int]) – The maximum number of commands to send back. If None, returns all commands.

  • command_ids (Optional[List[int]]) –

    List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.

    If limit is passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up to limit more, if available.

  • application (Optional[Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.

  • with_applications (bool) – Whether to include applications in the response.

Raises
  • TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.

  • ValueError – The limit was not greater than or equal to 0. Could not resolve the channel’s guild ID.

  • HTTPException – Getting the commands failed.

  • Forbidden – You do not have permissions to get the commands.

  • HTTPException – The request to get the commands failed.

Yields

UserCommand – A user command.

async for ... in message_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)

Returns a asynchronous iterator of the message commands available to use on the message.

Deprecated since version 2.1.

Examples

Usage

async for command in message.message_commands():
    print(command.name)

Flattening into a list

commands = [command async for command in message.message_commands()]
# commands is now a list of MessageCommand...

All parameters are optional.

Parameters
  • query (Optional[str]) – The query to search for. Specifying this limits results to 25 commands max.

  • limit (Optional[int]) – The maximum number of commands to send back. If None, returns all commands.

  • command_ids (Optional[List[int]]) –

    List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.

    If limit is passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up to limit more, if available.

  • application (Optional[Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.

  • with_applications (bool) – Whether to include applications in the response.

Raises
  • TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.

  • ValueError – The limit was not greater than or equal to 0.

  • HTTPException – Getting the commands failed.

  • Forbidden – You do not have permissions to get the commands.

  • HTTPException – The request to get the commands failed.

Yields

MessageCommand – A message command.

await invoke(command, /, *args, **kwargs)

This function is a coroutine.

Calls a command with the arguments given.

This is useful if you want to just call the callback that a Command holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function.

Changed in version 2.0: command parameter is now positional-only.

Parameters
  • command (Command) – The command that is going to be called.

  • *args – The arguments to use.

  • **kwargs – The keyword arguments to use.

Raises

TypeError – The command argument to invoke is missing.

await reinvoke(*, call_hooks=False, restart=True)

This function is a coroutine.

Calls the command again.

This is similar to invoke() except that it bypasses checks, cooldowns, and error handlers.

Note

If you want to bypass UserInputError derived exceptions, it is recommended to use the 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

Checks if the invocation context is valid to be invoked with.

Type

bool

property clean_prefix

The cleaned up invoke prefix. i.e. mentions are @name instead of <@id>.

New in version 2.0.

Type

str

property cog

Returns the cog associated with this context’s command. None if it does not exist.

Type

Optional[Cog]

property filesize_limit

Returns the maximum number of bytes files can have when uploaded to this guild or DM channel associated with this context.

New in version 2.1.

Type

int

guild

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

Type

Optional[Guild]

channel

Returns the channel associated with this context’s command. Shorthand for Message.channel.

Type

Union[abc.Messageable]

author

Union[User, Member]: Returns the author associated with this context’s command. Shorthand for Message.author

me

Union[Member, ClientUser]: Similar to Guild.me except it may return the ClientUser in private message contexts.

property voice_client

A shortcut to Guild.voice_client, if applicable.

Type

Optional[VoiceProtocol]

await send_help(entity=<bot>)

This function is a coroutine.

Shows the help command for the specified entity if given. The entity can be a command or a cog.

If no entity is given, then it’ll show help for the entire bot.

If the entity is a string, then it looks up whether it’s a Cog or 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 ack()

This function is a coroutine.

Marks every message in this channel as read.

New in version 1.9.

Raises

HTTPException – Acking the channel failed.

await ack_pins()

This function is a coroutine.

Marks a channel’s pins as viewed.

New in version 1.9.

Raises

HTTPException – Acking the pinned messages failed.

await application_commands()

This function is a coroutine.

Returns a list of application commands available in the channel.

New in version 2.1.

Note

Commands that the user does not have permission to use will not be returned.

Raises
  • TypeError – Attempted to fetch commands in a DM with a non-bot user.

  • ValueError – Could not resolve the channel’s guild ID.

  • HTTPException – Getting the commands failed.

Returns

A list of application commands.

Return type

List[Union[SlashCommand, UserCommand, MessageCommand]]

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

Parameters

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

Raises
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

Returns

The message asked for.

Return type

Message

await greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...)

This function is a coroutine.

Sends a sticker greeting to the destination.

A sticker greeting is used to begin a new DM or reply to a system message.

New in version 2.0.

Parameters
  • sticker (Union[GuildSticker, StickerItem]) – The sticker to greet with.

  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead. In the case of greeting, only replied_user is considered.

  • reference (Union[Message, MessageReference, PartialMessage]) – A reference to the Message to which you are replying, this can be created using to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the replied_user attribute of allowed_mentions or by setting mention_author.

  • mention_author (bool) – If set, overrides the replied_user attribute of allowed_mentions.

Raises
Returns

The sticker greeting that was sent.

Return type

Message

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)

Returns an asynchronous iterator that enables receiving the destination’s message history.

You must have read_message_history to do this.

Examples

Usage

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = [message async for message in channel.history(limit=123)]
# messages is now a list of Message...

All parameters are optional.

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

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

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

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

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

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

  • HTTPException – The request to get message history failed.

Yields

Message – The message with the message data parsed.

await pins()

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

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

Raises
  • Forbidden – You do not have the permission to retrieve pinned messages.

  • HTTPException – Retrieving the pinned messages failed.

Returns

The messages that are currently pinned.

Return type

List[Message]

search(content=..., *, limit=25, offset=0, before=..., after=..., authors=..., author_types=..., mentions=..., mention_everyone=..., pinned=..., has=..., embed_types=..., embed_providers=..., link_hostnames=..., attachment_filenames=..., attachment_extensions=..., application_commands=..., oldest_first=False, most_relevant=False)

Returns an asynchronous iterator that enables searching the channel’s messages.

You must have read_message_history to do this.

Note

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

New in version 2.1.

Examples

Usage

counter = 0
async for message in channel.search('hi', limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = [message async for message in channel.search('test', limit=123)]
# messages is now a list of Message...

All parameters are optional.

Parameters
  • content (str) – The message content to search for.

  • limit (Optional[int]) – The number of messages to retrieve. If None, retrieves every message in the results. Note, however, that this would make it a slow operation. Additionally, note that the search API has a maximum pagination offset of 5000 (subject to change), so a limit of over 5000 or None may eventually raise an exception.

  • offset (int) – The pagination offset to start at.

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

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

  • authors (List[User]) – The authors to filter by.

  • author_types (List[str]) – The author types to filter by. Can be one of user, bot, or webhook. These can be negated by prefixing with -, which will exclude them.

  • mentions (List[User]) – The mentioned users to filter by.

  • mention_everyone (bool) – Whether to filter by messages that do or do not mention @everyone.

  • pinned (bool) – Whether to filter by messages that are or are not pinned.

  • has (List[str]) – The message attributes to filter by. Can be one of image, sound, video, file, sticker, embed, or link. These can be negated by prefixing with -, which will exclude them.

  • embed_types (List[str]) – The embed types to filter by.

  • embed_providers (List[str]) – The embed providers to filter by (e.g. tenor).

  • link_hostnames (List[str]) – The link hostnames to filter by (e.g. google.com).

  • attachment_filenames (List[str]) – The attachment filenames to filter by.

  • attachment_extensions (List[str]) – The attachment extensions to filter by (e.g. txt).

  • application_commands (List[ApplicationCommand]) – The used application commands to filter by.

  • oldest_first (bool) – Whether to return the oldest results first.

  • most_relevant (bool) – Whether to sort the results by relevance. Using this with oldest_first will return the least relevant results first.

Raises
  • Forbidden – You do not have permissions to search the channel’s messages.

  • HTTPException – The request to search messages failed.

  • ValueError – Could not resolve the channel’s guild ID.

Yields

Message – The message with the message data parsed.

await send(content=None, *, tts=False, file=None, files=None, stickers=None, delete_after=None, nonce=..., allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, silent=False)

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content). If the content is set to None (the default), then a sticker or file must be sent.

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.

Changed in version 2.0: This function will now raise TypeError or ValueError instead of InvalidArgument.

Parameters
  • content (Optional[str]) – The content of the message to send.

  • tts (bool) – Indicates if the message should be sent using text-to-speech.

  • file (Union[File, CloudFile]) – The file to upload.

  • files (List[Union[File, CloudFile]]) – A list of files to upload. Must be a maximum of 10.

  • nonce (int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. Generates one by default.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by 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 to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the replied_user attribute of allowed_mentions or by setting mention_author.

    New in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    New in version 1.6.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    New in version 2.0.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This sends the message without any embeds if set to True.

    New in version 2.0.

  • silent (bool) –

    Whether to suppress push and desktop notifications for the message. This will increment the mention counter in the UI, but will not actually send a notification.

    New in version 2.0.

Raises
Returns

The message that was sent.

Return type

Message

await unack(*, mention_count=None)

This function is a coroutine.

Marks every message in this channel as unread. This manually sets the read state to a message ID of 0.

New in version 2.1.

Parameters

mention_count (Optional[int]) – The mention count to set the channel read state to.

Raises

HTTPException – Unacking the channel failed.

await upload_files(*files)

This function is a coroutine.

Pre-uploads files to Discord’s GCP bucket for use with send().

This method is useful if you have local files that you want to upload and reuse multiple times.

New in version 2.1.

Parameters

*files (File) – A list of files to upload. Must be a maximum of 10.

Raises
  • HTTPException – Uploading the files failed.

  • Forbidden – You do not have the proper permissions to upload files.

Returns

The files that were uploaded. These can be used in lieu of normal Files in send().

Return type

List[CloudFile]

await reply(content=None, **kwargs)

This function is a coroutine.

A shortcut method to abc.Messageable.send() to reply to the Message.

New in version 1.6.

Changed in version 2.0: This function will now raise TypeError or ValueError instead of InvalidArgument.

Raises
  • HTTPException – Sending the message failed.

  • Forbidden – You do not have the proper permissions to send the message.

  • ValueError – The files list is not of the appropriate size

  • TypeError – You specified both file and files.

Returns

The message that was sent.

Return type

Message

Converters

Methods
class discord.ext.commands.Converter(*args, **kwargs)

The base class of custom converters that require the Context to be passed to be useful.

This allows you to implement converters that function similar to the special cased discord classes.

Classes that derive from this should override the convert() method to do its conversion logic. This method must be a coroutine.

await convert(ctx, argument)

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.ObjectConverter(*args, **kwargs)

Converts to a Object.

The argument must follow the valid ID or mention formats (e.g. <@80088516616269824>).

New in version 2.0.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by member, role, or channel mention.

await convert(ctx, argument)

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.MemberConverter(*args, **kwargs)

Converts to a Member.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by username#discriminator (deprecated).

  4. Lookup by username#0 (deprecated, only gets users that migrated from their discriminator).

  5. Lookup by user name.

  6. Lookup by global name.

  7. Lookup by guild 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.

Deprecated since version 2.1: Looking up users by discriminator will be removed in a future version due to the removal of discriminators in an API change.

await convert(ctx, argument)

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.UserConverter(*args, **kwargs)

Converts to a User.

All lookups are via the global user cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by username#discriminator (deprecated).

  4. Lookup by username#0 (deprecated, only gets users that migrated from their discriminator).

  5. Lookup by user name.

  6. Lookup by global 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.

Deprecated since version 2.1: Looking up users by discriminator will be removed in a future version due to the removal of discriminators in an API change.

await convert(ctx, argument)

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.MessageConverter(*args, **kwargs)

Converts to a discord.Message.

New in version 1.1.

The lookup strategy is as follows (in order):

  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)

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
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.PartialMessageConverter(*args, **kwargs)

Converts to a discord.PartialMessage.

New in version 1.7.

The creation strategy is as follows (in order):

  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)

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
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.GuildChannelConverter(*args, **kwargs)

Converts to a GuildChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name.

New in version 2.0.

await convert(ctx, argument)

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.TextChannelConverter(*args, **kwargs)

Converts to a TextChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  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)

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
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.VoiceChannelConverter(*args, **kwargs)

Converts to a VoiceChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  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)

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
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.StageChannelConverter(*args, **kwargs)

Converts to a StageChannel.

New in version 1.7.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

await convert(ctx, argument)

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.CategoryChannelConverter(*args, **kwargs)

Converts to a CategoryChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  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)

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
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.ForumChannelConverter(*args, **kwargs)

Converts to a ForumChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

New in version 2.0.

await convert(ctx, argument)

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.InviteConverter(*args, **kwargs)

Converts to a Invite.

This is done via an HTTP request using Bot.fetch_invite().

Changed in version 1.5: Raise BadInviteArgument instead of generic BadArgument

await convert(ctx, argument)

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.GuildConverter(*args, **kwargs)

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)

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
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.RoleConverter(*args, **kwargs)

Converts to a Role.

All lookups are via the local guild. If in a DM context, the converter raises NoPrivateMessage exception.

The lookup strategy is as follows (in order):

  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)

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
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.GameConverter(*args, **kwargs)

Converts to a Game.

await convert(ctx, argument)

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.ColourConverter(*args, **kwargs)

Converts to a Colour.

Changed in version 1.5: Add an alias named ColorConverter

The following formats are accepted:

  • 0x<hex>

  • #<hex>

  • 0x#<hex>

  • rgb(<number>, <number>, <number>)

  • Any of the classmethod 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)

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
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.EmojiConverter(*args, **kwargs)

Converts to a Emoji.

All lookups are done for the local guild first, if available. If that lookup fails, then it checks the client’s global cache.

The lookup strategy is as follows (in order):

  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)

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
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.PartialEmojiConverter(*args, **kwargs)

Converts to a PartialEmoji.

This is done by extracting the animated flag, name and ID from the emoji.

Changed in version 1.5: Raise PartialEmojiConversionFailure instead of generic BadArgument

await convert(ctx, argument)

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.ThreadConverter(*args, **kwargs)

Converts to a Thread.

All lookups are via the local guild.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name.

await convert(ctx, argument)

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.GuildStickerConverter(*args, **kwargs)

Converts to a GuildSticker.

All lookups are done for the local guild first, if available. If that lookup fails, then it checks the client’s global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by name.

New in version 2.0.

await convert(ctx, argument)

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class discord.ext.commands.ScheduledEventConverter(*args, **kwargs)

Converts to a ScheduledEvent.

Lookups are done for the local guild if available. Otherwise, for a DM context, lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by url.

  3. Lookup by name.

New in version 2.0.

await convert(ctx, argument)

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class discord.ext.commands.clean_content(*, fix_channel_mentions=False, use_nicknames=True, escape_markdown=False, remove_markdown=False)

Converts the argument to mention scrubbed version of said content.

This behaves similarly to clean_content.

fix_channel_mentions

Whether to clean channel mentions.

Type

bool

use_nicknames

Whether to use nicknames when transforming mentions.

Type

bool

escape_markdown

Whether to also escape special markdown characters.

Type

bool

remove_markdown

Whether to also remove special markdown characters. This option is not supported with escape_markdown

New in version 1.7.

Type

bool

await convert(ctx, argument)

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

class discord.ext.commands.Greedy

A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.

When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.

For example, in the following code:

@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
    await ctx.send("numbers: {}, reason: {}".format(numbers, reason))

An invocation of [p]test 1 2 3 4 5 6 hello would pass numbers with [1, 2, 3, 4, 5, 6] and reason with hello.

For more information, check Special Converters.

class discord.ext.commands.Range

A special converter that can be applied to a parameter to require a numeric or string type to fit within the range provided.

During type checking time this is equivalent to typing.Annotated so type checkers understand the intent of the code.

Some example ranges:

  • Range[int, 10] means the minimum is 10 with no maximum.

  • Range[int, None, 10] means the maximum is 10 with no minimum.

  • Range[int, 1, 10] means the minimum is 1 and the maximum is 10.

  • Range[float, 1.0, 5.0] means the minimum is 1.0 and the maximum is 5.0.

  • Range[str, 1, 10] means the minimum length is 1 and the maximum length is 10.

If the value cannot be converted to the provided type or is outside the given range, BadArgument or RangeError is raised to the appropriate error handlers respectively.

New in version 2.0.

Examples

@bot.command()
async def range(ctx: commands.Context, value: commands.Range[int, 10, 12]):
    await ctx.send(f'Your value is {value}')
await discord.ext.commands.run_converters(ctx, converter, argument, param)

This function is a coroutine.

Runs converters for a given converter, argument, and parameter.

This function does the same work that the library does under the hood.

New in version 2.0.

Parameters
  • ctx (Context) – The invocation context to run the converters under.

  • converter (Any) – The converter to run, this corresponds to the annotation in the function.

  • argument (str) – The argument to convert to.

  • param (Parameter) – The parameter being converted. This is mainly for error reporting.

Raises

CommandError – The converter failed to convert.

Returns

The resulting conversion.

Return type

Any

Flag Converter

class discord.ext.commands.FlagConverter

A converter that allows for a user-friendly flag syntax.

The flags are defined using PEP 526 type annotations similar to 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()

Dict[str, Flag]: A mapping of flag name to flag object this converter has.

classmethod await convert(ctx, argument)

This function is a coroutine.

The method that actually converters an argument to the flag mapping.

Parameters
  • ctx (Context) – The invocation context.

  • argument (str) – The argument to convert from.

Raises

FlagError – A flag related parsing error.

Returns

The flag converter instance with all flags parsed.

Return type

FlagConverter

class discord.ext.commands.Flag

Represents a flag parameter for FlagConverter.

The flag() function helps create these flag objects, but it is not necessary to do so. These cannot be constructed manually.

name

The name of the flag.

Type

str

aliases

The aliases of the flag name.

Type

List[str]

attribute

The attribute in the class that corresponds to this flag.

Type

str

default

The default value of the flag, if available.

Type

Any

annotation

The underlying evaluated annotation of the flag.

Type

Any

max_args

The maximum number of arguments the flag can accept. A negative value indicates an unlimited amount of arguments.

Type

int

override

Whether multiple given values overrides the previous value.

Type

bool

property required

Whether the flag is required.

A required flag has no default value.

Type

bool

discord.ext.commands.flag(*, name=..., aliases=..., default=..., max_args=..., override=..., converter=...)

Override default functionality and parameters of the underlying FlagConverter class attributes.

Parameters
  • name (str) – The flag name. If not given, defaults to the attribute name.

  • aliases (List[str]) – Aliases to the flag name. If not given no aliases are set.

  • default (Any) – The default parameter. This could be either a value or a callable that takes Context as its sole parameter. If not given then it defaults to the default value given to the attribute.

  • max_args (int) – The maximum number of arguments the flag can accept. A negative value indicates an unlimited amount of arguments. The default value depends on the annotation given.

  • override (bool) – Whether multiple given values overrides the previous value. The default value depends on the annotation given.

  • converter (Any) – The converter to use for this flag. This replaces the annotation at runtime which is transparent to type checkers.

Defaults

class discord.ext.commands.Parameter

A class that stores information on a Command's parameter.

This is a subclass of inspect.Parameter.

New in version 2.0.

replace(*, name=..., kind=..., default=..., annotation=..., description=..., displayed_default=..., displayed_name=...)

Creates a customized copy of the Parameter.

property name

The parameter’s name.

property kind

The parameter’s kind.

property default

The parameter’s default.

property annotation

The parameter’s annotation.

property required

Whether this parameter is required.

Type

bool

property converter

The converter that should be used for this parameter.

property description

The description of this parameter.

Type

Optional[str]

property displayed_default

The displayed default in Command.signature.

Type

Optional[str]

property displayed_name

The name that is displayed to the user.

New in version 2.3.

Type

Optional[str]

await get_default(ctx)

This function is a coroutine.

Gets this parameter’s default value.

Parameters

ctx (Context) – The invocation context that is used to get the default argument.

discord.ext.commands.parameter(\*, converter=..., default=..., description=..., displayed_default=..., displayed_name=...)

A way to assign custom metadata for a Command's parameter.

New in version 2.0.

Examples

A custom default can be used to have late binding behaviour.

@bot.command()
async def wave(ctx, to: discord.User = commands.parameter(default=lambda ctx: ctx.author)):
    await ctx.send(f'Hello {to.mention} :wave:')
Parameters
  • converter (Any) – The converter to use for this parameter, this replaces the annotation at runtime which is transparent to type checkers.

  • default (Any) – The default value for the parameter, if this is a callable or a coroutine it is called with a positional Context argument.

  • description (str) – The description of this parameter.

  • displayed_default (str) – The displayed default in Command.signature.

  • displayed_name (str) –

    The name that is displayed to the user.

    New in version 2.3.

discord.ext.commands.param(*, converter, default, description, displayed_default, displayed_name)

param(*, converter=…, default=…, description=…, displayed_default=…, displayed_name=…)

An alias for parameter().

New in version 2.0.

discord.ext.commands.Author

A default Parameter which returns the author for this context.

New in version 2.0.

discord.ext.commands.CurrentChannel

A default Parameter which returns the channel for this context.

New in version 2.0.

discord.ext.commands.CurrentGuild

A default Parameter which returns the guild for this context. This will never be None. If the command is called in a DM context then NoPrivateMessage is raised to the error handlers.

New in version 2.0.

Exceptions

exception discord.ext.commands.CommandError(message=None, *args)

The base exception type for all command related errors.

This inherits from discord.DiscordException.

This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from Bot, on_command_error().

exception discord.ext.commands.ConversionError(converter, original)

Exception raised when a Converter class raises non-CommandError.

This inherits from CommandError.

converter

The converter that failed.

Type

discord.ext.commands.Converter

original

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

Type

Exception

exception discord.ext.commands.MissingRequiredArgument(param)

Exception raised when parsing a command and a parameter that is required is not encountered.

This inherits from UserInputError

param

The argument that is missing.

Type

Parameter

exception discord.ext.commands.MissingRequiredAttachment(param)

Exception raised when parsing a command and a parameter that requires an attachment is not given.

This inherits from UserInputError

New in version 2.0.

param

The argument that is missing an attachment.

Type

Parameter

exception discord.ext.commands.ArgumentParsingError(message=None, *args)

An exception raised when the parser fails to parse a user’s input.

This inherits from UserInputError.

There are child classes that implement more granular parsing errors for i18n purposes.

exception discord.ext.commands.UnexpectedQuoteError(quote)

An exception raised when the parser encounters a quote mark inside a non-quoted string.

This inherits from ArgumentParsingError.

quote

The quote mark that was found inside the non-quoted string.

Type

str

exception discord.ext.commands.InvalidEndOfQuotedStringError(char)

An exception raised when a space is expected after the closing quote in a string but a different character is found.

This inherits from ArgumentParsingError.

char

The character found instead of the expected string.

Type

str

exception discord.ext.commands.ExpectedClosingQuoteError(close_quote)

An exception raised when a quote character is expected but not found.

This inherits from ArgumentParsingError.

close_quote

The quote character expected.

Type

str

exception discord.ext.commands.BadArgument(message=None, *args)

Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command.

This inherits from UserInputError

exception discord.ext.commands.BadUnionArgument(param, converters, errors)

Exception raised when a typing.Union converter fails for all its associated types.

This inherits from UserInputError

param

The parameter that failed being converted.

Type

inspect.Parameter

converters

A tuple of converters attempted in conversion, in order of failure.

Type

Tuple[Type, ...]

errors

A list of errors that were caught from failing the conversion.

Type

List[CommandError]

exception discord.ext.commands.BadLiteralArgument(param, literals, errors, argument='')

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]

argument

The argument’s value that failed to be converted. Defaults to an empty string.

New in version 2.0.

Type

str

exception discord.ext.commands.PrivateMessageOnly(message=None)

Exception raised when an operation does not work outside of private message contexts.

This inherits from CheckFailure

exception discord.ext.commands.NoPrivateMessage(message=None)

Exception raised when an operation does not work in private message contexts.

This inherits from CheckFailure

exception discord.ext.commands.CheckFailure(message=None, *args)

Exception raised when the predicates in Command.checks have failed.

This inherits from CommandError

exception discord.ext.commands.CheckAnyFailure(checks, errors)

Exception raised when all predicates in check_any() fail.

This inherits from CheckFailure.

New in version 1.3.

errors

A list of errors that were caught during execution.

Type

List[CheckFailure]

checks

A list of check predicates that failed.

Type

List[Callable[[Context], bool]]

exception discord.ext.commands.CommandNotFound(message=None, *args)

Exception raised when a command is attempted to be invoked but no command under that name is found.

This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.

This inherits from CommandError.

exception discord.ext.commands.DisabledCommand(message=None, *args)

Exception raised when the command being invoked is disabled.

This inherits from CommandError

exception discord.ext.commands.CommandInvokeError(e)

Exception raised when the command being invoked raised an exception.

This inherits from CommandError

original

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

Type

Exception

exception discord.ext.commands.TooManyArguments(message=None, *args)

Exception raised when the command was passed too many arguments and its Command.ignore_extra attribute was not set to True.

This inherits from UserInputError

exception discord.ext.commands.UserInputError(message=None, *args)

The base exception type for errors that involve errors regarding user input.

This inherits from CommandError.

exception discord.ext.commands.CommandOnCooldown(cooldown, retry_after, type)

Exception raised when the command being invoked is on cooldown.

This inherits from CommandError

cooldown

A class with attributes rate 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 discord.ext.commands.MaxConcurrencyReached(number, per)

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

This inherits from CommandError.

number

The maximum number of concurrent invokers allowed.

Type

int

per

The bucket type passed to the max_concurrency() decorator.

Type

BucketType

exception discord.ext.commands.NotOwner(message=None, *args)

Exception raised when the message author is not the owner of the bot.

This inherits from CheckFailure

exception discord.ext.commands.MessageNotFound(argument)

Exception raised when the message provided was not found in the channel.

This inherits from BadArgument

New in version 1.5.

argument

The message supplied by the caller that was not found

Type

str

exception discord.ext.commands.MemberNotFound(argument)

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

This inherits from BadArgument

New in version 1.5.

argument

The member supplied by the caller that was not found

Type

str

exception discord.ext.commands.GuildNotFound(argument)

Exception raised when the guild provided was not found in the bot’s cache.

This inherits from BadArgument

New in version 1.7.

argument

The guild supplied by the called that was not found

Type

str

exception discord.ext.commands.UserNotFound(argument)

Exception raised when the user provided was not found in the bot’s cache.

This inherits from BadArgument

New in version 1.5.

argument

The user supplied by the caller that was not found

Type

str

exception discord.ext.commands.ChannelNotFound(argument)

Exception raised when the bot can not find the channel.

This inherits from BadArgument

New in version 1.5.

argument

The channel supplied by the caller that was not found

Type

Union[int, str]

exception discord.ext.commands.ChannelNotReadable(argument)

Exception raised when the bot does not have permission to read messages in the channel.

This inherits from BadArgument

New in version 1.5.

argument

The channel supplied by the caller that was not readable

Type

Union[abc.GuildChannel, Thread]

exception discord.ext.commands.ThreadNotFound(argument)

Exception raised when the bot can not find the thread.

This inherits from BadArgument

New in version 2.0.

argument

The thread supplied by the caller that was not found

Type

str

exception discord.ext.commands.BadColourArgument(argument)

Exception raised when the colour is not valid.

This inherits from BadArgument

New in version 1.5.

argument

The colour supplied by the caller that was not valid

Type

str

exception discord.ext.commands.RoleNotFound(argument)

Exception raised when the bot can not find the role.

This inherits from BadArgument

New in version 1.5.

argument

The role supplied by the caller that was not found

Type

str

exception discord.ext.commands.BadInviteArgument(argument)

Exception raised when the invite is invalid or expired.

This inherits from BadArgument

New in version 1.5.

argument

The invite supplied by the caller that was not valid

Type

str

exception discord.ext.commands.EmojiNotFound(argument)

Exception raised when the bot can not find the emoji.

This inherits from BadArgument

New in version 1.5.

argument

The emoji supplied by the caller that was not found

Type

str

exception discord.ext.commands.PartialEmojiConversionFailure(argument)

Exception raised when the emoji provided does not match the correct format.

This inherits from BadArgument

New in version 1.5.

argument

The emoji supplied by the caller that did not match the regex

Type

str

exception discord.ext.commands.GuildStickerNotFound(argument)

Exception raised when the bot can not find the sticker.

This inherits from BadArgument

New in version 2.0.

argument

The sticker supplied by the caller that was not found

Type

str

exception discord.ext.commands.ScheduledEventNotFound(argument)

Exception raised when the bot can not find the scheduled event.

This inherits from BadArgument

New in version 2.0.

argument

The event supplied by the caller that was not found

Type

str

exception discord.ext.commands.BadBoolArgument(argument)

Exception raised when a boolean argument was not convertable.

This inherits from BadArgument

New in version 1.5.

argument

The boolean argument supplied by the caller that is not in the predefined list

Type

str

exception discord.ext.commands.RangeError(value, minimum, maximum)

Exception raised when an argument is out of range.

This inherits from BadArgument

New in version 2.0.

minimum

The minimum value expected or None if there wasn’t one

Type

Optional[Union[int, float]]

maximum

The maximum value expected or None if there wasn’t one

Type

Optional[Union[int, float]]

value

The value that was out of range.

Type

Union[int, float, str]

exception discord.ext.commands.MissingPermissions(missing_permissions, *args)

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

This inherits from CheckFailure

missing_permissions

The required permissions that are missing.

Type

List[str]

exception discord.ext.commands.BotMissingPermissions(missing_permissions, *args)

Exception raised when the bot’s member lacks permissions to run a command.

This inherits from CheckFailure

missing_permissions

The required permissions that are missing.

Type

List[str]

exception discord.ext.commands.MissingRole(missing_role)

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

This inherits from CheckFailure

New in version 1.1.

missing_role

The required role that is missing. This is the parameter passed to has_role().

Type

Union[str, int]

exception discord.ext.commands.BotMissingRole(missing_role)

Exception raised when the bot’s member lacks a role to run a command.

This inherits from CheckFailure

New in version 1.1.

missing_role

The required role that is missing. This is the parameter passed to has_role().

Type

Union[str, int]

exception discord.ext.commands.MissingAnyRole(missing_roles)

Exception raised when the command invoker lacks any of the roles specified to run a command.

This inherits from CheckFailure

New in version 1.1.

missing_roles

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

Type

List[Union[str, int]]

exception discord.ext.commands.BotMissingAnyRole(missing_roles)

Exception raised when the bot’s member lacks any of the roles specified to run a command.

This inherits from CheckFailure

New in version 1.1.

missing_roles

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

Type

List[Union[str, int]]

exception discord.ext.commands.NSFWChannelRequired(channel)

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

This inherits from CheckFailure.

New in version 1.1.

channel

The channel that does not have NSFW enabled.

Type

Union[abc.GuildChannel, Thread]

exception discord.ext.commands.FlagError(message=None, *args)

The base exception type for all flag parsing related errors.

This inherits from BadArgument.

New in version 2.0.

exception discord.ext.commands.BadFlagArgument(flag, argument, original)

An exception raised when a flag failed to convert a value.

This inherits from FlagError

New in version 2.0.

flag

The flag that failed to convert.

Type

Flag

argument

The argument supplied by the caller that was not able to be converted.

Type

str

original

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

Type

Exception

exception discord.ext.commands.MissingFlagArgument(flag)

An exception raised when a flag did not get a value.

This inherits from FlagError

New in version 2.0.

flag

The flag that did not get a value.

Type

Flag

exception discord.ext.commands.TooManyFlags(flag, values)

An exception raised when a flag has received too many values.

This inherits from FlagError.

New in version 2.0.

flag

The flag that received too many values.

Type

Flag

values

The values that were passed.

Type

List[str]

exception discord.ext.commands.MissingRequiredFlag(flag)

An exception raised when a required flag was not given.

This inherits from FlagError

New in version 2.0.

flag

The required flag that was not found.

Type

Flag

exception discord.ext.commands.ExtensionError(message=None, *args, name)

Base exception for extension related errors.

This inherits from DiscordException.

name

The extension that had an error.

Type

str

exception discord.ext.commands.ExtensionAlreadyLoaded(name)

An exception raised when an extension has already been loaded.

This inherits from ExtensionError

exception discord.ext.commands.ExtensionNotLoaded(name)

An exception raised when an extension was not loaded.

This inherits from ExtensionError

exception discord.ext.commands.NoEntryPointError(name)

An exception raised when an extension does not have a setup entry point function.

This inherits from ExtensionError

exception discord.ext.commands.ExtensionFailed(name, original)

An exception raised when an extension failed to load during execution of the module or setup entry point.

This inherits from ExtensionError

name

The extension that had the error.

Type

str

original

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

Type

Exception

exception discord.ext.commands.ExtensionNotFound(name)

An exception raised when an extension is not found.

This inherits from ExtensionError

Changed in version 1.3: Made the original attribute always None.

name

The extension that had the error.

Type

str

exception discord.ext.commands.CommandRegistrationError(name, *, alias_conflict=False)

An exception raised when the command can’t be added because the name is already taken by a different command.

This inherits from discord.ClientException

New in version 1.4.

name

The command name that had the error.

Type

str

alias_conflict

Whether the name that conflicts is an alias of the command we try to add.

Type

bool

Exception Hierarchy