API Reference

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

Bot

class discord.ext.commands.Bot(command_prefix, formatter=None, description=None, pm_help=False, **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.

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. To avoid confusion empty iterables are not allowed.

Note

When passing multiple prefixes be careful to not pass a prefix that matches a longer prefix occuring 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

bool – 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.

description

str – The content prefixed into the default help message.

self_bot

bool – If True, the bot will only listen to commands invoked by itself rather than ignoring itself. If False (the default) then the bot will ignore itself. This cannot be changed once initialised.

formatter

HelpFormatter – The formatter used to format the help message. By default, it uses the HelpFormatter. Check it for more info on how to override it. If you want to change the help command completely (add aliases, etc) then a call to remove_command() with ‘help’ as the argument would do the trick.

pm_help

Optional[bool] – A tribool that indicates if the help command should PM 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 PM’d. If False, none of the help output is PM’d. If None, then the bot will only PM when the help message becomes too long (dictated by more than 1000 characters). Defaults to False.

help_attrs

dict – 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. Note that pass_context will always be set to True regardless of what you pass in.

command_not_found

str – The format string used when the help command is invoked with a command that is not found. Useful for i18n. Defaults to "No command called {} found.". The only format argument is the name of the command passed.

command_has_no_subcommands

str – The format string used when the help command is invoked with requests for a subcommand but the command does not have any subcommands. Defaults to "Command {0.name} has no subcommands.". The first format argument is the Command attempted to get a subcommand and the second is the name.

owner_id

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

activity

Optional[Union[Activity, Game, Streaming]] – The activity being used upon logging in.

add_check(func, *, call_once=False)

Adds a global check to the bot.

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

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

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

add_cog(cog)

Adds a “cog” to the bot.

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

They are meant as a way to organize multiple relevant commands into a singular class that shares some state or no state at all.

The cog can also have a __global_check member function that allows you to define a global check. See check() for more info. If the name is __global_check_once then it’s equivalent to the check_once() decorator.

More information will be documented soon.

Parameters

cog – The cog to register to the bot.

add_command(command)

Adds a Command or its superclasses into the internal list of commands.

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

Parameters

command – The command to add.

Raises
add_listener(func, name=None)

The non decorator alternative to listen().

Parameters
  • func (coroutine) – The extra event to listen to.

  • name (Optional[str]) – The name of the command to use. 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')
after_invoke(coro)

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

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

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

Note

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

Parameters

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

Raises

ClientException – The coroutine is not actually a coroutine.

coroutine application_info()

This function is a coroutine.

Retrieve’s the bot’s application information.

Returns

A namedtuple representing the application info.

Return type

AppInfo

Raises

HTTPException – Retrieving the information failed somehow.

before_invoke(coro)

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

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

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

Note

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

Parameters

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

Raises

ClientException – The coroutine is not actually a coroutine.

coroutine change_presence(*, activity=None, status=None, afk=False)

This function is a coroutine.

Changes the client’s presence.

The activity parameter is a Activity object (not a string) that represents the activity being done currently. This could also be the slimmed down versions, Game and Streaming.

Example:

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

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

  • 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 actually idle and not lying.

Raises

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

check(func)

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 derived from CommandError.

Example

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

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

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

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 derived from CommandError.

Example

@bot.check_once
def whitelist(ctx):
    return ctx.message.author.id in my_whitelist
clear()

Clears the internal state of the bot.

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

command(*args, **kwargs)

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

commands

Set[Command] – A unique set of commands without aliases that are registered.

coroutine connect(*, reconnect=True)

This function is a coroutine.

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

Parameters

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

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

  • ConnectionClosed – The websocket connection has been terminated.

coroutine create_guild(name, region=None, icon=None)

This function is a coroutine.

Creates a Guild.

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

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

  • region (VoiceRegion) – The region for the voice communication server. Defaults to VoiceRegion.us_west.

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

Raises
  • HTTPException – Guild creation failed.

  • InvalidArgument – Invalid icon image format given. Must be PNG or JPG.

Returns

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

Return type

Guild

coroutine delete_invite(invite)

This function is a coroutine.

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

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

Parameters

invite – 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.

emojis

List[Emoji] – The emojis that the connected client has.

event(coro)

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, ClientException is raised.

Example

@client.event
async def on_ready():
    print('Ready!')
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.

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
get_channel(id)

Returns a abc.GuildChannel or abc.PrivateChannel with the following ID.

If not found, returns None.

get_cog(name)

Gets the cog instance requested.

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

Parameters

name (str) – The name of the cog you are requesting.

get_cog_commands(name)

Gets a unique set of the cog’s registered commands without aliases.

If the cog is not found, an empty set is returned.

Parameters

name (str) – The name of the cog whose commands you are requesting.

Returns

A unique set of commands without aliases that belong to the cog.

Return type

Set[Command]

get_command(name)

Get a Command or subclasses from the internal list of commands.

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

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

Parameters

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

Returns

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

Return type

Command or subclass

coroutine get_context(message, *, cls=<class 'discord.ext.commands.context.Context'>)

This function is a coroutine.

Returns the invocation context from the message.

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

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

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 a Emoji with the given ID. If not found, returns None.

get_guild(id)

Returns a Guild with the given ID. If not found, returns None.

coroutine get_invite(url)

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 Object with the names patched in.

Parameters

url (str) – The discord invite ID or URL (must be a discord.gg URL).

Raises
  • NotFound – The invite has expired or is invalid.

  • HTTPException – Getting the invite failed.

Returns

The invite from the URL/ID.

Return type

Invite

coroutine get_prefix(message)

This function is a coroutine.

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

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_user(id)

Returns a User with the given ID. If not found, returns None.

coroutine get_user_info(user_id)

This function is a coroutine.

Retrieves a User based on their ID. This can only be used by bot accounts. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Parameters

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

Returns

The user you requested.

Return type

User

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

  • HTTPException – Fetching the user failed.

coroutine get_user_profile(user_id)

This function is a coroutine.

Gets an arbitrary user’s profile. This can only be used by non-bot accounts.

Parameters

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

Raises
  • Forbidden – Not allowed to fetch profiles.

  • HTTPException – Fetching the profile failed.

Returns

The profile of the user.

Return type

Profile

coroutine get_webhook_info(webhook_id)

This function is a coroutine.

Retrieves a Webhook with the specified ID.

Raises
  • HTTPException – Retrieving the webhook failed.

  • NotFound – Invalid webhook ID.

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

Returns

The webhook you requested.

Return type

Webhook

group(*args, **kwargs)

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

guilds

List[Guild] – The guilds that the connected client is a member of.

coroutine invoke(ctx)

This function is a coroutine.

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

Parameters

ctx (Context) – The invocation context to invoke.

is_closed()

bool: Indicates if the websocket connection is closed.

coroutine is_owner(user)

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

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

Parameters

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

is_ready()

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

latency

float – Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

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

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

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

load_extension(name)

Loads an extension.

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

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

Parameters

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

Raises
  • ClientException – The extension does not have a setup function.

  • ImportError – The extension could not be imported.

coroutine login(token, *, bot=True)

This function is a coroutine.

Logs in the client with the specified credentials.

This function can be used in two different ways.

Warning

Logging on with a user token is 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. Do not prefix this token with anything as the library will do it for you.

  • bot (bool) – Keyword argument that specifies if the account logging on is a bot token or not.

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.

coroutine logout()

This function is a coroutine.

Logs out of Discord and closes all connections.

coroutine on_command_error(context, exception)

This function is a coroutine.

The default command error handler provided by the bot.

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

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

coroutine on_error(event_method, *args, **kwargs)

This function is a coroutine.

The default error handler provided by the client.

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

private_channels

List[abc.PrivateChannel] – The private channels that the connected client is participating on.

Note

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

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

Parameters

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

remove_check(func, *, call_once=False)

Removes a global check from the bot.

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

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

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

remove_cog(name)

Removes a cog from the bot.

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.

If the cog defines a special member function named __unload then it is called when removal has completed. This function cannot be a coroutine. It must be a regular function.

Parameters

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

remove_command(name)

Remove a Command or subclasses from the internal list of commands.

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

Parameters

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

Returns

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

Return type

Command or subclass

remove_listener(func, name=None)

Removes a listener from the pool of listeners.

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

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

coroutine request_offline_members(*guilds)

This function is a coroutine.

Requests previously offline members from the guild to be filled up into the Guild.members cache. This function is usually not called. It should only be used if you have the fetch_offline_members parameter set to False.

When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if Guild.large is True.

Parameters

*guilds – An argument list of guilds to request offline members for.

Raises

InvalidArgument – If any guild is unavailable or not large in the collection.

run(*args, **kwargs)

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

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

Roughly Equivalent to:

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

Warning

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

coroutine start(*args, **kwargs)

This function is a coroutine.

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

unload_extension(name)

Unloads an extension.

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

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

Parameters

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

user

Optional[ClientUser] – Represents the connected client. None if not logged in.

users

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

voice_clients

List[VoiceClient] – Represents a list of voice connections.

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('Hello {.author}!'.format(msg))

Waiting for a thumbs up reaction from the message author:

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

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

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

  • check (Optional[predicate]) – 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

coroutine wait_until_ready()

This function is a coroutine.

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

walk_commands()

An iterator that recursively walks through all commands and subcommands.

class discord.ext.commands.AutoShardedBot(command_prefix, formatter=None, description=None, pm_help=False, **options)

This is similar to Bot except that it is derived from discord.AutoShardedClient instead.

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.

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

Command

discord.ext.commands.command(name=None, cls=None, **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=None, **attrs)

A decorator that transforms a function into a Group.

This is similar to the command() decorator but creates a Group instead of a Command.

class discord.ext.commands.Command(name, callback, **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

str – The name of the command.

callback

coroutine – The coroutine that is executed when the command is called.

help

str – The long help text for the command.

brief

str – The short help text for the command. If this is not specified then the first line of the long help text is used instead.

usage

str – A replacement for arguments in the default help text.

aliases

list – The list of aliases the command can be invoked under.

enabled

bool – 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.

parent

Optional[command] – The parent command that this command belongs to. None if there isn’t one.

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 derived from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_command_error() event.

description

str – The message prefixed into the default help command.

hidden

bool – If True, the default help command does not show this in the help output.

rest_is_raw

bool – 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.

ignore_extra

bool – 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.

clean_params

Retrieves the parameter OrderedDict without the context or self parameters.

Useful for inspecting signature.

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.

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.

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.

is_on_cooldown(ctx)

Checks whether the command is currently on cooldown.

Parameters

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

Returns

A boolean indicating if the command is on cooldown.

Return type

bool

reset_cooldown(ctx)

Resets the cooldown on this command.

Parameters

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

error(coro)

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

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

Parameters

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

Raises

discord.ClientException – The coroutine is not actually a coroutine.

before_invoke(coro)

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

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

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

See Bot.before_invoke() for more info.

Parameters

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

Raises

ClientException – The coroutine is not actually a coroutine.

after_invoke(coro)

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

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

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

See Bot.after_invoke() for more info.

Parameters

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

Raises

ClientException – The coroutine is not actually a coroutine.

cog_name

The name of the cog this command belongs to. None otherwise.

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.

signature

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

coroutine can_run(ctx)

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute.

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

class discord.ext.commands.Group(**attrs)

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

bool – 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.

case_insensitive

bool – Indicates if the group’s commands should be case insensitive. Defaults to False.

add_command(command)

Adds a Command or its superclasses into the internal list of commands.

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

Parameters

command – The command to add.

Raises
after_invoke(coro)

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

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

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

See Bot.after_invoke() for more info.

Parameters

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

Raises

ClientException – The coroutine is not actually a coroutine.

before_invoke(coro)

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

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

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

See Bot.before_invoke() for more info.

Parameters

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

Raises

ClientException – The coroutine is not actually a coroutine.

coroutine can_run(ctx)

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute.

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

clean_params

Retrieves the parameter OrderedDict without the context or self parameters.

Useful for inspecting signature.

cog_name

The name of the cog this command belongs to. None otherwise.

command(*args, **kwargs)

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

commands

Set[Command] – A unique set of commands without aliases that are registered.

error(coro)

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

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

Parameters

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

Raises

discord.ClientException – The coroutine is not actually a coroutine.

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.

get_command(name)

Get a Command or subclasses from the internal list of commands.

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

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

Parameters

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

Returns

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

Return type

Command or subclass

group(*args, **kwargs)

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

is_on_cooldown(ctx)

Checks whether the command is currently on cooldown.

Parameters

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

Returns

A boolean indicating if the command is on cooldown.

Return type

bool

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.

remove_command(name)

Remove a Command or subclasses from the internal list of commands.

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

Parameters

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

Returns

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

Return type

Command or subclass

reset_cooldown(ctx)

Resets the cooldown on this command.

Parameters

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

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.

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.

signature

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

walk_commands()

An iterator that recursively walks through all commands and subcommands.

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

A mixin that implements common functionality for classes that behave similar to Group and are allowed to register commands.

all_commands

dict – A mapping of command name to Command or superclass objects.

case_insensitive

bool – Whether the commands should be case insensitive. Defaults to False.

commands

Set[Command] – A unique set of commands without aliases that are registered.

add_command(command)

Adds a Command or its superclasses into the internal list of commands.

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

Parameters

command – The command to add.

Raises
remove_command(name)

Remove a Command or subclasses from the internal list of commands.

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

Parameters

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

Returns

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

Return type

Command or subclass

walk_commands()

An iterator that recursively walks through all commands and subcommands.

get_command(name)

Get a Command or subclasses from the internal list of commands.

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

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

Parameters

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

Returns

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

Return type

Command or subclass

command(*args, **kwargs)

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

group(*args, **kwargs)

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

Formatters

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

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

prefix

str – The prefix inserted to every page. e.g. three backticks.

suffix

str – The suffix appended at the end of every page. e.g. three backticks.

max_size

int – The maximum amount of codepoints allowed in a page.

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.

pages

Returns the rendered list of pages.

class discord.ext.commands.HelpFormatter(show_hidden=False, show_check_failure=False, width=80)

The default base implementation that handles formatting of the help command.

To override the behaviour of the formatter, format() should be overridden. A number of utility functions are provided for use inside that method.

show_hidden

bool – Dictates if hidden commands should be shown in the output. Defaults to False.

show_check_failure

bool – Dictates if commands that have their Command.checks failed shown. Defaults to False.

width

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

has_subcommands()

bool: Specifies if the command has subcommands.

is_bot()

bool: Specifies if the command being formatted is the bot itself.

is_cog()

bool: Specifies if the command being formatted is actually a cog.

shorten(text)

Shortens text to fit into the width.

max_name_size

int – Returns the largest name length of a command or if it has subcommands the largest subcommand name.

clean_prefix

The cleaned up invoke prefix. i.e. mentions are @name instead of <@id>.

get_command_signature()

Retrieves the signature portion of the help page.

coroutine filter_command_list()

Returns a filtered list of commands based on the two attributes provided, show_check_failure and show_hidden. Also filters based on if is_cog() is valid.

Returns

An iterable with the filter being applied. The resulting value is a (key, value) tuple of the command name and the command itself.

Return type

iterable

coroutine format()

Handles the actual behaviour involved with formatting.

To change the behaviour, this method should be overridden.

Returns

A paginated output of the help command.

Return type

list

coroutine format_help_for(context, command_or_bot)

Formats the help page and handles the actual heavy lifting of how the help command looks like. To change the behaviour, override the format() method.

Parameters
  • context (Context) – The context of the invoked help command.

  • command_or_bot (Command or Bot) – The bot or command that we are getting the help of.

Returns

A paginated output of the help command.

Return type

list

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

Note

These functions can either be regular functions or coroutines.

Parameters

predicate – The predicate to check if the command should be invoked.

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

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 any of the permissions necessary.

The permissions passed in must be exactly like the properties shown under discord.Permissions.

This check raises a special exception, MissingPermissions that is derived 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_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.

Parameters

items – 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.

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 derived from CheckFailure.

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.

discord.ext.commands.cooldown(rate, per, type=<BucketType.default: 0>)

A decorator that adds a cooldown to a Command or its subclasses.

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

  • BucketType.default for a global basis.

  • BucketType.user for a per-user basis.

  • BucketType.guild for a per-guild basis.

  • BucketType.channel for a per-channel basis.

  • BucketType.member for a per-member basis.

  • BucketType.category for a per-category basis.

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 (BucketType) – The type of cooldown to have.

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 derived from CheckFailure.

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.

Context

class discord.ext.commands.Context(**attrs)

Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the abc.Messageable ABC.

message

discord.Message – The message that triggered the command being executed.

bot

Bot – The bot that contains the command being executed.

args

list – 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.

kwargs

dict – 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.

prefix

str – The prefix that was used to invoke the command.

command

The command (i.e. Command or its superclasses) that is being invoked currently.

invoked_with

str – The command name that triggered this invocation. Useful for finding out which alias called the command.

invoked_subcommand

The subcommand (i.e. Command or its superclasses) that was invoked. If no valid subcommand was invoked then this is equal to None.

subcommand_passed

Optional[str] – 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.

command_failed

bool – A boolean that indicates if the command failed to be parsed, checked, or invoked.

async-for history(*, limit=100, before=None, after=None, around=None, reverse=None)

Return an AsyncIterator that enables receiving the destination’s message history.

You must have read_message_history permissions to use this.

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 (Message or datetime) – Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • after (Message or datetime) – Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • around (Message or datetime) – Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC 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.

  • reverse (bool) – If set to true, return messages in oldest->newest order. If unspecified, this defaults to False for most cases. However if passing in a after parameter then this is set to True. This avoids getting messages out of order in the after case.

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.

Examples

Usage

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

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...
async-with typing()

Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

Note

This is both a regular context manager and an async context manager. This means that both with and async with work with this.

Example Usage:

async with channel.typing():
    # do expensive stuff here
    await channel.send('done!')
valid

Checks if the invocation context is valid to be invoked with.

cog

Returns the cog associated with this context’s command. None if it does not exist.

coroutine get_message(id)

This function is a coroutine.

Retrieves a single Message from the destination.

This can only be used by bot accounts.

Parameters

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

Returns

The message asked for.

Return type

Message

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.

coroutine invoke(*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

You do not pass in the context as it is done for you.

Warning

The first parameter passed must be the command being invoked.

Parameters
  • command (Command) – A command or superclass of a command that is going to be called.

  • *args – The arguments to to use.

  • **kwargs – The keyword arguments to use.

coroutine pins()

This function is a coroutine.

Returns a list of Message that are currently pinned.

Raises

HTTPException – Retrieving the pinned messages failed.

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

coroutine send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None)

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content). If the content is set to None (the default), then the embed parameter must be provided.

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

If the embed parameter is provided, it must be of type Embed and it must be a rich embed type.

Parameters
  • content – The content of the message to send.

  • tts (bool) – Indicates if the message should be sent using text-to-speech.

  • embed (Embed) – The rich embed for the content.

  • file (File) – The file to upload.

  • files (List[File]) – A list of files to upload. Must be a maximum of 10.

  • nonce (int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

Raises
  • HTTPException – Sending the message failed.

  • Forbidden – You do not have the proper permissions to send the message.

  • InvalidArgument – The files list is not of the appropriate size or you specified both file and files.

Returns

The message that was sent.

Return type

Message

coroutine trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

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

guild

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

channel

Returns the channel associated with this context’s command. Shorthand for Message.channel.

author

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

me

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

voice_client

Optional[VoiceClient] – A shortcut to Guild.voice_client, if applicable.

Converters

class discord.ext.commands.Converter

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.

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

class discord.ext.commands.MemberConverter

Converts to a Member.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name#discrim

  4. Lookup by name

  5. Lookup by nickname

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

class discord.ext.commands.UserConverter

Converts to a User.

All lookups are via the global user cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name#discrim

  4. Lookup by name

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

class discord.ext.commands.TextChannelConverter

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

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

class discord.ext.commands.VoiceChannelConverter

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

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

class discord.ext.commands.CategoryChannelConverter

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

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

class discord.ext.commands.InviteConverter

Converts to a Invite.

This is done via an HTTP request using Bot.get_invite().

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

class discord.ext.commands.RoleConverter

Converts to a Role.

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

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

class discord.ext.commands.GameConverter

Converts to Game.

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

class discord.ext.commands.ColourConverter

Converts to a Colour.

The following formats are accepted:

  • 0x<hex>

  • #<hex>

  • 0x#<hex>

  • Any of the classmethod in Colour

    • The _ in the name can be optionally replaced with spaces.

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

class discord.ext.commands.EmojiConverter

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

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

class discord.ext.commands.PartialEmojiConverter

Converts to a PartialEmoji.

This is done by extracting the animated flag, name and ID from the emoji.

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

class discord.ext.commands.clean_content(*, fix_channel_mentions=False, use_nicknames=True, escape_markdown=False)

Converts the argument to mention scrubbed version of said content.

This behaves similarly to Message.clean_content.

fix_channel_mentions

bool – Whether to clean channel mentions.

use_nicknames

bool – Whether to use nicknames when transforming mentions.

escape_markdown

bool – Whether to also escape special markdown characters.

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

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.

Errors

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 derived 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

discord.ext.commands.Converter – The converter that failed.

original

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

exception discord.ext.commands.MissingRequiredArgument(param)

Exception raised when parsing a command and a parameter that is required is not encountered.

param

inspect.Parameter – The argument that is missing.

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.

exception discord.ext.commands.BadUnionArgument(param, converters, errors)

Exception raised when a typing.Union converter fails for all its associated types.

param

inspect.Parameter – The parameter that failed being converted.

converters

Tuple[Type, …] – A tuple of converters attempted in conversion, in order of failure.

errors

List[CommandError] – A list of errors that were caught from failing the conversion.

exception discord.ext.commands.NoPrivateMessage(message=None, *args)

Exception raised when an operation does not work in private message contexts.

exception discord.ext.commands.CheckFailure(message=None, *args)

Exception raised when the predicates in Command.checks have failed.

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.

exception discord.ext.commands.DisabledCommand(message=None, *args)

Exception raised when the command being invoked is disabled.

exception discord.ext.commands.CommandInvokeError(e)

Exception raised when the command being invoked raised an exception.

original

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

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.

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)

Exception raised when the command being invoked is on cooldown.

cooldown

Cooldown – A class with attributes rate, per, and type similar to the cooldown() decorator.

retry_after

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

exception discord.ext.commands.NotOwner(message=None, *args)

Exception raised when the message author is not the owner of the bot.

exception discord.ext.commands.MissingPermissions(missing_perms, *args)

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

missing_perms

list – The required permissions that are missing.

exception discord.ext.commands.BotMissingPermissions(missing_perms, *args)

Exception raised when the bot lacks permissions to run command.

missing_perms

list – The required permissions that are missing.