API Reference

The following section outlines the API of Pycord.

Note

This module uses the Python logging module to log diagnostic and errors in an output independent way. If the logging module is not configured, these logs will not be output anywhere. See Setting Up Logging for more information on how to set up and use the logging module with Pycord.

Clients

Client

class discord.Client(*, loop=None, **options)

Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

A number of options can be passed to the Client.

Parameters
  • max_messages (Optional[int]) –

    The maximum number of messages to store in the internal message cache. This defaults to 1000. Passing in None disables the message cache.

    Changed in version 1.3: Allow disabling the message cache and change the default size to 1000.

  • loop (Optional[asyncio.AbstractEventLoop]) – The asyncio.AbstractEventLoop to use for asynchronous operations. Defaults to None, in which case the default event loop is used via asyncio.get_event_loop().

  • connector (Optional[aiohttp.BaseConnector]) – The connector to use for connection pooling.

  • proxy (Optional[str]) – Proxy URL.

  • proxy_auth (Optional[aiohttp.BasicAuth]) – An object that represents proxy HTTP Basic Authorization.

  • shard_id (Optional[int]) – Integer starting at 0 and less than shard_count.

  • shard_count (Optional[int]) – The total number of shards.

  • application_id (int) – The client’s application ID.

  • intents (Intents) –

    The intents that you want to enable for the session. This is a way of disabling and enabling certain gateway events from triggering and being sent. If not given, defaults to a regularly constructed Intents class.

    New in version 1.5.

  • member_cache_flags (MemberCacheFlags) –

    Allows for finer control over how the library caches members. If not given, defaults to cache as much as possible with the currently selected intents.

    New in version 1.5.

  • chunk_guilds_at_startup (bool) –

    Indicates if on_ready() should be delayed to chunk all guilds at start-up if necessary. This operation is incredibly slow for large amounts of guilds. The default is True if Intents.members is True.

    New in version 1.5.

  • status (Optional[Status]) – A status to start your presence with upon logging on to Discord.

  • activity (Optional[BaseActivity]) – An activity to start your presence with upon logging on to Discord.

  • allowed_mentions (Optional[AllowedMentions]) –

    Control how the client handles mentions by default on every message sent.

    New in version 1.4.

  • heartbeat_timeout (float) – The maximum numbers of seconds before timing out and restarting the WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful if processing the initial packets take too long to the point of disconnecting you. The default timeout is 60 seconds.

  • guild_ready_timeout (float) –

    The maximum number of seconds to wait for the GUILD_CREATE stream to end before preparing the member cache and firing READY. The default timeout is 2 seconds.

    New in version 1.4.

  • assume_unsync_clock (bool) –

    Whether to assume the system clock is unsynced. This applies to the ratelimit handling code. If this is set to True, the default, then the library uses the time to reset a rate limit bucket given by Discord. If this is False then your system clock is used to calculate how long to sleep for. If this is set to False it is recommended to sync your system clock to Google’s NTP server.

    New in version 1.3.

  • enable_debug_events (bool) –

    Whether to enable events that are useful only for debugging gateway related information.

    Right now this involves on_socket_raw_receive() and on_socket_raw_send(). If this is False then those events will not be dispatched (due to performance considerations). To enable these events, this must be set to True. Defaults to False.

    New in version 2.0.

ws

The WebSocket gateway the client is currently connected to. Could be None.

loop

The event loop that the client uses for asynchronous operations.

Type

asyncio.AbstractEventLoop

@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!')
Raises

TypeError – The coroutine passed is not actually a coroutine.

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

Retrieves an AsyncIterator that enables receiving your guilds.

Note

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

Note

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

Examples

Usage

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

Flattening into a list

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

All parameters are optional.

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

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

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

Raises

HTTPException – Getting the guilds failed.

Yields

Guild – The guild with the guild data parsed.

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

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.

property user

Represents the connected client. None if not logged in.

Type

Optional[ClientUser]

property guilds

The guilds that the connected client is a member of.

Type

List[Guild]

property emojis

The emojis that the connected client has.

Type

List[Emoji]

property stickers

The stickers that the connected client has.

New in version 2.0.

Type

List[GuildSticker]

property cached_messages

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

New in version 1.1.

Type

Sequence[Message]

property private_channels

The private channels that the connected client is participating on.

Note

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

Type

List[abc.PrivateChannel]

property voice_clients

Represents a list of voice connections.

These are usually VoiceClient instances.

Type

List[VoiceProtocol]

property application_id

The client’s application ID.

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

New in version 2.0.

Type

Optional[int]

property application_flags

The client’s application flags.

New in version 2.0.

Type

ApplicationFlags

is_ready()

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

await 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 on_error() for more details.

await before_identify_hook(shard_id, *, 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 sleeps for 5 seconds.

New in version 1.4.

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

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

await login(token)

This function is a coroutine.

Logs in the client with the specified credentials.

Parameters

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

Raises
  • TypeError – The token was in invalid type.

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

await close()

This function is a coroutine.

Closes the connection to Discord.

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.

await start(token, *, reconnect=True)

This function is a coroutine.

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

Raises

TypeError – An unexpected keyword argument was received.

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(close())
    # cancel all tasks lingering
finally:
    loop.close()

Warning

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

is_closed()

bool: Indicates if the WebSocket connection is closed.

property activity

The activity being used upon logging in.

Type

Optional[BaseActivity]

property status

Status: The status being used upon logging on to Discord.

property allowed_mentions

The allowed mention configuration.

New in version 1.4.

Type

Optional[AllowedMentions]

property intents

The intents configured for this connection.

New in version 1.5.

Type

Intents

property users

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

Type

List[User]

await fetch_application(application_id, /)

This function is a coroutine. Retrieves a PartialAppInfo from an application ID.

Parameters

application_id (int) – The application ID to retrieve information from.

Raises
  • NotFound – An application with this ID does not exist.

  • HTTPException – Retrieving the application failed.

Returns

The application information.

Return type

PartialAppInfo

get_channel(id, /)

Returns a channel or thread with the given ID.

Parameters

id (int) – The ID to search for.

Returns

The returned channel or None if not found.

Return type

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

get_message(id, /)

Returns a message the given ID.

This is useful if you have a message_id but don’t want to do an API call to access the message.

Parameters

id (int) – The ID to search for.

Returns

The returned message or None if not found.

Return type

Optional[Message]

get_partial_messageable(id, *, 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.

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

Returns

The partial messageable

Return type

PartialMessageable

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_guild(id, /)

Returns a guild with the given ID.

Parameters

id (int) – The ID to search for.

Returns

The guild or None if not found.

Return type

Optional[Guild]

get_user(id, /)

Returns a user with the given ID.

Parameters

id (int) – The ID to search for.

Returns

The user or None if not found.

Return type

Optional[User]

get_emoji(id, /)

Returns an emoji with the given ID.

Parameters

id (int) – The ID to search for.

Returns

The custom emoji or None if not found.

Return type

Optional[Emoji]

get_sticker(id, /)

Returns a guild sticker with the given ID.

New in version 2.0.

Note

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

Returns

The sticker or None if not found.

Return type

Optional[GuildSticker]

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.

await get_or_fetch_user(id, /)

Looks up a user in the user cache or fetches if not found.

Parameters

id (int) – The ID to search for.

Returns

The user or None if not found.

Return type

Optional[User]

await wait_until_ready()

This function is a coroutine.

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

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('👍')
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 – Raised if a timeout is provided and 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 change_presence(*, activity=None, status=None)

This function is a coroutine.

Changes the client’s presence.

Example

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

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

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

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

Raises

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

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_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, Guild.members, Member.activity and Member.voice per Member.

Note

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

Parameters
Raises
Returns

The guild from the ID.

Return type

Guild

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

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.

  • 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 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_invite(url, *, with_counts=True, with_expiration=True, 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.

Parameters
Raises
Returns

The invite from the URL/ID.

Return type

Invite

await 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 (Union[Invite, str]) – The invite to revoke.

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

  • NotFound – The invite is invalid or expired.

  • HTTPException – Revoking the invite failed.

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

Parameters

guild_id (int) – The ID of the guild.

Raises
Returns

The guild’s widget.

Return type

Widget

await application_info()

This function is a coroutine.

Retrieves the bot’s application information.

Raises

HTTPException – Retrieving the information failed somehow.

Returns

The bot’s application information.

Return type

AppInfo

await fetch_user(user_id, /)

This function is a coroutine.

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

Note

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

Parameters

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

Raises
Returns

The user you requested.

Return type

User

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.

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_webhook(webhook_id, /)

This function is a coroutine.

Retrieves a Webhook with the specified ID.

Raises
Returns

The webhook you requested.

Return type

Webhook

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

This function is a coroutine.

Retrieves all available premium sticker packs.

New in version 2.0.

Raises

HTTPException – Retrieving the sticker packs failed.

Returns

All available premium sticker packs.

Return type

List[StickerPack]

await 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

add_view(view, *, message_id=None)

Registers a View for persistent listening.

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

New in version 2.0.

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

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

Raises
  • TypeError – A view was not passed.

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

property persistent_views

A sequence of persistent views added to the client.

New in version 2.0.

Type

Sequence[View]

AutoShardedClient

class discord.AutoShardedClient(*args, loop=None, **kwargs)

A client similar to Client except it handles the complications of sharding for the user into a more manageable and transparent single process bot.

When using this client, you will be able to use it as-if it was a regular Client with a single shard when implementation wise internally it is split up into multiple shards. This allows you to not have to deal with IPC or other complicated infrastructure.

It is recommended to use this client only if you have surpassed at least 1000 guilds.

If no shard_count is provided, then the library will use the Bot Gateway endpoint call to figure out how many shards to use.

If a shard_ids parameter is given, then those shard IDs will be used to launch the internal shards. Note that shard_count must be provided if this is used. By default, when omitted, the client will launch shards from 0 to shard_count - 1.

shard_ids

An optional list of shard_ids to launch the shards with.

Type

Optional[List[int]]

property latency

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

This operates similarly to Client.latency() except it uses the average latency of every shard’s latency. To get a list of shard latency, check the latencies property. Returns nan if there are no shards ready.

Type

float

property latencies

A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

This returns a list of tuples with elements (shard_id, latency).

Type

List[Tuple[int, float]]

get_shard(shard_id)

Optional[ShardInfo]: Gets the shard information at a given shard ID or None if not found.

property shards

Returns a mapping of shard IDs to their respective info object.

Type

Mapping[int, ShardInfo]

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 invalid sharding payloads or bad tokens).

Raises
  • GatewayNotFound – 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.

await close()

This function is a coroutine.

Closes the connection to Discord.

await change_presence(*, activity=None, status=None, shard_id=None)

This function is a coroutine.

Changes the client’s presence.

Example:

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

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

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

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

  • shard_id (Optional[int]) – The shard_id to change the presence to. If not specified or None, then it will change the presence of every shard the bot can see.

Raises

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

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.

This implementation checks if any of the shards are rate limited. For more granular control, consider ShardInfo.is_ws_ratelimited().

New in version 1.6.

Bots

Bot

class discord.Bot(description=None, *args, **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 ApplicationCommandMixin to provide the functionality to manage commands.

New in version 2.0.

description

The content prefixed into the default help message.

Type

str

owner_id

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

Type

Optional[int]

owner_ids

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

New in version 1.3.

Type

Optional[Collection[int]]

debug_guilds

Guild IDs of guilds to use for testing commands. The bot will not create any global commands if debug guild IDs are passed.

New in version 2.0.

Type

Optional[List[int]]

auto_sync_commands

Whether to automatically sync slash commands. This will call sync_commands in on_connect, and in process_application_commands if the command is not found. Defaults to True.

New in version 2.0.

Type

bool

@command(**kwargs)

An alias for application_command().

Note

This decorator is overridden by discord.ext.commands.Bot.

New in version 2.0.

Returns

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

Return type

Callable[…, ApplicationCommand]

@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!')
Raises

TypeError – The coroutine passed is not actually a coroutine.

@message_command(**kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list via add_application_command(). This shortcut is made specifically for MessageCommand.

New in version 2.0.

Returns

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

Return type

Callable[…, MessageCommand]

@slash_command(**kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list via add_application_command(). This shortcut is made specifically for SlashCommand.

New in version 2.0.

Returns

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

Return type

Callable[…, SlashCommand]

@user_command(**kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list via add_application_command(). This shortcut is made specifically for UserCommand.

New in version 2.0.

Returns

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

Return type

Callable[…, UserCommand]

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

property activity

The activity being used upon logging in.

Type

Optional[BaseActivity]

add_application_command(command)

Adds a ApplicationCommand into the internal list of commands.

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

New in version 2.0.

Parameters

command (ApplicationCommand) – The command to add.

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 Bot.invoke() call.

add_cog(cog, *, override=False)

Adds a “cog” to the bot.

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

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

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

  • override (bool) –

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

    New in version 2.0.

Raises
add_listener(func, name=...)

The non decorator alternative to listen().

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')
add_view(view, *, message_id=None)

Registers a View for persistent listening.

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

New in version 2.0.

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

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

Raises
  • TypeError – A view was not passed.

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

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 (coroutine) – The coroutine to register as the post-invoke hook.

Raises

TypeError – The coroutine passed is not actually a coroutine.

property allowed_mentions

The allowed mention configuration.

New in version 1.4.

Type

Optional[AllowedMentions]

application_command(**kwargs)

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

New in version 2.0.

Returns

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

Return type

Callable[…, ApplicationCommand]

property application_flags

The client’s application flags.

New in version 2.0.

Type

ApplicationFlags

property application_id

The client’s application ID.

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

New in version 2.0.

Type

Optional[int]

await application_info()

This function is a coroutine.

Retrieves the bot’s application information.

Raises

HTTPException – Retrieving the information failed somehow.

Returns

The bot’s application information.

Return type

AppInfo

await before_identify_hook(shard_id, *, initial=False)

This function is a coroutine.

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

The default implementation sleeps for 5 seconds.

New in version 1.4.

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

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

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 (coroutine) – The coroutine to register as the pre-invoke hook.

Raises

TypeError – The coroutine passed is not actually a coroutine.

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=None, status=None)

This function is a coroutine.

Changes the client’s presence.

Example

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

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

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

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

Raises

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 inherited from ApplicationCommandError.

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

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.

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]

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 invalid sharding payloads or bad tokens).

Raises
  • GatewayNotFound – 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.

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

create_group(name, description=None, guild_ids=None, **kwargs)

A shortcut method that creates a slash command group with no subcommands and adds it to the internal command list via add_application_command().

New in version 2.0.

Parameters
  • name (str) – The name of the group to create.

  • description (Optional[str]) – The description of the group to create.

  • guild_ids (Optional[List[int]]) – A list of the IDs of each guild this group should be added to, making it a guild command. This will be a global command if None is passed.

  • kwargs – Any additional keyword arguments to pass to SlashCommandGroup.

Returns

The slash command group that was created.

Return type

SlashCommandGroup

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

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.

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

property emojis

The emojis that the connected client has.

Type

List[Emoji]

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 a PartialAppInfo from an application ID.

Parameters

application_id (int) – The application ID to retrieve information from.

Raises
  • NotFound – An application with this ID does not exist.

  • HTTPException – Retrieving the application failed.

Returns

The application information.

Return type

PartialAppInfo

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.

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_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, Guild.members, Member.activity and Member.voice per Member.

Note

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

Parameters
Raises
Returns

The guild from the ID.

Return type

Guild

fetch_guilds(*, limit=100, before=None, after=None)

Retrieves an AsyncIterator that enables receiving your guilds.

Note

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

Note

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

Examples

Usage

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

Flattening into a list

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

All parameters are optional.

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

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

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

Raises

HTTPException – Getting the guilds failed.

Yields

Guild – The guild with the guild data parsed.

await fetch_invite(url, *, with_counts=True, with_expiration=True, 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.

Parameters
Raises
Returns

The invite from the URL/ID.

Return type

Invite

await fetch_premium_sticker_packs()

This function is a coroutine.

Retrieves all available premium sticker packs.

New in version 2.0.

Raises

HTTPException – Retrieving the sticker packs failed.

Returns

All available premium sticker packs.

Return type

List[StickerPack]

await fetch_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_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_user(user_id, /)

This function is a coroutine.

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

Note

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

Parameters

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

Raises
Returns

The user you requested.

Return type

User

await fetch_webhook(webhook_id, /)

This function is a coroutine.

Retrieves a Webhook with the specified ID.

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.

Parameters

guild_id (int) – The ID of the guild.

Raises
Returns

The guild’s widget.

Return type

Widget

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_application_command(name, guild_ids=None, type=<class 'discord.commands.core.SlashCommand'>)

Get a ApplicationCommand from the internal list of commands.

New in version 2.0.

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

  • guild_ids (List[int]) – The guild ids associated to the command to get.

  • type (Type[ApplicationCommand]) – The type of the command to get. Defaults to SlashCommand.

Returns

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

Return type

Optional[ApplicationCommand]

await get_application_context(interaction, cls=<class 'discord.commands.context.ApplicationContext'>)

This function is a coroutine.

Returns the invocation context from the interaction.

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

Parameters
  • interaction (discord.Interaction) – The interaction to get the invocation context from.

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

Returns

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

Return type

ApplicationContext

await get_autocomplete_context(interaction, cls=<class 'discord.commands.context.AutocompleteContext'>)

This function is a coroutine.

Returns the autocomplete context from the interaction.

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

Parameters
  • interaction (discord.Interaction) – The interaction to get the invocation context from.

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

Returns

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

Return type

AutocompleteContext

get_channel(id, /)

Returns a channel or thread with the given ID.

Parameters

id (int) – The ID to search for.

Returns

The returned channel or None if not found.

Return type

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

get_cog(name)

Gets the cog instance requested.

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

Parameters

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

Returns

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

Return type

Optional[Cog]

property get_command

Shortcut for get_application_command().

Note

Overridden in ext.commands.Bot.

New in version 2.0.

await get_desynced_commands(guild_id=None, prefetched=None)

This function is a coroutine.

Gets the list of commands that are desynced from discord. If guild_id is specified, it will only return guild commands that are desynced from said guild, else it will return global commands.

Note

This function is meant to be used internally, and should only be used if you want to override the default command registration behavior.

New in version 2.0.

Parameters
  • guild_id (Optional[int]) – The guild id to get the desynced commands for, else global commands if unspecified.

  • prefetched (Optional[List[ApplicationCommand]]) – If you already fetched the commands, you can pass them here to be used. Not recommended for typical usage.

Returns

A list of the desynced commands. Each will come with at least the cmd and action keys, which respectively contain the command and the action to perform. Other keys may also be present depending on the action, including id.

Return type

List[Dict[str, Any]]

get_emoji(id, /)

Returns an emoji with the given ID.

Parameters

id (int) – The ID to search for.

Returns

The custom emoji or None if not found.

Return type

Optional[Emoji]

get_guild(id, /)

Returns a guild with the given ID.

Parameters

id (int) – The ID to search for.

Returns

The guild or None if not found.

Return type

Optional[Guild]

get_message(id, /)

Returns a message the given ID.

This is useful if you have a message_id but don’t want to do an API call to access the message.

Parameters

id (int) – The ID to search for.

Returns

The returned message or None if not found.

Return type

Optional[Message]

await get_or_fetch_user(id, /)

Looks up a user in the user cache or fetches if not found.

Parameters

id (int) – The ID to search for.

Returns

The user or None if not found.

Return type

Optional[User]

get_partial_messageable(id, *, 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.

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

Returns

The partial messageable

Return type

PartialMessageable

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

Returns

The sticker or None if not found.

Return type

Optional[GuildSticker]

get_user(id, /)

Returns a user with the given ID.

Parameters

id (int) – The ID to search for.

Returns

The user or None if not found.

Return type

Optional[User]

group(name=None, description=None, guild_ids=None)

A shortcut decorator that initializes the provided subclass of SlashCommandGroup and adds it to the internal command list via add_application_command().

New in version 2.0.

Parameters
  • name (Optional[str]) – The name of the group to create. This will resolve to the name of the decorated class if None is passed.

  • description (Optional[str]) – The description of the group to create.

  • guild_ids (Optional[List[int]]) – A list of the IDs of each guild this group should be added to, making it a guild command. This will be a global command if None is passed.

Returns

The slash command group that was created.

Return type

Callable[[Type[SlashCommandGroup]], SlashCommandGroup]

property guilds

The guilds that the connected client is a member of.

Type

List[Guild]

property intents

The intents configured for this connection.

New in version 1.5.

Type

Intents

await invoke_application_command(ctx)

This function is a coroutine.

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

Parameters

ctx (ApplicationCommand) – The invocation context to invoke.

is_closed()

bool: Indicates if the WebSocket connection is closed.

await is_owner(user)

This function is a coroutine.

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

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

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

Parameters

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

Returns

Whether the user is the owner.

Return type

bool

is_ready()

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.

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

load_extension(name, *, package=None, recursive=False, store=False)

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.

The extension passed can either be the direct name of a file within the current working directory or a folder that contains multiple extensions.

Parameters
  • name (str) – The extension or folder name to load. It must be dot separated like regular Python imports if accessing a submodule. 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.

  • recursive (Optional[bool]) –

    If subdirectories under the given head directory should be recursively loaded. Defaults to False.

    New in version 2.0.

  • store (Optional[bool]) –

    If exceptions should be stored or raised. If set to True, all exceptions encountered will be stored in a returned dictionary as a load status. If set to False, if any exceptions are encountered they will be raised and the bot will be closed. If no exceptions are encountered, a list of loaded extension names will be returned. Defaults to False.

    New in version 2.0.

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.

Returns

If the store parameter is set to True, a dictionary will be returned that contains keys to represent the loaded extension names. The values bound to each key can either be an exception that occurred when loading that extension or a True boolean representing a successful load. If the store parameter is set to False, either a list containing a list of loaded extensions or nothing due to an encountered exception.

Return type

Optional[Union[Dict[str, Union[errors.ExtensionError, bool]], List[str]]]

load_extensions(*names, package=None, recursive=False, store=False)

Loads multiple extensions at once.

This method simplifies the process of loading multiple extensions by handling the looping of load_extension.

Parameters
  • names (str) – The extension or folder names to load. It must be dot separated like regular Python imports if accessing a submodule. 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.

  • recursive (Optional[bool]) –

    If subdirectories under the given head directory should be recursively loaded. Defaults to False.

    New in version 2.0.

  • store (Optional[bool]) –

    If exceptions should be stored or raised. If set to True, all exceptions encountered will be stored in a returned dictionary as a load status. If set to False, if any exceptions are encountered they will be raised and the bot will be closed. If no exceptions are encountered, a list of loaded extension names will be returned. Defaults to False.

    New in version 2.0.

Raises
  • ExtensionNotFound – A given 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 – A given extension is already loaded.

  • NoEntryPointError – A given extension does not have a setup function.

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

Returns

If the store parameter is set to True, a dictionary will be returned that contains keys to represent the loaded extension names. The values bound to each key can either be an exception that occurred when loading that extension or a True boolean representing a successful load. If the store parameter is set to False, either a list containing names of loaded extensions or nothing due to an encountered exception.

Return type

Optional[Union[Dict[str, Union[errors.ExtensionError, bool]], List[str]]]

await login(token)

This function is a coroutine.

Logs in the client with the specified credentials.

Parameters

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

Raises
  • TypeError – The token was in invalid type.

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

await 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 on_error() for more details.

property persistent_views

A sequence of persistent views added to the client.

New in version 2.0.

Type

Sequence[View]

property private_channels

The private channels that the connected client is participating on.

Note

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

Type

List[abc.PrivateChannel]

await process_application_commands(interaction, auto_sync=None)

This function is a coroutine.

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

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

This function finds a registered command matching the interaction id from application commands and invokes it. If no matching command was found, it replies to the interaction with a default message.

New in version 2.0.

Parameters
  • interaction (discord.Interaction) – The interaction to process

  • auto_sync (Optional[bool]) – Whether to automatically sync and unregister the command if it is not found in the internal cache. This will invoke the sync_commands() method on the context of the command, either globally or per-guild, based on the type of the command, respectively. Defaults to Bot.auto_sync_commands.

await register_command(command, force=True, guild_ids=None)

This function is a coroutine.

Registers a command. If the command has guild_ids set, or if the guild_ids parameter is passed, the command will be registered as a guild command for those guilds.

Parameters
  • command (ApplicationCommand) – The command to register.

  • force (bool) – Whether to force the command to be registered. If this is set to False, the command will only be registered if it seems to already be registered and up to date with our internal cache. Defaults to True.

  • guild_ids (list) – A list of guild ids to register the command for. If this is not set, the command’s ApplicationCommand.guild_ids attribute will be used.

Returns

The command that was registered

Return type

ApplicationCommand

await register_commands(commands=None, guild_id=None, method='bulk', force=False, delete_existing=True)

This function is a coroutine.

Register a list of commands.

New in version 2.0.

Parameters
  • commands (Optional[List[ApplicationCommand]]) – A list of commands to register. If this is not set (None), then all commands will be registered.

  • guild_id (Optional[int]) – If this is set, the commands will be registered as a guild command for the respective guild. If it is not set, the commands will be registered according to their ApplicationCommand.guild_ids attribute.

  • method (Literal['individual', 'bulk', 'auto']) – The method to use when registering the commands. If this is set to “individual”, then each command will be registered individually. If this is set to “bulk”, then all commands will be registered in bulk. If this is set to “auto”, then the method will be determined automatically. Defaults to “bulk”.

  • force (bool) – Registers the commands regardless of the state of the command on Discord. This uses one less API call, but can result in hitting rate limits more often. Defaults to False.

  • delete_existing (bool) – Whether to delete existing commands that are not in the list of commands to register. Defaults to True.

reload_extension(name, *, package=None)

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 submodule. 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_application_command(command)

Remove a ApplicationCommand from the internal list of commands.

New in version 2.0.

Parameters

command (ApplicationCommand) – The command to remove.

Returns

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

Return type

Optional[ApplicationCommand]

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 and returns it.

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

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

Parameters

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

Returns

The cog that was removed. None if not found.

Return type

Optional[Cog]

remove_listener(func, name=...)

Removes a listener from the pool of listeners.

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

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(close())
    # cancel all tasks lingering
finally:
    loop.close()

Warning

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

slash_group(name=None, description=None, guild_ids=None)

A shortcut decorator that initializes the provided subclass of SlashCommandGroup and adds it to the internal command list via add_application_command().

New in version 2.0.

Parameters
  • name (Optional[str]) – The name of the group to create. This will resolve to the name of the decorated class if None is passed.

  • description (Optional[str]) – The description of the group to create.

  • guild_ids (Optional[List[int]]) – A list of the IDs of each guild this group should be added to, making it a guild command. This will be a global command if None is passed.

Returns

The slash command group that was created.

Return type

Callable[[Type[SlashCommandGroup]], SlashCommandGroup]

await start(token, *, reconnect=True)

This function is a coroutine.

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

Raises

TypeError – An unexpected keyword argument was received.

property status

Status: The status being used upon logging on to Discord.

property stickers

The stickers that the connected client has.

New in version 2.0.

Type

List[GuildSticker]

await sync_commands(commands=None, method='bulk', force=False, guild_ids=None, register_guild_commands=True, check_guilds=[], delete_existing=True)

This function is a coroutine.

Registers all commands that have been added through add_application_command(). This method cleans up all commands over the API and should sync them with the internal cache of commands. It attempts to register the commands in the most efficient way possible, unless force is set to True, in which case it will always register all commands.

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

Note

If you remove all guild commands from a particular guild, the library may not be able to detect and update the commands accordingly, as it would have to individually check for each guild. To force the library to unregister a guild’s commands, call this function with commands=[] and guild_ids=[guild_id].

New in version 2.0.

Parameters
  • commands (Optional[List[ApplicationCommand]]) – A list of commands to register. If this is not set (None), then all commands will be registered.

  • method (Literal['individual', 'bulk', 'auto']) – The method to use when registering the commands. If this is set to “individual”, then each command will be registered individually. If this is set to “bulk”, then all commands will be registered in bulk. If this is set to “auto”, then the method will be determined automatically. Defaults to “bulk”.

  • force (bool) – Registers the commands regardless of the state of the command on Discord. This uses one less API call, but can result in hitting rate limits more often. Defaults to False.

  • guild_ids (Optional[List[int]]) – A list of guild ids to register the commands for. If this is not set, the commands’ guild_ids attribute will be used.

  • register_guild_commands (bool) – Whether to register guild commands. Defaults to True.

  • check_guilds (Optional[List[int]]) – A list of guilds ids to check for commands to unregister, since the bot would otherwise have to check all guilds. Unlike guild_ids, this does not alter the commands’ guild_ids attribute, instead it adds the guild ids to a list of guilds to sync commands for. If register_guild_commands is set to False, then this parameter is ignored.

  • delete_existing (bool) – Whether to delete existing commands that are not in the list of commands to register. Defaults to True.

unload_extension(name, *, package=None)

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

property users

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

Type

List[User]

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('👍')
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 – Raised if a timeout is provided and 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.

for ... in walk_application_commands()

An iterator that recursively walks through all application commands and subcommands.

Yields

ApplicationCommand – An application command from the internal list of application commands.

AutoShardedBot

class discord.AutoShardedBot(description=None, *args, **options)

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

New in version 2.0.

Application Commands

Command Permission Decorators

@discord.commands.default_permissions(**perms)

A decorator that limits the usage of a slash command to members with certain permissions.

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

Note

These permissions can be updated by server administrators per-guild. As such, these are only “defaults”, as the name suggests. If you want to make sure that a user always has the specified permissions regardless, you should use an internal check such as has_permissions().

Parameters

**perms (Dict[str, bool]) – An argument list of permissions to check for.

Example

from discord import default_permissions

@bot.slash_command()
@default_permissions(manage_messages=True)
async def test(ctx):
    await ctx.respond('You can manage messages.')
@discord.commands.guild_only

A decorator that limits the usage of a slash command to guild contexts. The command won’t be able to be used in private message channels.

Example

from discord import guild_only

@bot.slash_command()
@guild_only()
async def test(ctx):
    await ctx.respond("You're in a guild.")

ApplicationCommand

class discord.ApplicationCommand(func, **kwargs)
is_on_cooldown(ctx)

Checks whether the command is currently on cooldown.

Note

This uses the current time instead of the interaction time.

Parameters

ctx (ApplicationContext) – The invocation context to use when checking the command’s 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 (ApplicationContext) – 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.

Note

This uses the current time instead of the interaction time.

Parameters

ctx (ApplicationContext) – 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

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

TypeError – The coroutine passed is not actually a coroutine.

has_error_handler()

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

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 ApplicationContext. See Bot.before_invoke() for more info.

Parameters

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

Raises

TypeError – The coroutine passed is not actually a coroutine.

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 ApplicationContext. See Bot.after_invoke() for more info.

Parameters

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

Raises

TypeError – The coroutine passed is not actually a coroutine.

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

@discord.commands.application_command(cls=<class 'discord.commands.core.SlashCommand'>, **attrs)

A decorator that transforms a function into an ApplicationCommand. More specifically, usually one of SlashCommand, UserCommand, or MessageCommand. The exact class depends on the cls parameter. By default, the description attribute is received automatically from the docstring of the function and is cleaned up with the use of inspect.cleandoc. If the docstring is bytes, then it is decoded into str using utf-8 encoding. The name attribute also defaults to the function name unchanged.

New in version 2.0.

Parameters
  • cls (ApplicationCommand) – The class to construct with. By default, this is SlashCommand. You usually do not change this.

  • attrs – Keyword arguments to pass into the construction of the class denoted by cls.

Raises

TypeError – If the function is not a coroutine or is already a command.

Returns

A decorator that converts the provided method into an ApplicationCommand, or subclass of it.

Return type

Callable[…, ApplicationCommand]

@discord.commands.command(**kwargs)

An alias for application_command().

Note

This decorator is overridden by ext.commands.command().

New in version 2.0.

Returns

A decorator that converts the provided method into an ApplicationCommand.

Return type

Callable[…, ApplicationCommand]

SlashCommand

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

A class that implements the protocol for a slash command.

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

New in version 2.0.

name

The name of the command.

Type

str

callback

The coroutine that is executed when the command is called.

Type

coroutine

description

The description for the command.

Type

Optional[str]

guild_ids

The ids of the guilds where this command will be registered.

Type

Optional[List[int]]

options

The parameters for this command.

Type

List[Option]

parent

The parent group that this command belongs to. None if there isn’t one.

Type

Optional[SlashCommandGroup]

mention

Returns a string that allows you to mention the slash command.

Type

str

guild_only

Whether the command should only be usable inside a guild.

Type

bool

default_member_permissions

The default permissions a member needs to be able to run the command.

Type

Permissions

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 ApplicationContext as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from ApplicationCommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_application_command_error() event.

Type

List[Callable[[ApplicationContext], bool]]

cooldown

The cooldown applied when the command is invoked. None if the command doesn’t have a cooldown.

Type

Optional[Cooldown]

name_localizations

The name localizations for this command. The values of this should be "locale": "name". See here for a list of valid locales.

Type

Optional[Dict[str, str]]

description_localizations

The description localizations for this command. The values of this should be "locale": "description". See here for a list of valid locales.

Type

Optional[Dict[str, str]]

copy()

Creates a copy of this command.

Returns

A new instance of this command.

Return type

SlashCommand

@discord.commands.slash_command(**kwargs)

Decorator for slash commands that invokes application_command().

New in version 2.0.

Returns

A decorator that converts the provided method into a SlashCommand.

Return type

Callable[…, SlashCommand]

SlashCommandGroup

class discord.SlashCommandGroup(*args, **kwargs)

A class that implements the protocol for a slash command group.

These can be created manually, but they should be created via the decorator or functional interface.

name

The name of the command.

Type

str

description

The description for the command.

Type

Optional[str]

guild_ids

The ids of the guilds where this command will be registered.

Type

Optional[List[int]]

parent

The parent group that this group belongs to. None if there isn’t one.

Type

Optional[SlashCommandGroup]

guild_only

Whether the command should only be usable inside a guild.

Type

bool

default_member_permissions

The default permissions a member needs to be able to run the command.

Type

Permissions

checks

A list of predicates that verifies if the command could be executed with the given ApplicationContext as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from ApplicationCommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_application_command_error() event.

Type

List[Callable[[ApplicationContext], bool]]

name_localizations

The name localizations for this command. The values of this should be "locale": "name". See here for a list of valid locales.

Type

Optional[Dict[str, str]]

description_localizations

The description localizations for this command. The values of this should be "locale": "description". See here for a list of valid locales.

Type

Optional[Dict[str, str]]

create_subgroup(name, description=None, guild_ids=None, **kwargs)

Creates a new subgroup for this SlashCommandGroup.

Parameters
  • name (str) – The name of the group to create.

  • description (Optional[str]) – The description of the group to create.

  • guild_ids (Optional[List[int]]) – A list of the IDs of each guild this group should be added to, making it a guild command. This will be a global command if None is passed.

  • guild_only (bool) – Whether the command should only be usable inside a guild.

  • default_member_permissions (Permissions) – The default permissions a member needs to be able to run the command.

  • checks (List[Callable[[ApplicationContext], bool]]) – A list of predicates that verifies if the command could be executed with the given ApplicationContext as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from ApplicationCommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_application_command_error() event.

  • name_localizations (Optional[Dict[str, str]]) –

    The name localizations for this command. The values of this should be "locale": "name". See here for a list of valid locales.

  • description_localizations (Optional[Dict[str, str]]) –

    The description localizations for this command. The values of this should be "locale": "description". See here for a list of valid locales.

Returns

The slash command group that was created.

Return type

SlashCommandGroup

subgroup(name=None, description=None, guild_ids=None)

A shortcut decorator that initializes the provided subclass of SlashCommandGroup as a subgroup.

New in version 2.0.

Parameters
  • name (Optional[str]) – The name of the group to create. This will resolve to the name of the decorated class if None is passed.

  • description (Optional[str]) – The description of the group to create.

  • guild_ids (Optional[List[int]]) – A list of the IDs of each guild this group should be added to, making it a guild command. This will be a global command if None is passed.

Returns

The slash command group that was created.

Return type

Callable[[Type[SlashCommandGroup]], SlashCommandGroup]

for ... in walk_commands()

An iterator that recursively walks through all slash commands in this group.

Yields

SlashCommand – A slash command from the group.

copy()

Creates a copy of this command group.

Returns

A new instance of this command group.

Return type

SlashCommandGroup

Option

class discord.Option(input_type=<class 'str'>, /, description=None, **kwargs)

Represents a selectable option for a slash command.

Examples

Basic usage:

@bot.slash_command(guild_ids=[...])
async def hello(
    ctx: discord.ApplicationContext,
    name: Option(str, "Enter your name"),
    age: Option(int, "Enter your age", min_value=1, max_value=99, default=18)
    # passing the default value makes an argument optional
    # you also can create optional argument using:
    # age: Option(int, "Enter your age") = 18
):
    await ctx.respond(f"Hello! Your name is {name} and you are {age} years old.")

New in version 2.0.

input_type

The type of input that is expected for this option. This can be a SlashCommandOptionType, an associated class, a channel type, a Converter, a converter class or an enum.Enum.

Type

Union[Type[str], Type[bool], Type[int], Type[float], Type[abc.GuildChannel], Type[Thread], Type[Member], Type[User], Type[Attachment], Type[Role], Type[abc.Mentionable], SlashCommandOptionType, Type[ext.commands.Converter], Type[enums.Enum], Type[Enum]]

name

The name of this option visible in the UI. Inherits from the variable name if not provided as a parameter.

Type

str

description

The description of this option. Must be 100 characters or fewer.

Type

Optional[str]

choices

The list of available choices for this option. Can be a list of values or OptionChoice objects (which represent a name:value pair). If provided, the input from the user must match one of the choices in the list.

Type

Optional[List[Union[Any, OptionChoice]]]

required

Whether this option is required.

Type

Optional[bool]

default

The default value for this option. If provided, required will be considered False.

Type

Optional[Any]

min_value

The minimum value that can be entered. Only applies to Options with an input_type of int or float.

Type

Optional[int]

max_value

The maximum value that can be entered. Only applies to Options with an input_type of int or float.

Type

Optional[int]

min_length

The minimum length of the string that can be entered. Must be between 0 and 6000 (inclusive). Only applies to Options with an input_type of str.

Type

Optional[int]

max_length

The maximum length of the string that can be entered. Must be between 1 and 6000 (inclusive). Only applies to Options with an input_type of str.

Type

Optional[int]

autocomplete

The autocomplete handler for the option. Accepts an iterable of str, a callable (sync or async) that takes a single argument of AutocompleteContext, or a coroutine. Must resolve to an iterable of str.

Note

Does not validate the input value against the autocomplete results.

Type

Optional[Any]

name_localizations

The name localizations for this option. The values of this should be "locale": "name". See here for a list of valid locales.

Type

Optional[Dict[str, str]]

description_localizations

The description localizations for this option. The values of this should be "locale": "description". See here for a list of valid locales.

Type

Optional[Dict[str, str]]

@discord.commands.option(name, type=None, **kwargs)

A decorator that can be used instead of typehinting Option.

New in version 2.0.

ThreadOption

class discord.ThreadOption(thread_type)

Represents a class that can be passed as the input_type for an Option class.

New in version 2.0.

Parameters

thread_type (Literal["public", "private", "news"]) – The thread type to expect for this options input.

OptionChoice

class discord.OptionChoice(name, value=None, name_localizations=None)

Represents a name:value pairing for a selected Option.

New in version 2.0.

name

The name of the choice. Shown in the UI when selecting an option.

Type

str

value

The value of the choice. If not provided, will use the value of name.

Type

Optional[Union[str, int, float]]

name_localizations

The name localizations for this choice. The values of this should be "locale": "name". See here for a list of valid locales.

Type

Optional[Dict[str, str]]

UserCommand

Methods
class discord.UserCommand(*args, **kwargs)

A class that implements the protocol for user context menu commands.

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

guild_ids

The ids of the guilds where this command will be registered.

Type

Optional[List[int]]

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 ApplicationContext as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from ApplicationCommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_application_command_error() event.

Type

List[Callable[[ApplicationContext], bool]]

copy()

Creates a copy of this command.

Returns

A new instance of this command.

Return type

UserCommand

@discord.commands.user_command(**kwargs)

Decorator for user commands that invokes application_command().

New in version 2.0.

Returns

A decorator that converts the provided method into a UserCommand.

Return type

Callable[…, UserCommand]

MessageCommand

Methods
class discord.MessageCommand(*args, **kwargs)

A class that implements the protocol for message context menu commands.

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

guild_ids

The ids of the guilds where this command will be registered.

Type

Optional[List[int]]

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 ApplicationContext as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from ApplicationCommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_application_command_error() event.

Type

List[Callable[[ApplicationContext], bool]]

copy()

Creates a copy of this command.

Returns

A new instance of this command.

Return type

MessageCommand

@discord.commands.message_command(**kwargs)

Decorator for message commands that invokes application_command().

New in version 2.0.

Returns

A decorator that converts the provided method into a MessageCommand.

Return type

Callable[…, MessageCommand]

ApplicationContext

class discord.ApplicationContext(bot, interaction)

Represents a Discord application command interaction context.

This class is not created manually and is instead passed to application commands as the first parameter.

New in version 2.0.

bot

The bot that the command belongs to.

Type

Bot

interaction

The interaction object that invoked the command.

Type

Interaction

command

The command that this context belongs to.

Type

ApplicationCommand

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 ApplicationCommand holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function. You must take care in passing the proper arguments when using this function.

Parameters
  • command (ApplicationCommand) – 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.

channel

Union[abc.GuildChannel, PartialMessageable, Thread]: Returns the channel associated with this context’s command. Shorthand for Interaction.channel.

channel_id

Returns the ID of the channel associated with this context’s command. Shorthand for Interaction.channel_id.

Type

int

guild

Returns the guild associated with this context’s command. Shorthand for Interaction.guild.

Type

Optional[Guild]

guild_id

Returns the ID of the guild associated with this context’s command. Shorthand for Interaction.guild_id.

Type

int

locale

Returns the locale of the guild associated with this context’s command. Shorthand for Interaction.locale.

Type

str

guild_locale

Returns the locale of the guild associated with this context’s command. Shorthand for Interaction.guild_locale.

Type

str

me

Union[Member, ClientUser]: Similar to Guild.me except it may return the ClientUser in private message message contexts, or when Intents.guilds() is absent.

message

Returns the message sent with this context’s command. Shorthand for Interaction.message, if applicable.

Type

Optional[Message]

user

Returns the user that sent this context’s command. Shorthand for Interaction.user.

Type

Union[Member, User]

author

Returns the user that sent this context’s command. Shorthand for Interaction.user.

Type

Union[Member, User]

property voice_client

Returns the voice client associated with this context’s command. Shorthand for Interaction.guild.voice_client, if applicable.

Type

Optional[VoiceProtocol]

response

Returns the response object associated with this context’s command. Shorthand for Interaction.response.

Type

InteractionResponse

property selected_options

The options and values that were selected by the user when sending the command.

Returns

A dictionary containing the options and values that were selected by the user when the command was processed, if applicable. Returns None if the command has not yet been invoked, or if there are no options defined for that command.

Return type

Optional[List[Dict[str, Any]]]

property unselected_options

The options that were not provided by the user when sending the command.

Returns

A list of Option objects (if any) that were not selected by the user when the command was processed. Returns None if there are no options defined for that command.

Return type

Optional[List[Option]]

property send_modal

This function is a coroutine. Responds to this interaction by sending a modal dialog. This cannot be used to respond to another modal dialog submission.

Parameters

modal (discord.ui.Modal) – The modal dialog to display to the user.

Raises
await respond(*args, **kwargs)

This function is a coroutine.

Sends either a response or a message using the followup webhook determined by whether the interaction has been responded to or not.

Returns

The response, its type depending on whether it’s an interaction response or a followup.

Return type

Union[discord.Interaction, discord.WebhookMessage]

property send_response

This function is a coroutine.

Responds to this interaction by sending a message.

Parameters
  • content (Optional[str]) – The content of the message to send.

  • embeds (List[Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the embed parameter.

  • embed (Embed) – The rich embed for the content to send. This cannot be mixed with embeds parameter.

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

  • view (discord.ui.View) – The view to send with the message.

  • ephemeral (bool) – Indicates if the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message, and it has no timeout set then the timeout is set to 15 minutes.

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

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent.

  • file (File) – The file to upload.

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

Raises
Returns

The interaction object associated with the sent message.

Return type

Interaction

property send_followup

This function is a coroutine.

Sends a message using the webhook.

The content must be a type that can convert to a string through str(content).

To upload a single file, the file parameter should be used with a single File object.

If the embed parameter is provided, it must be of type Embed and it must be a rich embed type. You cannot mix the embed parameter with the embeds parameter, which must be a list of Embed objects to send.

Parameters
  • content (str) – The content of the message to send.

  • wait (bool) – Whether the server should wait before sending a response. This essentially means that the return type of this function changes from None to a WebhookMessage if set to True. If the type of webhook is WebhookType.application then this is always set to True.

  • username (str) – The username to send with this message. If no username is provided then the default username for the webhook is used.

  • avatar_url (str) – The avatar URL to send with this message. If no avatar URL is provided then the default avatar for the webhook is used. If this is not a string then it is explicitly cast using str.

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

  • ephemeral (bool) –

    Indicates if the message should only be visible to the user. This is only available to WebhookType.application webhooks. If a view is sent with an ephemeral message, and it has no timeout set then the timeout is set to 15 minutes.

    New in version 2.0.

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

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

  • embed (Embed) – The rich embed for the content to send. This cannot be mixed with embeds parameter.

  • embeds (List[Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the embed parameter.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message.

    New in version 1.4.

  • view (discord.ui.View) –

    The view to send with the message. You can only send a view if this webhook is not partial and has state attached. A webhook has state attached if the webhook is managed by the library.

    New in version 2.0.

  • thread (Snowflake) –

    The thread to send this webhook to.

    New in version 2.0.

  • thread_name (str) –

    The name of the thread to create. Only works for forum channels.

    New in version 2.0.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent.

Raises
  • HTTPException – Sending the message failed.

  • NotFound – This webhook was not found.

  • Forbidden – The authorization token for the webhook is incorrect.

  • TypeError – You specified both embed and embeds or file and files.

  • ValueError – The length of embeds was invalid.

  • InvalidArgument – Either there was no token associated with this webhook, ephemeral was passed with the improper webhook type, there was no state attached with this webhook when giving it a view, or you specified both thread_name and thread.

Returns

If wait is True then the message that was sent, otherwise None.

Return type

Optional[WebhookMessage]

property defer

This function is a coroutine.

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This can only be used with the following interaction types:

Parameters
Raises
property followup

Returns the followup webhook for followup interactions.

Type

Webhook

await delete(*, delay=None)

This function is a coroutine.

Deletes the original interaction response message.

This is a higher level interface to Interaction.delete_original_response().

Parameters

delay (Optional[float]) – If provided, the number of seconds to wait before deleting the message.

Raises
  • HTTPException – Deleting the message failed.

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

property edit

This function is a coroutine.

Edits the original interaction response message.

This is a lower level interface to InteractionMessage.edit() in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.

Parameters
  • content (Optional[str]) – The content to edit the message with or None to clear it.

  • embeds (List[Embed]) – A list of embeds to edit the message with.

  • embed (Optional[Embed]) – The embed to edit the message with. None suppresses the embeds. This should not be mixed with the embeds parameter.

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

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

  • attachments (List[Attachment]) – A list of attachments to keep in the message. If [] is passed then all attachments are removed.

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

  • view (Optional[View]) – The updated view to update this message with. If None is passed then the view is removed.

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

Raises
  • HTTPException – Editing the message failed.

  • Forbidden – Edited a message that is not yours.

  • TypeError – You specified both embed and embeds or file and files

  • ValueError – The length of embeds was invalid.

Returns

The newly edited message.

Return type

InteractionMessage

property cog

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

Type

Optional[Cog]

AutocompleteContext

class discord.AutocompleteContext(bot, interaction)

Represents context for a slash command’s option autocomplete.

This class is not created manually and is instead passed to an Option’s autocomplete callback.

New in version 2.0.

bot

The bot that the command belongs to.

Type

Bot

interaction

The interaction object that invoked the autocomplete.

Type

Interaction

command

The command that this context belongs to.

Type

ApplicationCommand

focused

The option the user is currently typing.

Type

Option

value

The content of the focused option.

Type

str

options

A name to value mapping of the options that the user has selected before this option.

Type

Dict[str, Any]

property cog

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

Type

Optional[Cog]

Cogs

Cog

class discord.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 ApplicationCommands that are defined inside this cog.

Note

This does not include subcommands.

Return type

List[ApplicationCommand]

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.

cog_unload()

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

This function cannot be a coroutine. It must be a regular function.

Subclasses must replace this if they want special unloading behaviour.

bot_check_once(ctx)

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

Parameters

ctx (Context) – The invocation 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 or ApplicationContext.

Parameters

ctx (Context) – The invocation 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 or ApplicationContext.

Parameters

ctx (Context) – The invocation context.

await cog_command_error(ctx, error)

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
await cog_before_invoke(ctx)

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

This is similar to ApplicationCommand.before_invoke().

This must be a coroutine.

Parameters

ctx (ApplicationContext) – The invocation context.

await cog_after_invoke(ctx)

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

This is similar to ApplicationCommand.after_invoke().

This must be a coroutine.

Parameters

ctx (ApplicationContext) – The invocation context.

CogMeta

class discord.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(discord.CogMeta, abc.ABCMeta):
    pass

class SomeMixin(metaclass=abc.ABCMeta):
    pass

class SomeCogMixin(SomeMixin, discord.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(discord.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(discord.Cog, command_attrs=dict(hidden=True)):
    @discord.slash_command()
    async def foo(self, ctx):
        pass # hidden -> True

    @discord.slash_command(hidden=False)
    async def bar(self, ctx):
        pass # hidden -> False
Type

dict

guild_ids

A shortcut to command_attrs, what guild_ids should all application commands have in the cog. You can override this by setting guild_ids per command.

New in version 2.0.

Type

Optional[List[int]]

Application Info

AppInfo

class discord.AppInfo

Represents the application info for the bot provided by Discord.

id

The application ID.

Type

int

name

The application name.

Type

str

owner

The application owner.

Type

User

team

The application’s team.

New in version 1.3.

Type

Optional[Team]

description

The application description.

Type

str

bot_public

Whether the bot can be invited by anyone or if it is locked to the application owner.

Type

bool

bot_require_code_grant

Whether the bot requires the completion of the full OAuth2 code grant flow to join.

Type

bool

rpc_origins

A list of RPC origin URLs, if RPC is enabled.

Type

Optional[List[str]]

summary

If this application is a game sold on Discord, this field will be the summary field for the store page of its primary SKU.

New in version 1.3.

Type

str

verify_key

The hex encoded key for verification in interactions and the GameSDK’s GetTicket.

New in version 1.3.

Type

str

guild_id

If this application is a game sold on Discord, this field will be the guild to which it has been linked to.

New in version 1.3.

Type

Optional[int]

primary_sku_id

If this application is a game sold on Discord, this field will be the id of the “Game SKU” that is created, if it exists.

New in version 1.3.

Type

Optional[int]

slug

If this application is a game sold on Discord, this field will be the URL slug that links to the store page.

New in version 1.3.

Type

Optional[str]

terms_of_service_url

The application’s terms of service URL, if set.

New in version 2.0.

Type

Optional[str]

privacy_policy_url

The application’s privacy policy URL, if set.

New in version 2.0.

Type

Optional[str]

property icon

Retrieves the application’s icon asset, if any.

Type

Optional[Asset]

property cover_image

Retrieves the cover image on a store embed, if any.

This is only available if the application is a game sold on Discord.

Type

Optional[Asset]

property guild

If this application is a game sold on Discord, this field will be the guild to which it has been linked.

New in version 1.3.

Type

Optional[Guild]

PartialAppInfo

class discord.PartialAppInfo

Represents a partial AppInfo given by create_invite()

New in version 2.0.

id

The application ID.

Type

int

name

The application name.

Type

str

description

The application description.

Type

str

rpc_origins

A list of RPC origin URLs, if RPC is enabled.

Type

Optional[List[str]]

summary

If this application is a game sold on Discord, this field will be the summary field for the store page of its primary SKU.

Type

str

verify_key

The hex encoded key for verification in interactions and the GameSDK’s GetTicket.

Type

str

terms_of_service_url

The application’s terms of service URL, if set.

Type

Optional[str]

privacy_policy_url

The application’s privacy policy URL, if set.

Type

Optional[str]

property icon

Retrieves the application’s icon asset, if any.

Type

Optional[Asset]

Team

class discord.Team

Represents an application team for a bot provided by Discord.

id

The team ID.

Type

int

name

The team name.

Type

str

owner_id

The team’s owner ID.

Type

int

members

A list of the members in the team.

New in version 1.3.

Type

List[TeamMember]

property icon

Retrieves the team’s icon asset, if any.

Type

Optional[Asset]

property owner

The team’s owner.

Type

Optional[TeamMember]

TeamMember

class discord.TeamMember

Represents a team member in a team.

x == y

Checks if two team members are equal.

x != y

Checks if two team members are not equal.

hash(x)

Return the team member’s hash.

str(x)

Returns the team member’s name with discriminator.

New in version 1.3.

name

The team member’s username.

Type

str

id

The team member’s unique ID.

Type

int

discriminator

The team member’s discriminator. This is given when the username has conflicts.

Type

str

avatar

The avatar hash the team member has. Could be None.

Type

Optional[str]

bot

Specifies if the user is a bot account.

Type

bool

team

The team that the member is from.

Type

Team

membership_state

The membership state of the member (e.g. invited or accepted)

Type

TeamMembershipState

Event Reference

This section outlines the different types of events listened by Client.

There are two ways to register an event, the first way is through the use of Client.event(). The second way is through subclassing Client and overriding the specific events. For example:

import discord

class MyClient(discord.Client):
    async def on_message(self, message):
        if message.author == self.user:
            return

        if message.content.startswith('$hello'):
            await message.channel.send('Hello World!')

If an event handler raises an exception, on_error() will be called to handle it, which defaults to print a traceback and ignoring the exception.

Warning

All the events must be a coroutine. If they aren’t, then you might get unexpected errors. In order to turn a function into a coroutine they must be async def functions.

Application Commands

discord.on_application_command(context)

Called when an application command is received.

New in version 2.0.

Parameters

context (ApplicationContext) – The ApplicationContext associated to the command being received.

discord.on_application_command_completion(context)

Called when an application command is completed, after any checks have finished.

New in version 2.0.

Parameters

context (ApplicationContext) – The ApplicationContext associated to the command that was completed.

discord.on_application_command_error(context, exception)

Called when an application command has an error.

New in version 2.0.

Parameters
  • context (ApplicationContext) – The ApplicationContext associated to the command that has an error.

  • exception (DiscordException) – The DiscordException associated to the error.

discord.on_unknown_application_command(interaction)

Called when an application command was not found in the bot’s internal cache.

New in version 2.0.

Parameters

interaction (Interaction) – The interaction associated to the unknown command.

AutoMod

discord.on_auto_moderation_rule_create(rule)

Called when an auto moderation rule is created.

The bot must have manage_guild to receive this, and Intents.auto_moderation_configuration must be enabled.

Parameters

rule (AutoModRule) – The newly created rule.

discord.on_auto_moderation_rule_update(rule)

Called when an auto moderation rule is updated.

The bot must have manage_guild to receive this, and Intents.auto_moderation_configuration must be enabled.

Parameters

rule (AutoModRule) – The updated rule.

discord.on_auto_moderation_rule_delete(rule)

Called when an auto moderation rule is deleted.

The bot must have manage_guild to receive this, and Intents.auto_moderation_configuration must be enabled.

Parameters

rule (AutoModRule) – The deleted rule.

discord.on_auto_moderation_action_execution(payload)

Called when an auto moderation action is executed.

The bot must have manage_guild to receive this, and Intents.auto_moderation_execution must be enabled.

Parameters

payload (AutoModActionExecutionEvent) – The event’s data.

Bans

discord.on_member_ban(guild, user)

Called when user gets banned from a Guild.

This requires Intents.bans to be enabled.

Parameters
  • guild (Guild) – The guild the user got banned from.

  • user (Union[User, Member]) – The user that got banned. Can be either User or Member depending if the user was in the guild or not at the time of removal.

discord.on_member_unban(guild, user)

Called when a User gets unbanned from a Guild.

This requires Intents.bans to be enabled.

Parameters
  • guild (Guild) – The guild the user got unbanned from.

  • user (User) – The user that got unbanned.

Channels

discord.on_private_channel_update(before, after)

Called whenever a private group DM is updated. e.g. changed name or topic.

This requires Intents.messages to be enabled.

Parameters
  • before (GroupChannel) – The updated group channel’s old info.

  • after (GroupChannel) – The updated group channel’s new info.

discord.on_private_channel_pins_update(channel, last_pin)

Called whenever a message is pinned or unpinned from a private channel.

Parameters
  • channel (abc.PrivateChannel) – The private channel that had its pins updated.

  • last_pin (Optional[datetime.datetime]) – The latest message that was pinned as an aware datetime in UTC. Could be None.

discord.on_guild_channel_update(before, after)

Called whenever a guild channel is updated. e.g. changed name, topic, permissions.

This requires Intents.guilds to be enabled.

Parameters
discord.on_guild_channel_pins_update(channel, last_pin)

Called whenever a message is pinned or unpinned from a guild channel.

This requires Intents.guilds to be enabled.

Parameters
  • channel (Union[abc.GuildChannel, Thread]) – The guild channel that had its pins updated.

  • last_pin (Optional[datetime.datetime]) – The latest message that was pinned as an aware datetime in UTC. Could be None.

discord.on_guild_channel_delete(channel)
discord.on_guild_channel_create(channel)

Called whenever a guild channel is deleted or created.

Note that you can get the guild from guild.

This requires Intents.guilds to be enabled.

Parameters

channel (abc.GuildChannel) – The guild channel that got created or deleted.

Connection

discord.on_error(event, *args, **kwargs)

Usually when an event raises an uncaught exception, a traceback is printed to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.

The information of the exception raised and the exception itself can be retrieved with a standard call to sys.exc_info().

If you want exception to propagate out of the Client class you can define an on_error handler consisting of a single empty raise statement. Exceptions raised by on_error will not be handled in any way by Client.

Note

on_error will only be dispatched to Client.event().

It will not be received by Client.wait_for(), or, if used, Bots listeners such as listen() or listener().

Parameters
  • event (str) – The name of the event that raised the exception.

  • args – The positional arguments for the event that raised the exception.

  • kwargs – The keyword arguments for the event that raised the exception.

discord.on_connect()

Called when the client has successfully connected to Discord. This is not the same as the client being fully prepared, see on_ready() for that.

The warnings on on_ready() also apply.

discord.on_shard_connect(shard_id)

Similar to on_connect() except used by AutoShardedClient to denote when a particular shard ID has connected to Discord.

New in version 1.4.

Parameters

shard_id (int) – The shard ID that has connected.

discord.on_disconnect()

Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. This could happen either through the internet being disconnected, explicit calls to close, or Discord terminating the connection one way or the other.

This function can be called many times without a corresponding on_connect() call.

discord.on_shard_disconnect(shard_id)

Similar to on_disconnect() except used by AutoShardedClient to denote when a particular shard ID has disconnected from Discord.

New in version 1.4.

Parameters

shard_id (int) – The shard ID that has disconnected.

discord.on_ready()

Called when the client is done preparing the data received from Discord. Usually after login is successful and the Client.guilds and co. are filled up.

Warning

This function is not guaranteed to be the first event called. Likewise, this function is not guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.

discord.on_shard_ready(shard_id)

Similar to on_ready() except used by AutoShardedClient to denote when a particular shard ID has become ready.

Parameters

shard_id (int) – The shard ID that is ready.

discord.on_resumed()

Called when the client has resumed a session.

discord.on_shard_resumed(shard_id)

Similar to on_resumed() except used by AutoShardedClient to denote when a particular shard ID has resumed a session.

New in version 1.4.

Parameters

shard_id (int) – The shard ID that has resumed.

discord.on_socket_event_type(event_type)

Called whenever a WebSocket event is received from the WebSocket.

This is mainly useful for logging how many events you are receiving from the Discord gateway.

New in version 2.0.

Parameters

event_type (str) – The event type from Discord that is received, e.g. 'READY'.

discord.on_socket_raw_receive(msg)

Called whenever a message is completely received from the WebSocket, before it’s processed and parsed. This event is always dispatched when a complete message is received and the passed data is not parsed in any way.

This is only really useful for grabbing the WebSocket stream and debugging purposes.

This requires setting the enable_debug_events setting in the Client.

Note

This is only for the messages received from the client WebSocket. The voice WebSocket will not trigger this event.

Parameters

msg (str) – The message passed in from the WebSocket library.

discord.on_socket_raw_send(payload)

Called whenever a send operation is done on the WebSocket before the message is sent. The passed parameter is the message that is being sent to the WebSocket.

This is only really useful for grabbing the WebSocket stream and debugging purposes.

This requires setting the enable_debug_events setting in the Client.

Note

This is only for the messages sent from the client WebSocket. The voice WebSocket will not trigger this event.

Parameters

payload – The message that is about to be passed on to the WebSocket library. It can be bytes to denote a binary message or str to denote a regular text message.

Guilds

discord.on_guild_join(guild)

Called when a Guild is either created by the Client or when the Client joins a guild.

This requires Intents.guilds to be enabled.

Parameters

guild (Guild) – The guild that was joined.

discord.on_guild_remove(guild)

Called when a Guild is removed from the Client.

This happens through, but not limited to, these circumstances:

  • The client got banned.

  • The client got kicked.

  • The client left the guild.

  • The client or the guild owner deleted the guild.

In order for this event to be invoked then the Client must have been part of the guild to begin with. (i.e. it is part of Client.guilds)

This requires Intents.guilds to be enabled.

Parameters

guild (Guild) – The guild that got removed.

discord.on_guild_update(before, after)

Called when a Guild is updated, for example:

  • Changed name

  • Changed AFK channel

  • Changed AFK timeout

  • etc.

This requires Intents.guilds to be enabled.

Parameters
  • before (Guild) – The guild prior to being updated.

  • after (Guild) – The guild after being updated.

discord.on_guild_role_create(role)
discord.on_guild_role_delete(role)

Called when a Guild creates or deletes a Role.

To get the guild it belongs to, use Role.guild.

This requires Intents.guilds to be enabled.

Parameters

role (Role) – The role that was created or deleted.

discord.on_guild_role_update(before, after)

Called when a Role is changed guild-wide.

This requires Intents.guilds to be enabled.

Parameters
  • before (Role) – The updated role’s old info.

  • after (Role) – The updated role’s updated info.

discord.on_guild_emojis_update(guild, before, after)

Called when a Guild adds or removes an Emoji.

This requires Intents.emojis_and_stickers to be enabled.

Parameters
  • guild (Guild) – The guild who got their emojis updated.

  • before (Sequence[Emoji]) – A list of emojis before the update.

  • after (Sequence[Emoji]) – A list of emojis after the update.

discord.on_guild_stickers_update(guild, before, after)

Called when a Guild adds or removes a sticker.

This requires Intents.emojis_and_stickers to be enabled.

New in version 2.0.

Parameters
  • guild (Guild) – The guild who got their stickers updated.

  • before (Sequence[GuildSticker]) – A list of stickers before the update.

  • after (Sequence[GuildSticker]) – A list of stickers after the update.

discord.on_guild_available(guild)
discord.on_guild_unavailable(guild)

Called when a guild becomes available or unavailable. The guild must have existed in the Client.guilds cache.

This requires Intents.guilds to be enabled.

Parameters

guild (Guild) – The guild that has changed availability.

discord.on_webhooks_update(channel)

Called whenever a webhook is created, modified, or removed from a guild channel.

This requires Intents.webhooks to be enabled.

Parameters

channel (abc.GuildChannel) – The channel that had its webhooks updated.

Integrations

discord.on_guild_integrations_update(guild)

Called whenever an integration is created, modified, or removed from a guild.

This requires Intents.integrations to be enabled.

New in version 1.4.

Parameters

guild (Guild) – The guild that had its integrations updated.

discord.on_integration_create(integration)

Called when an integration is created.

This requires Intents.integrations to be enabled.

New in version 2.0.

Parameters

integration (Integration) – The integration that was created.

discord.on_integration_update(integration)

Called when an integration is updated.

This requires Intents.integrations to be enabled.

New in version 2.0.

Parameters

integration (Integration) – The integration that was created.

discord.on_raw_integration_delete(payload)

Called when an integration is deleted.

This requires Intents.integrations to be enabled.

New in version 2.0.

Parameters

payload (RawIntegrationDeleteEvent) – The raw event payload data.

Interactions

discord.on_interaction(interaction)

Called when an interaction happened.

This currently happens due to application command invocations or components being used.

Warning

This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the View instead as it provides a nicer user experience.

New in version 2.0.

Parameters

interaction (Interaction) – The interaction data.

Invites

discord.on_invite_create(invite)

Called when an Invite is created. You must have the manage_channels permission to receive this.

New in version 1.3.

Note

There is a rare possibility that the Invite.guild and Invite.channel attributes will be of Object rather than the respective models.

This requires Intents.invites to be enabled.

Parameters

invite (Invite) – The invite that was created.

discord.on_invite_delete(invite)

Called when an Invite is deleted. You must have the manage_channels permission to receive this.

New in version 1.3.

Note

There is a rare possibility that the Invite.guild and Invite.channel attributes will be of Object rather than the respective models.

Outside of those two attributes, the only other attribute guaranteed to be filled by the Discord gateway for this event is Invite.code.

This requires Intents.invites to be enabled.

Parameters

invite (Invite) – The invite that was deleted.

Members/Users

discord.on_member_join(member)
discord.on_member_remove(member)

Called when a Member leaves or joins a Guild.

This requires Intents.members to be enabled.

Parameters

member (Member) – The member who joined or left.

discord.on_member_update(before, after)

Called when a Member updates their profile.

This is called when one or more of the following things change:

  • nickname

  • roles

  • pending

  • communication_disabled_until

  • timed_out

This requires Intents.members to be enabled.

Parameters
  • before (Member) – The updated member’s old info.

  • after (Member) – The updated member’s updated info.

discord.on_presence_update(before, after)

Called when a Member updates their presence.

This is called when one or more of the following things change:

  • status

  • activity

This requires Intents.presences and Intents.members to be enabled.

New in version 2.0.

Parameters
  • before (Member) – The updated member’s old info.

  • after (Member) – The updated member’s updated info.

discord.on_voice_state_update(member, before, after)

Called when a Member changes their VoiceState.

The following, but not limited to, examples illustrate when this event is called:

  • A member joins a voice or stage channel.

  • A member leaves a voice or stage channel.

  • A member is muted or deafened by their own accord.

  • A member is muted or deafened by a guild administrator.

This requires Intents.voice_states to be enabled.

Parameters
  • member (Member) – The member whose voice states changed.

  • before (VoiceState) – The voice state prior to the changes.

  • after (VoiceState) – The voice state after the changes.

discord.on_user_update(before, after)

Called when a User updates their profile.

This is called when one or more of the following things change:

  • avatar

  • username

  • discriminator

This requires Intents.members to be enabled.

Parameters
  • before (User) – The updated user’s old info.

  • after (User) – The updated user’s updated info.

Messages

discord.on_message(message)

Called when a Message is created and sent.

This requires Intents.messages to be enabled.

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that Bot does not have this problem.

Parameters

message (Message) – The current message.

discord.on_message_delete(message)

Called when a message is deleted. If the message is not found in the internal message cache, then this event will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.

If this occurs increase the max_messages parameter or use the on_raw_message_delete() event instead.

This requires Intents.messages to be enabled.

Parameters

message (Message) – The deleted message.

discord.on_bulk_message_delete(messages)

Called when messages are bulk deleted. If none of the messages deleted are found in the internal message cache, then this event will not be called. If individual messages were not found in the internal message cache, this event will still be called, but the messages not found will not be included in the messages list. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.

If this occurs increase the max_messages parameter or use the on_raw_bulk_message_delete() event instead.

This requires Intents.messages to be enabled.

Parameters

messages (List[Message]) – The messages that have been deleted.

discord.on_raw_message_delete(payload)

Called when a message is deleted. Unlike on_message_delete(), this is called regardless of the message being in the internal message cache or not.

If the message is found in the message cache, it can be accessed via RawMessageDeleteEvent.cached_message

This requires Intents.messages to be enabled.

Parameters

payload (RawMessageDeleteEvent) – The raw event payload data.

discord.on_raw_bulk_message_delete(payload)

Called when a bulk delete is triggered. Unlike on_bulk_message_delete(), this is called regardless of the messages being in the internal message cache or not.

If the messages are found in the message cache, they can be accessed via RawBulkMessageDeleteEvent.cached_messages

This requires Intents.messages to be enabled.

Parameters

payload (RawBulkMessageDeleteEvent) – The raw event payload data.

discord.on_message_edit(before, after)

Called when a Message receives an update event. If the message is not found in the internal message cache, then these events will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.

If this occurs increase the max_messages parameter or use the on_raw_message_edit() event instead.

The following non-exhaustive cases trigger this event:

  • A message has been pinned or unpinned.

  • The message content has been changed.

  • The message has received an embed.

    • For performance reasons, the embed server does not do this in a “consistent” manner.

  • The message’s embeds were suppressed or unsuppressed.

  • A call message has received an update to its participants or ending time.

This requires Intents.messages to be enabled.

Parameters
  • before (Message) – The previous version of the message.

  • after (Message) – The current version of the message.

discord.on_raw_message_edit(payload)

Called when a message is edited. Unlike on_message_edit(), this is called regardless of the state of the internal message cache.

If the message is found in the message cache, it can be accessed via RawMessageUpdateEvent.cached_message. The cached message represents the message before it has been edited. For example, if the content of a message is modified and triggers the on_raw_message_edit() coroutine, the RawMessageUpdateEvent.cached_message will return a Message object that represents the message before the content was modified.

Due to the inherently raw nature of this event, the data parameter coincides with the raw data given by the gateway.

Since the data payload can be partial, care must be taken when accessing stuff in the dictionary. One example of a common case of partial data is when the 'content' key is inaccessible. This denotes an “embed” only edit, which is an edit in which only the embeds are updated by the Discord embed server.

This requires Intents.messages to be enabled.

Parameters

payload (RawMessageUpdateEvent) – The raw event payload data.

Reactions

discord.on_reaction_add(reaction, user)

Called when a message has a reaction added to it. Similar to on_message_edit(), if the message is not found in the internal message cache, then this event will not be called. Consider using on_raw_reaction_add() instead.

Note

To get the Message being reacted, access it via Reaction.message.

This requires Intents.reactions to be enabled.

Note

This doesn’t require Intents.members within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using on_raw_reaction_add() if you need this and do not otherwise want to enable the members intent.

Parameters
  • reaction (Reaction) – The current state of the reaction.

  • user (Union[Member, User]) – The user who added the reaction.

discord.on_raw_reaction_add(payload)

Called when a message has a reaction added. Unlike on_reaction_add(), this is called regardless of the state of the internal message cache.

This requires Intents.reactions to be enabled.

Parameters

payload (RawReactionActionEvent) – The raw event payload data.

discord.on_reaction_remove(reaction, user)

Called when a message has a reaction removed from it. Similar to on_message_edit, if the message is not found in the internal message cache, then this event will not be called.

Note

To get the message being reacted, access it via Reaction.message.

This requires both Intents.reactions and Intents.members to be enabled.

Note

Consider using on_raw_reaction_remove() if you need this and do not want to enable the members intent.

Parameters
  • reaction (Reaction) – The current state of the reaction.

  • user (Union[Member, User]) – The user who added the reaction.

discord.on_raw_reaction_remove(payload)

Called when a message has a reaction removed. Unlike on_reaction_remove(), this is called regardless of the state of the internal message cache.

This requires Intents.reactions to be enabled.

Parameters

payload (RawReactionActionEvent) – The raw event payload data.

discord.on_reaction_clear(message, reactions)

Called when a message has all its reactions removed from it. Similar to on_message_edit(), if the message is not found in the internal message cache, then this event will not be called. Consider using on_raw_reaction_clear() instead.

This requires Intents.reactions to be enabled.

Parameters
  • message (Message) – The message that had its reactions cleared.

  • reactions (List[Reaction]) – The reactions that were removed.

discord.on_raw_reaction_clear(payload)

Called when a message has all its reactions removed. Unlike on_reaction_clear(), this is called regardless of the state of the internal message cache.

This requires Intents.reactions to be enabled.

Parameters

payload (RawReactionClearEvent) – The raw event payload data.

discord.on_reaction_clear_emoji(reaction)

Called when a message has a specific reaction removed from it. Similar to on_message_edit(), if the message is not found in the internal message cache, then this event will not be called. Consider using on_raw_reaction_clear_emoji() instead.

This requires Intents.reactions to be enabled.

New in version 1.3.

Parameters

reaction (Reaction) – The reaction that got cleared.

discord.on_raw_reaction_clear_emoji(payload)

Called when a message has a specific reaction removed from it. Unlike on_reaction_clear_emoji() this is called regardless of the state of the internal message cache.

This requires Intents.reactions to be enabled.

New in version 1.3.

Parameters

payload (RawReactionClearEmojiEvent) – The raw event payload data.

Scheduled Events

discord.on_scheduled_event_create(event)

Called when an ScheduledEvent is created.

This requires Intents.scheduled_events to be enabled.

Parameters

event (ScheduledEvent) – The newly created scheduled event.

discord.on_scheduled_event_update(before, after)

Called when a scheduled event is updated.

This requires Intents.scheduled_events to be enabled.

Parameters
discord.on_scheduled_event_delete(event)

Called when a scheduled event is deleted.

This requires Intents.scheduled_events to be enabled.

Parameters

event (ScheduledEvent) – The deleted scheduled event.

discord.on_scheduled_event_user_add(event, member)

Called when a user subscribes to an event. If the member or event is not found in the internal cache, then this event will not be called. Consider using on_raw_scheduled_event_user_add() instead.

This requires Intents.scheduled_events to be enabled.

Parameters
  • event (ScheduledEvent) – The scheduled event subscribed to.

  • member (Member) – The member who subscribed.

discord.on_raw_scheduled_event_user_add(payload)

Called when a user subscribes to an event. Unlike on_scheduled_event_user_add(), this will be called regardless of the state of the internal cache.

This requires Intents.scheduled_events to be enabled.

Parameters

payload (RawScheduledEventSubscription) – The raw event payload data.

discord.on_scheduled_event_user_remove(event, member)

Called when a user unsubscribes to an event. If the member or event is not found in the internal cache, then this event will not be called. Consider using on_raw_scheduled_event_user_remove() instead.

This requires Intents.scheduled_events to be enabled.

Parameters
  • event (ScheduledEvent) – The scheduled event unsubscribed from.

  • member (Member) – The member who unsubscribed.

discord.on_raw_scheduled_event_user_remove(payload)

Called when a user unsubscribes to an event. Unlike on_scheduled_event_user_remove(), this will be called regardless of the state of the internal cache.

This requires Intents.scheduled_events to be enabled.

Parameters

payload (RawScheduledEventSubscription) – The raw event payload data.

Stage Instances

discord.on_stage_instance_create(stage_instance)
discord.on_stage_instance_delete(stage_instance)

Called when a StageInstance is created or deleted for a StageChannel.

New in version 2.0.

Parameters

stage_instance (StageInstance) – The stage instance that was created or deleted.

discord.on_stage_instance_update(before, after)

Called when a StageInstance is updated.

The following, but not limited to, examples illustrate when this event is called:

  • The topic is changed.

  • The privacy level is changed.

New in version 2.0.

Parameters

Threads

discord.on_thread_join(thread)

Called whenever a thread is joined.

<<<<<<< HEAD

Note that you can get the guild from Thread.guild.

This requires Intents.guilds to be enabled.

New in version 2.0.

param thread

The thread that got joined.

type thread

Thread

discord.on_thread_create(thread)

Called whenever a thread is created.

Note that you can get the guild from Thread.guild.

This requires Intents.guilds to be enabled.

New in version 2.0.

Parameters

thread (Thread) – The thread that got created.

discord.on_thread_remove(thread)

Called whenever a thread is removed. This is different from a thread being deleted.

Note that you can get the guild from Thread.guild.

This requires Intents.guilds to be enabled.

Warning

Due to technical limitations, this event might not be called as soon as one expects. Since the library tracks thread membership locally, the API only sends updated thread membership status upon being synced by joining a thread.

New in version 2.0.

Parameters

thread (Thread) – The thread that got removed.

discord.on_thread_delete(thread)

Called whenever a thread is deleted. If the deleted thread isn’t found in internal cache then this will not be called. Archived threads are not in the cache. Consider using on_raw_thread_delete()

Note that you can get the guild from Thread.guild.

This requires Intents.guilds to be enabled.

New in version 2.0.

Parameters

thread (Thread) – The thread that got deleted.

discord.on_raw_thread_delete(payload)

Called whenever a thread is deleted. Unlike on_thread_delete() this is called regardless of the state of the internal cache.

Parameters

payload (RawThreadDeleteEvent) – The raw event payload data.

discord.on_thread_member_join(member)
discord.on_thread_member_remove(member)

Called when a ThreadMember leaves or joins a Thread.

You can get the thread a member belongs in by accessing ThreadMember.thread.

This requires Intents.members to be enabled.

New in version 2.0.

Parameters

member (ThreadMember) – The member who joined or left.

discord.on_thread_update(before, after)

Called whenever a thread is updated.

This requires Intents.guilds to be enabled.

New in version 2.0.

Parameters
  • before (Thread) – The updated thread’s old info.

  • after (Thread) – The updated thread’s new info.

Typing

discord.on_typing(channel, user, when)

Called when someone begins typing a message.

The channel parameter can be a abc.Messageable instance. Which could either be TextChannel, GroupChannel, or DMChannel.

If the channel is a TextChannel then the user parameter is a Member, otherwise it is a User.

This requires Intents.typing to be enabled.

Parameters
  • channel (abc.Messageable) – The location where the typing originated from.

  • user (Union[User, Member]) – The user that started typing.

  • when (datetime.datetime) – When the typing started as an aware datetime in UTC.

discord.on_raw_typing(payload)

Called when someone begins typing a message. Unlike on_typing(), this is called regardless if the user can be found in the bot’s cache or not.

If the typing event is occurring in a guild, the member that started typing can be accessed via RawTypingEvent.member

This requires Intents.typing to be enabled.

Parameters

payload (RawTypingEvent) – The raw typing payload.

Utility Functions

discord.utils.find(predicate, seq)

A helper to return the first element found in the sequence that meets the predicate. For example:

member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)

would find the first Member whose name is ‘Mighty’ and return it. If an entry is not found, then None is returned.

This is different from filter() due to the fact it stops the moment it finds a valid entry.

Parameters
  • predicate – A function that returns a boolean-like result.

  • seq (collections.abc.Iterable) – The iterable to search through.

discord.utils.get(iterable, **attrs)

A helper that returns the first element in the iterable that meets all the traits passed in attrs. This is an alternative for find().

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by x.y) then pass in x__y as the keyword argument.

If nothing is found that matches the attributes passed, then None is returned.

Examples

Basic usage:

member = discord.utils.get(message.guild.members, name='Foo')

Multiple attribute matching:

channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)

Nested attribute matching:

channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')
Parameters
  • iterable – An iterable to search through.

  • **attrs – Keyword arguments that denote attributes to search with.

discord.utils.snowflake_time(id)
Parameters

id (int) – The snowflake ID.

Returns

An aware datetime in UTC representing the creation time of the snowflake.

Return type

datetime.datetime

discord.utils.oauth_url(client_id, *, permissions=..., guild=..., redirect_uri=..., scopes=..., disable_guild_select=False)

A helper function that returns the OAuth2 URL for inviting the bot into guilds.

Parameters
  • client_id (Union[int, str]) – The client ID for your bot.

  • permissions (Permissions) – The permissions you’re requesting. If not given then you won’t be requesting any permissions.

  • guild (Snowflake) – The guild to pre-select in the authorization screen, if available.

  • redirect_uri (str) – An optional valid redirect URI.

  • scopes (Iterable[str]) –

    An optional valid list of scopes. Defaults to ('bot',).

    New in version 1.7.

  • disable_guild_select (bool) –

    Whether to disallow the user from changing the guild dropdown.

    New in version 2.0.

Returns

The OAuth2 URL for inviting the bot into guilds.

Return type

str

discord.utils.remove_markdown(text, *, ignore_links=True)

A helper function that removes markdown characters.

New in version 1.7.

Note

This function is not markdown aware and may remove meaning from the original text. For example, if the input contains 10 * 5 then it will be converted into 10  5.

Parameters
  • text (str) – The text to remove markdown from.

  • ignore_links (bool) – Whether to leave links alone when removing markdown. For example, if a URL in the text contains characters such as _ then it will be left alone. Defaults to True.

Returns

The text with the markdown special characters removed.

Return type

str

discord.utils.escape_markdown(text, *, as_needed=False, ignore_links=True)

A helper function that escapes Discord’s markdown.

Parameters
  • text (str) – The text to escape markdown from.

  • as_needed (bool) – Whether to escape the markdown characters as needed. This means that it does not escape extraneous characters if it’s not necessary, e.g. **hello** is escaped into \*\*hello** instead of \*\*hello\*\*. Note however that this can open you up to some clever syntax abuse. Defaults to False.

  • ignore_links (bool) – Whether to leave links alone when escaping markdown. For example, if a URL in the text contains characters such as _ then it will be left alone. This option is not supported with as_needed. Defaults to True.

Returns

The text with the markdown special characters escaped with a slash.

Return type

str

discord.utils.escape_mentions(text)

A helper function that escapes everyone, here, role, and user mentions.

Note

This does not include channel mentions.

Note

For more granular control over what mentions should be escaped within messages, refer to the AllowedMentions class.

Parameters

text (str) – The text to escape mentions from.

Returns

The text with the mentions removed.

Return type

str

discord.utils.resolve_invite(invite)

Resolves an invite from a Invite, URL or code.

Parameters

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

Returns

The invite code.

Return type

str

discord.utils.resolve_template(code)

Resolves a template code from a Template, URL or code.

New in version 1.4.

Parameters

code (Union[Template, str]) – The code.

Returns

The template code.

Return type

str

await discord.utils.sleep_until(when, result=None)

This function is a coroutine.

Sleep until a specified time.

If the time supplied is in the past this function will yield instantly.

New in version 1.3.

Parameters
  • when (datetime.datetime) – The timestamp in which to sleep until. If the datetime is naive then it is assumed to be local time.

  • result (Any) – If provided is returned to the caller when the coroutine completes.

discord.utils.utcnow()

A helper function to return an aware UTC datetime representing the current time.

This should be preferred to datetime.datetime.utcnow() since it is an aware datetime, compared to the naive datetime in the standard library.

New in version 2.0.

Returns

The current aware datetime in UTC.

Return type

datetime.datetime

discord.utils.format_dt(dt, /, style=None)

A helper function to format a datetime.datetime for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown.

Style

Example Output

Description

t

22:57

Short Time

T

22:57:58

Long Time

d

17/05/2016

Short Date

D

17 May 2016

Long Date

f (default)

17 May 2016 22:57

Short Date Time

F

Tuesday, 17 May 2016 22:57

Long Date Time

R

5 years ago

Relative Time

Note that the exact output depends on the user’s locale setting in the client. The example output presented is using the en-GB locale.

New in version 2.0.

Parameters
  • dt (datetime.datetime) – The datetime to format.

  • style (str) – The style to format the datetime with.

Returns

The formatted string.

Return type

str

discord.utils.as_chunks(iterator, max_size)

A helper function that collects an iterator into chunks of a given size.

New in version 2.0.

Parameters

Warning

The last chunk collected may not be as large as max_size.

Returns

A new iterator which yields chunks of a given size.

Return type

Union[collections.abc.Iterator, collections.abc.AsyncIterator]

discord.utils.time_snowflake(dt, high=False)

Returns a numeric snowflake pretending to be created at the given date.

When using as the lower end of a range, use time_snowflake(high=False) - 1 to be inclusive, high=True to be exclusive.

When using as the higher end of a range, use time_snowflake(high=True) + 1 to be inclusive, high=False to be exclusive

Parameters
  • dt (datetime.datetime) – A datetime object to convert to a snowflake. If naive, the timezone is assumed to be local time.

  • high (bool) – Whether to set the lower 22 bit to high or low.

Returns

The snowflake representing the time given.

Return type

int

discord.utils.generate_snowflake(dt=None)

Returns a numeric snowflake pretending to be created at the given date but more accurate and random than time_snowflake(). If dt is not passed, it makes one from the current time using utcnow.

Parameters

dt (datetime.datetime) – A datetime object to convert to a snowflake. If naive, the timezone is assumed to be local time.

Returns

The snowflake representing the time given.

Return type

int

discord.utils.basic_autocomplete(values)

A helper function to make a basic autocomplete for slash commands. This is a pretty standard autocomplete and will return any options that start with the value from the user, case-insensitive. If the values parameter is callable, it will be called with the AutocompleteContext.

This is meant to be passed into the discord.Option.autocomplete attribute.

Note

Autocomplete cannot be used for options that have specified choices.

Example

Option(str, "color", autocomplete=basic_autocomplete(("red", "green", "blue")))

# or

async def autocomplete(ctx):
    return "foo", "bar", "baz", ctx.interaction.user.name

Option(str, "name", autocomplete=basic_autocomplete(autocomplete))

New in version 2.0.

Parameters

values (Union[Union[Iterable[OptionChoice], Iterable[str], Iterable[int], Iterable[float]], Callable[[AutocompleteContext], Union[Union[Iterable[str], Iterable[int], Iterable[float]], Awaitable[Union[Iterable[str], Iterable[int], Iterable[float]]]]], Awaitable[Union[Iterable[str], Iterable[int], Iterable[float]]]]) – Possible values for the option. Accepts an iterable of str, a callable (sync or async) that takes a single argument of AutocompleteContext, or a coroutine. Must resolve to an iterable of str.

Returns

A wrapped callback for the autocomplete.

Return type

Callable[[AutocompleteContext], Awaitable[Union[Iterable[OptionChoice], Iterable[str], Iterable[int], Iterable[float]]]]

discord.utils.filter_params(params, **kwargs)

A helper function to filter out and replace certain keyword parameters

Parameters
  • params (Dict[str, Any]) – The initial parameters to filter.

  • **kwargs (Dict[str, Optional[str]]) – Key to value pairs where the key’s contents would be moved to the value, or if the value is None, remove key’s contents (see code example).

Example

>>> params = {"param1": 12, "param2": 13}
>>> filter_params(params, param1="param3", param2=None)
{'param3': 12}
# values of 'param1' is moved to 'param3'
# and values of 'param2' are completely removed.

Enumerations

The API provides some enumerations for certain types of strings to avoid the API from being stringly typed in case the strings change in the future.

All enumerations are subclasses of an internal class which mimics the behaviour of enum.Enum.

class discord.SlashCommandOptionType

Specifies the input type of an option.

New in version 2.0.

sub_command

A slash subcommand.

sub_command_group

A slash command group.

string

A string.

integer

An integer.

boolean

A boolean.

user

A user from the current channel. This will be converted to an instance of User in private channels, else Member

channel

A channel from the current guild.

role

A role from the current guild.

mentionable

A mentionable (user or role).

number

A floating number.

attachment

An attachment. Currently in beta.

class discord.ChannelType

Specifies the type of channel.

text

A text channel.

voice

A voice channel.

private

A private text channel. Also called a direct message.

group

A private group text channel.

category

A category channel.

news

A guild news channel.

stage_voice

A guild stage voice channel.

New in version 1.7.

news_thread

A news thread

New in version 2.0.

public_thread

A public thread

New in version 2.0.

private_thread

A private thread

New in version 2.0.

directory

A guild directory entry, used in hub guilds, currently in experiment.

New in version 2.0.

forum

User can only write in threads, similar functionality to a forum, currently in experiment.

New in version 2.0.

class discord.MessageType

Specifies the type of Message. This is used to denote if a message is to be interpreted as a system message or a regular message.

x == y

Checks if two messages are equal.

x != y

Checks if two messages are not equal.

default

The default message type. This is the same as regular messages.

recipient_add

The system message when a user is added to a group private message or a thread.

recipient_remove

The system message when a user is removed from a group private message or a thread.

call

The system message denoting call state, e.g. missed call, started call, etc.

channel_name_change

The system message denoting that a channel’s name has been changed.

channel_icon_change

The system message denoting that a channel’s icon has been changed.

pins_add

The system message denoting that a pinned message has been added to a channel.

new_member

The system message denoting that a new member has joined a Guild.

premium_guild_subscription

The system message denoting that a member has “nitro boosted” a guild.

premium_guild_tier_1

The system message denoting that a member has “nitro boosted” a guild and it achieved level 1.

premium_guild_tier_2

The system message denoting that a member has “nitro boosted” a guild and it achieved level 2.

premium_guild_tier_3

The system message denoting that a member has “nitro boosted” a guild and it achieved level 3.

channel_follow_add

The system message denoting that an announcement channel has been followed.

New in version 1.3.

guild_stream

The system message denoting that a member is streaming in the guild.

New in version 1.7.

guild_discovery_disqualified

The system message denoting that the guild is no longer eligible for Server Discovery.

New in version 1.7.

guild_discovery_requalified

The system message denoting that the guild has become eligible again for Server Discovery.

New in version 1.7.

guild_discovery_grace_period_initial_warning

The system message denoting that the guild has failed to meet the Server Discovery requirements for one week.

New in version 1.7.

guild_discovery_grace_period_final_warning

The system message denoting that the guild has failed to meet the Server Discovery requirements for 3 weeks in a row.

New in version 1.7.

thread_created

The system message denoting that a thread has been created. This is only sent if the thread has been created from an older message. The period of time required for a message to be considered old cannot be relied upon and is up to Discord.

New in version 2.0.

reply

The system message denoting that the author is replying to a message.

New in version 2.0.

application_command

The system message denoting that an application (or “slash”) command was executed.

New in version 2.0.

guild_invite_reminder

The system message sent as a reminder to invite people to the guild.

New in version 2.0.

thread_starter_message

The system message denoting the message in the thread that is the one that started the thread’s conversation topic.

New in version 2.0.

context_menu_command

The system message denoting that an context menu command was executed.

New in version 2.0.

class discord.UserFlags

Represents Discord User flags.

staff

The user is a Discord Employee.

partner

The user is a Discord Partner.

hypesquad

The user is a HypeSquad Events member.

bug_hunter

The user is a Bug Hunter.

mfa_sms

The user has SMS recovery for Multi Factor Authentication enabled.

premium_promo_dismissed

The user has dismissed the Discord Nitro promotion.

hypesquad_bravery

The user is a HypeSquad Bravery member.

hypesquad_brilliance

The user is a HypeSquad Brilliance member.

hypesquad_balance

The user is a HypeSquad Balance member.

early_supporter

The user is an Early Supporter.

team_user

The user is a Team User.

partner_or_verification_application

Relates to partner/verification applications.

system

The user is a system user (i.e. represents Discord officially).

has_unread_urgent_messages

The user has an unread system message.

bug_hunter_level_2

The user is a Bug Hunter Level 2.

verified_bot

The user is a Verified Bot.

verified_bot_developer

The user is an Early Verified Bot Developer.

discord_certified_moderator

The user is a Discord Certified Moderator.

bot_http_interactions

The bot has set an interactions endpoint url.

spammer

The user is disabled for being a spammer.

class discord.ActivityType

Specifies the type of Activity. This is used to check how to interpret the activity itself.

unknown

An unknown activity type. This should generally not happen.

playing

A “Playing” activity type.

streaming

A “Streaming” activity type.

listening

A “Listening” activity type.

watching

A “Watching” activity type.

custom

A custom activity type.

competing

A competing activity type.

New in version 1.5.

class discord.InteractionType

Specifies the type of Interaction.

New in version 2.0.

ping

Represents Discord pinging to see if the interaction response server is alive.

application_command

Represents a slash command interaction.

component

Represents a component based interaction, i.e. using the Discord Bot UI Kit.

auto_complete

Represents a autocomplete interaction for slash commands.

modal_submit

Represents a modal based interaction.

class discord.InteractionResponseType

Specifies the response type for the interaction.

New in version 2.0.

pong

Pongs the interaction when given a ping.

See also InteractionResponse.pong()

channel_message

Respond to the interaction with a message.

See also InteractionResponse.send_message()

deferred_channel_message

Responds to the interaction with a message at a later time.

See also InteractionResponse.defer()

deferred_message_update

Acknowledges the component interaction with a promise that the message will update later (though there is no need to actually update the message).

See also InteractionResponse.defer()

message_update

Responds to the interaction by editing the message.

See also InteractionResponse.edit_message()

auto_complete_result

Responds to the interaction by sending the autocomplete choices.

See also InteractionResponse.send_autocomplete_result()

modal

Responds to the interaction by sending a modal dialog.

See also InteractionResponse.send_modal()

class discord.ComponentType

Represents the component type of a component.

New in version 2.0.

action_row

Represents the group component which holds different components in a row.

button

Represents a button component.

select

Represents a select component.

input_text

Represents an input_text component.

class discord.ButtonStyle

Represents the style of the button component.

New in version 2.0.

primary

Represents a blurple button for the primary action.

secondary

Represents a grey button for the secondary action.

success

Represents a green button for a successful action.

danger

Represents a red button for a dangerous action.

Represents a link button.

blurple

An alias for primary.

grey

An alias for secondary.

gray

An alias for secondary.

green

An alias for success.

red

An alias for danger.

url

An alias for link.

class discord.InputTextStyle

Represents the style of the input text component.

New in version 2.0.

short

Represents a single-line input text field.

long

Represents a multi-line input text field.

singleline

An alias for short.

multiline

An alias for long.

paragraph

An alias for long.

class discord.VoiceRegion

Specifies the region a voice server belongs to.

amsterdam

The Amsterdam region.

brazil

The Brazil region.

dubai

The Dubai region.

New in version 1.3.

eu_central

The EU Central region.

eu_west

The EU West region.

europe

The Europe region.

New in version 1.3.

frankfurt

The Frankfurt region.

hongkong

The Hong Kong region.

india

The India region.

New in version 1.2.

japan

The Japan region.

london

The London region.

russia

The Russia region.

singapore

The Singapore region.

southafrica

The South Africa region.

south_korea

The South Korea region.

sydney

The Sydney region.

us_central

The US Central region.

us_east

The US East region.

us_south

The US South region.

us_west

The US West region.

vip_amsterdam

The Amsterdam region for VIP guilds.

vip_us_east

The US East region for VIP guilds.

vip_us_west

The US West region for VIP guilds.

class discord.VerificationLevel

Specifies a Guild's verification level, which is the criteria in which a member must meet before being able to send messages to the guild.

New in version 2.0.

x == y

Checks if two verification levels are equal.

x != y

Checks if two verification levels are not equal.

x > y

Checks if a verification level is higher than another.

x < y

Checks if a verification level is lower than another.

x >= y

Checks if a verification level is higher or equal to another.

x <= y

Checks if a verification level is lower or equal to another.

none

No criteria set.

low

Member must have a verified email on their Discord account.

medium

Member must have a verified email and be registered on Discord for more than five minutes.

high

Member must have a verified email, be registered on Discord for more than five minutes, and be a member of the guild itself for more than ten minutes.

highest

Member must have a verified phone on their Discord account.

class discord.NotificationLevel

Specifies whether a Guild has notifications on for all messages or mentions only by default.

New in version 2.0.

x == y

Checks if two notification levels are equal.

x != y

Checks if two notification levels are not equal.

x > y

Checks if a notification level is higher than another.

x < y

Checks if a notification level is lower than another.

x >= y

Checks if a notification level is higher or equal to another.

x <= y

Checks if a notification level is lower or equal to another.

all_messages

Members receive notifications for every message regardless of them being mentioned.

only_mentions