API Reference

The following section outlines the API of discord.py-oauth2.

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 discord.py-oauth2.

Clients

Client

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

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

async with x

Asynchronously initialises the client and automatically cleans up.

New in version 2.0.

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.

  • max_lobby_messages (Optional[int]) – The maximum number of lobby messages to store in the internal lobby message cache. This defaults to 1000. Passing in None disables the lobby message cache.

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

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

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

  • intents (Optional[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.

    New in version 1.5.

    Changed in version 2.0: Parameter is now required.

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

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

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

  • sync_presence (Optional[bool]) –

    Whether to keep presences up-to-date across clients. The default behavior is True (what the SDK does).

    New in version 3.0.

  • enable_raw_presences (bool) –

    Whether to manually enable or disable the on_raw_presence_update() event.

    Setting this flag to True requires Intents.presences to be enabled.

    By default, this flag is set to True only when Intents.presences is enabled and Intents.members is disabled, otherwise it’s set to False.

    New in version 2.5.

  • http_trace (aiohttp.TraceConfig) –

    The trace configuration to use for tracking HTTP requests the library does using aiohttp. This allows you to check requests the library is using. For more information, check the aiohttp documentation.

    New in version 2.0.

  • max_ratelimit_timeout (Optional[float]) –

    The maximum number of seconds to wait when a non-global rate limit is encountered. If a request requires sleeping for more than the seconds passed in, then RateLimited will be raised. By default, there is no timeout limit. In order to prevent misuse and unnecessary bans, the minimum value this can be set to is 30.0 seconds.

    New in version 2.0.

  • connector (Optional[aiohttp.BaseConnector]) –

    The aiohttp connector to use for this client. This can be used to control underlying aiohttp behavior, such as setting a DNS resolver or sslcontext.

    New in version 2.5.

  • rpc (Optional[discord.rpc.Client]) –

    The RPC client to upgrade from.

    New in version 3.0.

ws

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

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

property sync_presences

Whether to keep presences up-to-date across clients.

Type

bool

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

Sequence[Guild]

property lobbies

The lobbies that the connected client is a member of.

Type

Sequence[Lobby]

property emojis

The emojis that the connected client has.

Type

Sequence[Emoji]

property stickers

The stickers that the connected client has.

New in version 2.0.

Type

Sequence[GuildSticker]

property sessions

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

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

New in version 3.0.

Type

Sequence[Session]

property soundboard_sounds

The soundboard sounds that the connected client has.

New in version 2.5.

Type

List[SoundboardSound]

property cached_messages

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

New in version 1.1.

Type

Sequence[Message]

property cached_lobby_messages

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

Type

Sequence[LobbyMessage]

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

Sequence[abc.PrivateChannel]

property relationships

Returns all the relationships that the connected client has.

New in version 3.0.

Type

Sequence[Relationship]

property game_relationships

Returns all the game relationships that the connected client has.

New in version 3.0.

Type

Sequence[GameRelationship]

property friends

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

New in version 3.0.

Type

List[Relationship]

property incoming_friend_requests

Returns all the users that the connected client has friend request from.

New in version 3.0.

Type

List[Relationship]

property outgoing_friend_requests

Returns all the users that the connected client has sent friend request to.

New in version 3.0.

Type

List[Relationship]

property game_friends

Returns all the users that the connected client is friends with in-game.

New in version 3.0.

Type

List[GameRelationship]

property incoming_game_friend_requests

Returns all the users that the connected client has game friend request from.

New in version 3.0.

Type

List[GameRelationship]

property outgoing_game_friend_requests

Returns all the users that the connected client has sent game friend request.

New in version 3.0.

Type

List[GameRelationship]

property blocked

Returns all the users that the connected client has blocked.

New in version 3.0.

Type

List[Relationship]

get_game_relationship(user_id, /)

Retrieves the GameRelationship, if applicable.

New in version 3.0.

Parameters

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

Returns

The game relationship, if available.

Return type

Optional[GameRelationship]

get_relationship(user_id, /)

Retrieves the Relationship, if applicable.

New in version 3.0.

Parameters

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

Returns

The relationship, if available.

Return type

Optional[Relationship]

property settings

Returns the user’s settings.

New in version 3.0.

Type

UserSettings

property audio_settings

Returns the manager for user’s audio settings.

New in version 3.0.

Type

AudioSettingsManager

property game_invites

Returns all the game invites that the connected client has received.

New in version 3.0.

Type

Sequence[GameInvite]

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 or after a call to login(). Usually after on_connect() is called.

New in version 2.0.

Type

Optional[int]

property application_name

The client’s application name.

New in version 3.0.

Type

str

property application_flags

The client’s application flags.

New in version 2.0.

Type

ApplicationFlags

property application

The client’s application info.

This is retrieved on login() and is not updated afterwards. This allows populating the application_id without requiring a gateway connection.

This is None if accessed before login() is called.

New in version 2.0.

Type

Optional[AppInfo]

property disclose

The upcoming changes to the user’s account.

New in version 3.0.

Type

Sequence[str]

property av_sf_protocol_floor

The minimum DAVE version. Currently -1.

New in version 3.0.

Type

int

property scopes

The OAuth2 scopes the connected client has.

New in version 3.0.

Type

Tuple[str, …]

is_ready()

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

await before_identify_hook(*, initial=False)

This function is a coroutine.

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

The default implementation sleeps for 5 seconds.

New in version 1.4.

Parameters

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

await setup_hook()

This function is a coroutine.

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

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

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

Warning

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

New in version 2.0.

await login(token=None, *, validate=True)

This function is a coroutine.

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

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

  • validate (bool) –

    Whether to validate the token. Defaults to True. If False, the token will be set as is.

    New in version 3.0.

Raises
  • LoginFailure – The wrong credentials are passed.

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

Returns

The OAuth2 authorization.

New in version 3.0.

Return type

Optional[OAuth2Authorization]

await connect(*, reconnect=True, nonce=None)

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 intents or bad tokens).

  • nonce (Optional[str]) –

    The console connection request nonce.

    New in version 3.0.

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

  • ConnectionClosed – The websocket connection has been terminated.

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

This function is a coroutine.

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

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

  • 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 intents or bad tokens).

  • nonce (Optional[str]) –

    The console connection request nonce.

    New in version 3.0.

Raises

TypeError – An unexpected keyword argument was received.

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

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

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

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

Warning

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

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

  • 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 intents or bad tokens).

  • log_handler (Optional[logging.Handler]) –

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

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

    New in version 2.0.

  • log_formatter (logging.Formatter) –

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

    New in version 2.0.

  • log_level (int) –

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

    New in version 2.0.

  • root_logger (bool) –

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

    Defaults to False.

    New in version 2.0.

  • nonce (Optional[str]) –

    The console connection request nonce.

    New in version 3.0.

await start_device_flow(client_id, *, client_secret=None, scopes=None)

This function is a coroutine.

Starts an OAuth2 device flow.

New in version 3.0.

Parameters
  • client_id (int) – The ID of the application.

  • client_secret (Optional[str]) – The client secret of the application. Required if the application does not have public_oauth2_client flag.

  • scopes (Optional[List[str]]) – A list of scopes to request.

Raises

HTTPException – Starting the OAuth2 device flow failed.

Returns

The flow.

Return type

OAuth2DeviceFlow

await exchange_code(client_id, *, client_secret=None, code=None, code_verifier=None, redirect_uri=None, scopes=None, external_auth_token=None, external_auth_type=None)

This function is a coroutine.

Exchanges a code.

New in version 3.0.

Parameters
  • client_id (int) – The ID of the application.

  • client_secret (Optional[str]) – The client secret of the application. Required if the application does not have public_oauth2_client flag.

  • code (Optional[str]) – The code to exchange.

  • code_verifier (Optional[str]) – The code verifier for the PKCE extension to the code grant.

  • redirect_uri (Optional[str]) – The URL to redirect to after authorization, which must match one of the registered redirect URIs for the application.

  • scopes (Optional[List[str]]) – A list of scopes to request.

  • external_auth_token (Optional[str]) – The external authentication token. If this is provided, then external_auth_type must be provided as well.

  • external_auth_type (Optional[ExternalAuthenticationProviderType]) – The external authentication provider type. If this is provided, then external_auth_token must be provided as well.

Raises

HTTPException – Exchanging the code failed.

Returns

The access token.

Return type

AccessToken

await refresh_access_token(refresh_token, *, client_id, client_secret=None)

This function is a coroutine.

Refreshes an access token.

New in version 3.0.

Parameters
  • refresh_token (str) – The refresh token.

  • client_id (int) – The ID of the application.

  • client_secret (Optional[str]) – The client secret of the application. Required if the application does not have public_oauth2_client flag.

Raises

HTTPException – Refreshing the access token failed.

Returns

The access token.

Return type

AccessToken

await fetch_application_access_token(client_id, client_secret, *, scopes=None)

This function is a coroutine.

Retrieve access token for a team user, or user who owns the requesting application.

New in version 3.0.

Parameters
  • client_id (int) – The ID of the application.

  • client_secret (str) – The client secret of the application.

  • scopes (Optional[List[str]]) – A list of scopes to request.

Raises

HTTPException – Retrieving the access token failed.

Returns

The access token.

Return type

AccessToken

await fetch_provisional_account_token(token, *, external_auth_type, client_id, client_secret=None)

This function is a coroutine.

Retrieves token for a provisional account.

New in version 3.0.

Parameters
  • token (str) – The external authentication token.

  • external_auth_type (Optional[ExternalAuthenticationProviderType]) – The external authentication provider type.

  • client_id (int) – The ID of the application.

  • client_secret (Optional[str]) – The client secret of the application. Required if the application does not have public_oauth2_client flag.

Raises

HTTPException – Retrieving the token for a provisional account failed.

Returns

The access token of the provisional account.

Return type

AccessToken

is_closed()

bool: Indicates if the websocket connection is closed.

property initial_activity

The primary activity set upon logging in.

Note

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

Type

Optional[BaseActivity]

property initial_activities

The activities set upon logging in.

Type

List[BaseActivity]

property initial_status

The status set upon logging in.

Type

Optional[Status]

property status

The user’s overall status.

Type

Status

property raw_status

The user’s overall status as a string value.

Type

str

property client_status

The library’s status.

Type

Status

is_on_mobile()

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

property activities

Returns the activities the client is currently doing.

Note

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

Type

Tuple[Union[BaseActivity, Spotify], …]

property activity

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

Note

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

Note

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

Type

Optional[Union[BaseActivity, Spotify]]

property client_activities

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

Type

Tuple[Union[BaseActivity, Spotify], …]

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]

get_channel(id, /)

Returns a channel or thread with the given ID.

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

Parameters

id (int) – The ID to search for.

Returns

The returned channel or None if not found.

Return type

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

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

Returns a partial messageable with the given destination ID.

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

New in version 2.0.

Parameters
  • id (int) –

    The destination ID to create a partial messageable for.

    Depending on type, ID of specific entity must be passed instead.

    Channel Type

    Entity Type

    private

    User

    lobby

    Lobby

    ephemeral_dm

    User

    Other

    A channel

  • guild_id (Optional[int]) –

    The optional guild ID to create a partial messageable for.

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

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

Returns

The partial messageable.

Return type

PartialMessageable

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.

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

Parameters

id (int) – The ID to search for.

Returns

The guild or None if not found.

Return type

Optional[Guild]

get_user(id, /)

Returns a user with the given ID.

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

Parameters

id (int) – The ID to search for.

Returns

The user or None if not found.

Return type

Optional[User]

get_emoji(id, /)

Returns an emoji with the given ID.

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

Parameters

id (int) – The ID to search for.

Returns

The custom emoji or None if not found.

Return type

Optional[Emoji]

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

Returns a soundboard sound with the given ID.

New in version 2.5.

Parameters

id (int) – The ID to search for.

Returns

The soundboard sound or None if not found.

Return type

Optional[SoundboardSound]

get_lobby(id, /)

Returns a lobby with the given ID.

Parameters

id (int) – The ID to search for.

Returns

The lobby or None if not found.

Return type

Optional[Lobby]

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

This function is a coroutine.

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

Warning

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

dispatch(event, /, *args, **kwargs)

Dispatch an event.

Examples

Dispatch an mention event when client is mentioned in a message:

@client.event
async def on_message(message):
    if client.user.mentioned_in(message):
        client.dispatch('mention', message)

@client.event
async def on_mention(message):
    print(f'I was mentioned in message by {message.author.name}!')
Parameters
  • event (str) – The event to dispatch. Do not prefix this with on_ as library will do it for you.

  • *args (Any) – The event positional arguments.

  • **kwargs (Any) – The event keyword arguments.

event(coro, /)

A decorator that registers an event to listen to.

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

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

Example

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

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

Raises

TypeError – The coroutine passed is not actually a coroutine.

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

This function is a coroutine.

The default error handler provided by the client.

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

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

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

This function is a coroutine.

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the first event that meets the requirements.

Examples

Waiting for a user reply:

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

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

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

Waiting for a thumbs up reaction from the message author:

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

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

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

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

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

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

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

Raises

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

Returns

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

Return type

Any

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

This function is a coroutine.

Changes the client’s presence.

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

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

Example

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

  • activities (List[BaseActivity]) –

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

    New in version 2.0.

  • application_id (Optional[int]) –

    The ID of the application the activities should be associated with.

    New in version 3.0.

  • session_id (Optional[str]) –

    The ID of the Gateway session the activity should be associated with.

    New in version 3.0.

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

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

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

  • edit_settings (bool) –

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

    This should be set to False for idle changes.

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

    New in version 3.0.

  • update_presence (bool) –

    Whether to update presence immediately. This is useful when presence syncing is disabled.

    New in version 3.0.

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

  • ValueError – More than one custom activity was passed.

await create_headless_session(*, activities, application_id=..., token=None)

This function is a coroutine.

Creates, or updates a headless session.

New in version 3.0.

Parameters
  • activities (List[Union[BaseActivity, Spotify], …]) – The activities. This must contain exactly single activity.

  • token (Optional[str]) – The ID of the headless session to update. None denotes creating a new headless session.

Raises

HTTPException – The session token is invalid, or creating or editing the headless session failed.

Returns

The created headless session.

Return type

HeadlessSession

await fetch_connections()

This function is a coroutine.

Retrieves list of your Connections.

New in version 3.0.

Raises
  • Forbidden – You do not have proper permissions to retrieve your connections.

  • HTTPException – Retrieving connections failed.

Returns

The retrieved connections.

Return type

List[Connection]

async for ... in fetch_guilds(*, limit=200, before=None, after=None, with_counts=True)

Retrieves an asynchronous iterator that enables receiving your guilds.

Note

Using this, you will only receive UserGuild.is_owner, UserGuild.icon, UserGuild.id, UserGuild.name, UserGuild.approximate_member_count, and UserGuild.approximate_presence_count per UserGuild.

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 = [guild async for guild in client.fetch_guilds(limit=150)]
# guilds is now a list of UserGuild...

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

    Changed in version 2.0: The default has been changed to 200.

  • before (Union[abc.Snowflake, 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]) – 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.

  • with_counts (bool) –

    Whether to include count information in the guilds. This fills the UserGuild.approximate_member_count and UserGuild.approximate_presence_count attributes without needing any privileged intents. Defaults to True.

    New in version 2.3.

Raises

HTTPException – Getting the guilds failed.

Yields

UserGuild – The guild with the guild data parsed.

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 create_harvest(email)

This function is a coroutine.

Creates an user data harvest request.

New in version 3.0.

Parameters

email (str) – The email to send harvest to.

Raises
  • Forbidden – You are not allowed to create the user data harvest request.

  • HTTPException – Creating the user data harvest request failed.

Returns

The created harvest.

Return type

Harvest

await fetch_harvest()

This function is a coroutine.

Retrieves user’s harvest, if any.

Raises
  • Forbidden – You are not allowed to retrieve user’s harvest.

  • HTTPException – Getting the user’s harvest failed.

Returns

The user’s harvest.

Return type

Optional[Harvest]

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

This function is a coroutine.

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

Note

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

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

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

  • scheduled_event_id (Optional[int]) –

    The ID of the scheduled event this invite is for.

    Note

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

    New in version 2.0.

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

  • NotFound – The invite has expired or is invalid.

  • HTTPException – Getting the invite failed.

Returns

The invite from the URL/ID.

Return type

Invite

await create_or_join_lobby(secret, *, lobby_metadata=None, member_metadata=None, idle_timeout=None)

This function is a coroutine.

Creates or joins an existing lobby by secret.

Parameters
  • secret (str) – The secret for joining/creating a lobby.

  • lobby_metadata (Optional[Dict[str, str]]) – The lobby’s metadata. Must be 1000 characters in total (length of keys + values).

  • member_metadata (Optional[Dict[str, str]]) – The member’s metadata to assign to yourself. Must be 1000 characters in total (length of keys + values).

  • idle_timeout (Optional[int]) –

    The seconds to wait before shutting down a lobby after it becomes idle. Must be between 5 seconds and 1 week.

    Defaults to 5 minutes if not provided.

Raises
  • Forbidden – You do not have proper permissions to join lobby.

  • HTTPException – Creating/joining the lobby failed.

Returns

The joined or created lobby.

Return type

Lobby

await create_game_invite(recipient, *, launch_parameters, game_name, game_icon_url, fallback_url=..., ttl=...)

This function is a coroutine.

Creates a game invite for specified user.

The Bearer token must be associated with Xbox application (ID: 622174530214821906).

Parameters
  • recipient (User) – The user to create game invite for.

  • launch_parameters (Union[str, dict]) –

    The parameters for launching game. Typically this is a JSON string containing two optional and nullable string keys:

    • titleId: The ID of the game invite title.

    • inviteToken: The token of the game invite.

  • game_name (str) – The name of the game. Must be between 2 and 128 characters.

  • game_icon_url (str) – The URL of the game icon.

  • fallback_url (Optional[str]) – The URL for installing the game.

  • ttl (Optional[int]) – Duration in seconds when game invite should expire in. Must be between 300 (5 minutes) and 86400 (1 day). Defaults to 900 (15 minutes).

Raises
  • Forbidden – You are not allowed to send game invite to this user.

  • HTTPException – Sending the game invite failed.

Returns

The game invite created.

Return type

GameInvite

await fetch_skus()

This function is a coroutine.

Retrieves the application’s available SKUs.

New in version 2.4.

Raises
Returns

The application’s available SKUs.

Return type

List[SKU]

await fetch_entitlement(entitlement_id, /)

This function is a coroutine.

Retrieves a Entitlement with the specified ID.

New in version 2.4.

Parameters

entitlement_id (int) – The entitlement’s ID to fetch from.

Raises
Returns

The entitlement you requested.

Return type

Entitlement

async for ... in entitlements(*, limit=100, before=None, after=None, skus=None, user=None, guild=None, exclude_ended=False, exclude_deleted=True)

Retrieves an asynchronous iterator of the Entitlement that applications has.

New in version 2.4.

Examples

Usage

async for entitlement in client.entitlements(limit=100):
    print(entitlement.user_id, entitlement.ends_at)

Flattening into a list

entitlements = [entitlement async for entitlement in client.entitlements(limit=100)]
# entitlements is now a list of Entitlement...

All parameters are optional.

Parameters
  • limit (Optional[int]) – The number of entitlements to retrieve. If None, it retrieves every entitlement for this application. Note, however, that this would make it a slow operation. Defaults to 100.

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

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

  • skus (Optional[Sequence[Snowflake]]) – A list of SKUs to filter by.

  • user (Optional[Snowflake]) – The user to filter by.

  • guild (Optional[Snowflake]) – The guild to filter by.

  • exclude_ended (bool) – Whether to exclude ended entitlements. Defaults to False.

  • exclude_deleted (bool) –

    Whether to exclude deleted entitlements. Defaults to True.

    New in version 2.5.

Raises
  • MissingApplicationID – The application ID could not be found.

  • HTTPException – Fetching the entitlements failed.

  • TypeError – Both after and before were provided, as Discord does not support this type of pagination.

Yields

Entitlement – The entitlement with the application.

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

This function is a coroutine.

Changes client’s private channel voice state.

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

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

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

  • self_video (bool) – Indicates if the client should show camera.

await fetch_preferred_rtc_regions()

This function is a coroutine.

Retrieves the preferred RTC regions of the client.

Raises

HTTPException – Retrieving the preferred voice regions failed.

Returns

The region name and list of IPs for the closest voice regions.

Return type

Dict[str, List[str]]

await fetch_widget(guild_id, /)

This function is a coroutine.

Gets a Widget from a guild ID.

Note

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

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

Parameters

guild_id (int) – The ID of the guild.

Raises
Returns

The guild’s widget.

Return type

Widget

await fetch_game_relationships()

This function is a coroutine.

Retrieves all your game relationships.

Note

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

Raises

HTTPException – Retrieving your game relationships failed.

Returns

All your game relationships.

Return type

List[GameRelationship]

await fetch_relationships()

This function is a coroutine.

Retrieves all your relationships.

Note

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

Note

This methods returns only relationships of friend type.

Raises

HTTPException – Retrieving your relationships failed.

Returns

All your relationships.

Return type

List[Relationship]

await send_friend_request(*args)

This function is a coroutine.

Sends a friend request to another user.

This function can be used in multiple ways.

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

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

# Passing a legacy user:
await client.send_friend_request('Dolfies#0040')

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

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

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

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

  • HTTPException – Sending the friend request failed.

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

await send_game_friend_request(user)

This function is a coroutine.

Sends a game friend request to another user.

This function can be used in multiple ways.

# Passing an user object:
await client.send_game_friend_request(user)

# Passing an username
await client.send_game_friend_request('gatewaydisc.rdgg')

# Passing an ID
await client.send_game_friend_request(1073325901825187841)
Parameters

user (Union[discord.User, str, int]) – The user to send the game friend request to.

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

  • HTTPException – Sending the game friend request failed.

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

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

Union[DMChannel, EphemeralDMChannel]

await fetch_presences()

This function is a coroutine.

Retrieve presences for all your relationships.

Raises
await fetch_presences_for_xbox()

This function is a coroutine.

Retrieve presences for all your relationships and people who are in voice channel.

The Bearer token must be associated with Xbox application (ID: 622174530214821906).

Raises
await fetch_detectable_applications()

This function is a coroutine.

Retrieves applications detectable by desktop clients.

Raises

HTTPException – Retrieving detectable applications failed.

Returns

The detectable applications.

Return type

List[DetectableApplication]

Dispatcher

Methods
class discord.Dispatcher(*, logger)

A mixin to implement discord.py event system.

New in version 3.0.

@event

A decorator that registers an event to listen to.

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

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

Example

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

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

Raises

TypeError – The coroutine passed is not actually a coroutine.

dispatch(event, /, *args, **kwargs)

Dispatch an event.

Examples

Dispatch an mention event when client is mentioned in a message:

@client.event
async def on_message(message):
    if client.user.mentioned_in(message):
        client.dispatch('mention', message)

@client.event
async def on_mention(message):
    print(f'I was mentioned in message by {message.author.name}!')
Parameters
  • event (str) – The event to dispatch. Do not prefix this with on_ as library will do it for you.

  • *args (Any) – The event positional arguments.

  • **kwargs (Any) – The event keyword arguments.

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

This function is a coroutine.

The default error handler provided by the client.

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

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

Impersonate

class discord.Impersonate

An ABC that details client properties values and how to impersonate client.

The following implement this ABC:

Client properties are used for analytics and anti-abuse systems. See documentation for details.

New in version 3.0.

await setup()

This function is a coroutine.

Called when client properties need to be set.

get_client_properties(*, nonce=None)

This function could be a coroutine.

Return client properties as dict.

Parameters

nonce (Optional[str]) – The nonce.

get_client_properties_base64()

This function could be a coroutine.

Return client properties as base64-encoded str.

get_http_user_agent()

This function could be a coroutine.

Return user agent used to make HTTP requests.

get_http_initial_headers()

This function could be a coroutine.

Return initial headers used to make HTTP request.

get_websocket_user_agent()

This function could be a coroutine.

Return user agent used to make WebSocket connection.

get_websocket_initial_headers()

This function could be a coroutine.

Return initial headers used to make WebSocket connection.

DefaultImpersonate

class discord.DefaultImpersonate(*, os=None)

A default implementation of Impersonate.

user_agent

The user agent used to make HTTP requests.

Type

str

websocket_user_agent

The user agent used to make WebSocket connections.

Type

str

Parameters

os (Optional[ClientOperatingSystem]) – The operating system to send in properties.

property gateway_value

The client properties sent over Gateway.

Type

Mapping[str, Any]

property http_value

The client properties sent over HTTP.

Modifying anything in returned object will automatically update headers.

Type

Mapping[str, Any]

put(key, value, *, at='both')

Put a super property.

Parameters
  • key (str) – The key to insert super property at.

  • value (Any) – The value to insert.

  • at (str) –

    Must be one of:

    • 'both': Put super property to Gateway and HTTP properties.

    • 'gateway': Put super property only to Gateway properties.

    • 'http': Put super property only to HTTP properties.

Returns

This instance for chaining.

Return type

Self

without(*keys, at='both')

Remove super properties.

Parameters
  • *keys (str) – The keys to remove from super properties.

  • at (str) –

    Must be one of:

    • 'both': Remove super properties from Gateway and HTTP properties.

    • 'gateway': Remove super properties only from Gateway properties.

    • 'http': Remove super properties only from HTTP properties.

Returns

This instance for chaining.

Return type

Self

with_user_agent(value, /)

Sets HTTP user agent to provided value.

with_websocket_user_agent(value, /)

Sets WebSocket user agent to provided value.

get_client_properties(*, nonce=None)

This function could be a coroutine.

Return client properties as dict.

Parameters

nonce (Optional[str]) – The nonce.

get_client_properties_base64()

This function could be a coroutine.

Return client properties as base64-encoded str.

get_http_user_agent()

This function could be a coroutine.

Return user agent used to make HTTP requests.

get_http_initial_headers()

This function could be a coroutine.

Return initial headers used to make HTTP request.

get_websocket_user_agent()

This function could be a coroutine.

Return user agent used to make WebSocket connection.

get_websocket_initial_headers()

This function could be a coroutine.

Return initial headers used to make WebSocket connection.

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

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]

tags

The list of tags describing the functionality of the application.

New in version 2.0.

Type

List[str]

custom_install_url

The custom authorization URL for the application, if enabled.

New in version 2.0.

Type

List[str]

install_params

The settings for custom authorization URL of application, if enabled.

New in version 2.0.

Type

Optional[AppInstallParams]

role_connections_verification_url

The application’s connection verification URL which will render the application as a verification method in the guild’s role verification configuration.

New in version 2.2.

Type

Optional[str]

interactions_endpoint_url

The interactions endpoint url of the application to receive interactions over this endpoint rather than over the gateway, if configured.

New in version 2.4.

Type

Optional[str]

redirect_uris

A list of authentication redirect URIs.

New in version 2.4.

Type

List[str]

approximate_guild_count

The approximate count of the guilds the bot was added to.

New in version 2.4.

Type

int

approximate_user_install_count

The approximate count of the user-level installations the bot has.

New in version 2.5.

Type

Optional[int]

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]

property flags

The application’s flags.

New in version 2.0.

Type

ApplicationFlags

property guild_integration_config

The default settings for the application’s installation context in a guild.

New in version 2.5.

Type

Optional[IntegrationTypeConfig]

property user_integration_config

The default settings for the application’s installation context as a user.

New in version 2.5.

Type

Optional[IntegrationTypeConfig]

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

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]

approximate_guild_count

The approximate count of the guilds the bot was added to.

New in version 2.3.

Type

int

redirect_uris

A list of authentication redirect URIs.

New in version 2.3.

Type

List[str]

interactions_endpoint_url

The interactions endpoint url of the application to receive interactions over this endpoint rather than over the gateway, if configured.

New in version 2.3.

Type

Optional[str]

role_connections_verification_url

The application’s connection verification URL which will render the application as a verification method in the guild’s role verification configuration.

New in version 2.3.

Type

Optional[str]

property icon

Retrieves the application’s icon asset, if any.

Type

Optional[Asset]

property cover_image

Retrieves the cover image of the application’s default rich presence.

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

New in version 2.3.

Type

Optional[Asset]

property flags

The application’s flags.

New in version 2.0.

Type

ApplicationFlags

AppInstallParams

Attributes
class discord.AppInstallParams

Represents the settings for custom authorization URL of an application.

New in version 2.0.

scopes

The list of OAuth2 scopes to add the application to a guild with.

Type

List[str]

permissions

The permissions to give to application in the guild.

Type

Permissions

IntegrationTypeConfig

class discord.IntegrationTypeConfig

Represents the default settings for the application’s installation context.

New in version 2.5.

oauth2_install_params

The install params for this installation context’s default in-app authorization link.

Type

Optional[AppInstallParams]

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 handle (e.g. name or name#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 a legacy concept that is no longer used.

Type

str

global_name

The team member’s global nickname, taking precedence over the username in display.

New in version 2.3.

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

role

The role of the member within the team.

New in version 2.4.

Type

TeamMemberRole

property accent_color

Returns the user’s accent color, if applicable.

A user’s accent color is only shown if they do not have a banner. This will only be available if the user explicitly sets a color.

There is an alias for this named accent_colour.

New in version 2.0.

Note

This information is only available via discord.Client.fetch_user().

Type

Optional[discord.Color]

property accent_colour

Returns the user’s accent colour, if applicable.

A user’s accent colour is only shown if they do not have a banner. This will only be available if the user explicitly sets a colour.

This is an alias of accent_color.

New in version 2.0.

Note

This information is only available via discord.Client.fetch_user().

Type

Optional[discord.Color]

property avatar

Returns an Asset for the avatar the user has.

If the user has not uploaded a global avatar, None is returned. If you want the avatar that a user has displayed, consider display_avatar.

Type

Optional[discord.Asset]

property avatar_decoration

Returns an Asset for the avatar decoration the user has.

If the user has not set an avatar decoration, None is returned.

New in version 2.4.

Type

Optional[discord.Asset]

property avatar_decoration_sku_id

Returns the SKU ID of the avatar decoration the user has.

If the user has not set an avatar decoration, None is returned.

New in version 2.4.

Type

Optional[int]

property banner

Returns the user’s banner asset, if available.

New in version 2.0.

Note

This information is only available via discord.Client.fetch_user().

Type

Optional[discord.Asset]

property color

A property that returns a color denoting the rendered color for the user. This always returns Color.default().

There is an alias for this named colour.

Type

discord.Color

property colour

A property that returns a colour denoting the rendered colour for the user. This always returns Colour.default().

This is an alias of color.

Type

discord.Colour

property created_at

Returns the user’s creation time in UTC.

This is when the user’s Discord account was created.

Type

datetime.datetime

property default_avatar

Returns the default avatar for a given user.

Type

discord.Asset

property display_avatar

Returns the user’s display avatar.

For regular users this is just their default avatar or uploaded avatar.

New in version 2.0.

Type

discord.Asset

property display_name

Returns the user’s display name.

For regular users this is just their global name or their username, but if they have a guild specific nickname then that is returned instead.

Type

str

property game_relationship

Returns the GameRelationship with this user if applicable, None otherwise.

Type

Optional[GameRelationship]

is_blocked()

bool: Checks if the user is blocked.

is_friend()

bool: Checks if the user is your friend.

is_game_friend()

bool: Checks if the user is your friend in-game.

is_ignored()

bool: Checks if the user is ignored.

property mention

Returns a string that allows you to mention the given user.

Type

str

mentioned_in(message)

Checks if the user is mentioned in the specified message.

Parameters

message (discord.Message) – The message to check if you’re mentioned in.

Returns

Indicates if the user is mentioned in the message.

Return type

bool

property primary_guild

Returns the user’s primary guild.

Type

discord.PrimaryGuild

property public_flags

The publicly available flags the user has.

Type

discord.PublicUserFlags

property relationship

Returns the Relationship with this user if applicable, None otherwise.

Type

Optional[Relationship]

property voice

Returns the user’s current voice state.

Type

Optional[discord.VoiceState]

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

App Commands

discord.on_raw_app_command_permissions_update(payload)

Called when application command permissions are updated.

New in version 2.0.

Parameters

payload (RawAppCommandPermissionsUpdateEvent) – The raw event payload data.

discord.on_app_command_completion(interaction, command)

Called when a app_commands.Command or app_commands.ContextMenu has successfully completed without error.

New in version 2.0.

Parameters
  • interaction (Interaction) – The interaction of the command.

  • command (Union[app_commands.Command, app_commands.ContextMenu]) – The command that completed successfully

AutoMod

discord.on_automod_rule_create(rule)

Called when a AutoModRule is created. You must have manage_guild to receive this.

This requires Intents.auto_moderation_configuration to be enabled.

New in version 2.0.

Parameters

rule (AutoModRule) – The rule that was created.

discord.on_automod_rule_update(rule)

Called when a AutoModRule is updated. You must have manage_guild to receive this.

This requires Intents.auto_moderation_configuration to be enabled.

New in version 2.0.

Parameters

rule (AutoModRule) – The rule that was updated.

discord.on_automod_rule_delete(rule)

Called when a AutoModRule is deleted. You must have manage_guild to receive this.

This requires Intents.auto_moderation_configuration to be enabled.

New in version 2.0.

Parameters

rule (AutoModRule) – The rule that was deleted.

discord.on_automod_action(execution)

Called when a AutoModAction is created/performed. You must have manage_guild to receive this.

This requires Intents.auto_moderation_execution to be enabled.

New in version 2.0.

Parameters

execution (AutoModAction) – The rule execution that was performed.

Channels

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

Called whenever a guild channel is created or deleted.

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.

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_private_channel_create(channel)
discord.on_private_channel_delete(channel)

Called whenever a private channel is created or deleted.

This requires Intents.private_channels to be enabled.

Parameters

channel (abc.PrivateChannel) – The private channel that got created or deleted.

discord.on_private_channel_update(before, after)

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

This requires Intents.private_channels to be enabled.

Parameters
discord.on_private_channel_delete(channel)

Called whenever a private channel is deleted.

This requires Intents.private_channels to be enabled.

Parameters

after – The deleted private channel.

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

If the channel or user could not be found in the internal cache this event will not be called, you may use on_raw_typing() instead.

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 of the channel and user being in the internal cache.

This requires Intents.typing to be enabled.

New in version 2.0.

Parameters

payload (RawTypingEvent) – The raw event payload data.

Connection

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

Debug

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

Usually when an event raises an uncaught exception, a traceback is logged 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().

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

Changed in version 2.0: The traceback is now logged rather than printed.

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_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 (Union[bytes, str]) – 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.

Entitlements

discord.on_entitlement_create(entitlement)

Called when a user subscribes to a SKU.

New in version 2.4.

Parameters

entitlement (Entitlement) – The entitlement that was created.

discord.on_entitlement_update(entitlement)

Called when a user updates their subscription to a SKU. This is usually called when the user renews or cancels their subscription.

New in version 2.4.

Parameters

entitlement (Entitlement) – The entitlement that was updated.

discord.on_entitlement_delete(entitlement)

Called when a users subscription to a SKU is cancelled. This is typically only called when:

  • Discord issues a refund for the subscription.

  • Discord removes an entitlement from a user.

Warning

This event won’t be called if the user cancels their subscription manually, instead on_entitlement_update() will be called with Entitlement.ends_at set to the end of the current billing period.

New in version 2.4.

Parameters

entitlement (Entitlement) – The entitlement that was deleted.

Gateway

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

Called when the client has resumed a session.

Relationships

discord.on_relationship_add(relationship)
discord.on_relationship_remove(relationship)

Called when a Relationship is added or removed from the ClientUser.

This requires Intents.relationships to be enabled.

Parameters

relationship (Relationship) – The relationship that was added or removed.

discord.on_relationship_update(before, after)

Called when a Relationship is updated, e.g. when you block a friend or a friendship is accepted.

This requires Intents.relationships to be enabled.

Parameters
discord.on_game_relationship_add(relationship)
discord.on_game_relationship_remove(relationship)

Called when a GameRelationship is added or removed from the ClientUser.

This requires Intents.relationships to be enabled.

Parameters

relationship (GameRelationship) – The game relationship that was added or removed.

discord.on_game_relationship_update(before, after)

Called when a GameRelationship is updated, e.g. when you accept a friend request.

This requires Intents.relationships to be enabled.

Parameters

Calls

discord.on_call_create(call)
discord.on_call_delete(call)

Called when a call is created in a abc.PrivateChannel.

This requires Intents.calls to be enabled.

Parameters

call (Union[PrivateCall, GroupCall]) – The call that was created or deleted.

discord.on_call_update(before, after)

Called when a PrivateCall or GroupCall is updated, e.g. when a member is added or another person is rung.

This requires Intents.calls to be enabled.

Parameters

Guilds

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 – The Guild that has changed availability.

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 updates, 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_emojis_update(guild, before, after)

Called when a Guild adds or removes 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 updates its stickers.

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_audit_log_entry_create(entry)

Called when a Guild gets a new audit log entry. You must have view_audit_log to receive this.

This requires Intents.moderation to be enabled.

New in version 2.2.

Warning

Audit log entries received through the gateway are subject to data retrieval from cache rather than REST. This means that some data might not be present when you expect it to be. For example, the AuditLogEntry.target attribute will usually be a discord.Object and the AuditLogEntry.user attribute will depend on user and member cache.

To get the user ID of entry, AuditLogEntry.user_id can be used instead.

Parameters

entry (AuditLogEntry) – The audit log entry that was created.

discord.on_invite_create(invite)

Called when an Invite is created. You must have manage_channels 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 manage_channels 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.

Integrations

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

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

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.

Lobbies

discord.on_lobby_create(lobby)
discord.on_lobby_delete(lobby)

Called when a lobby is created or deleted.

New in version 3.0.

on_lobby_create() requires Intents.lobbies to be enabled. on_lobby_delete() requires Intents.lobby_delete to be enabled.

Parameters

lobby (Lobby) – The lobby that got created or deleted.

discord.on_lobby_update(before, after)

Called when a lobby is updated.

This requires Intents.lobbies to be enabled.

New in version 3.0.

Parameters
  • before (Lobby) – The updated lobby’s old info.

  • after (Lobby) – The updated lobby’s updated info.

discord.on_lobby_update(before, after)

Called when a lobby is updated.

This requires Intents.lobbies to be enabled.

New in version 3.0.

Parameters
  • before (Lobby) – The updated lobby’s old info.

  • after (Lobby) – The updated lobby’s updated info.

Members

discord.on_member_join(member)

Called when a Member joins a Guild.

This requires Intents.members to be enabled.

Parameters

member (Member) – The member who joined.

discord.on_member_remove(member)

Called when a Member leaves a Guild.

If the guild or member could not be found in the internal cache this event will not be called, you may use on_raw_member_remove() instead.

This requires Intents.members to be enabled.

Parameters

member (Member) – The member who left.

discord.on_raw_member_remove(payload)

Called when a Member leaves a Guild.

Unlike on_member_remove() this is called regardless of the guild or member being in the internal cache.

This requires Intents.members to be enabled.

New in version 2.0.

Parameters

payload (RawMemberRemoveEvent) – The raw event payload data.

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

  • timeout

  • guild avatar

  • flags

Due to a Discord limitation, this event is not dispatched when a member’s timeout expires.

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

discord.on_member_ban(guild, user)

Called when a user gets banned from a Guild.

This requires Intents.moderation 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.moderation to be enabled.

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

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

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_raw_presence_update(payload)

Called when a Member updates their presence.

This requires Intents.presences to be enabled.

Unlike on_presence_update(), when enabled, this is called regardless of the state of internal guild and member caches, and does not provide a comparison between the previous and updated states of the Member.

Important

By default, this event is only dispatched when Intents.presences is enabled and Intents.members is disabled.

You can manually override this behaviour by setting the enable_raw_presences flag in the Client, however Intents.presences is always required for this event to work.

New in version 2.5.

Parameters

payload (Presence) – The raw presence update event model.

Messages

discord.on_message(message)

Called when a Message is created and sent.

This requires Intents.messages to be enabled.

Warning

Your client’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your client was programmed. If you want the client 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_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_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_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.

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.

Polls

discord.on_poll_vote_add(user, answer)
discord.on_poll_vote_remove(user, answer)

Called when a Poll gains or loses a vote. If the user or answer’s poll parent message are not cached then this event will not be called.

This requires Intents.message_content and Intents.polls to be enabled.

Note

If the poll allows multiple answers and the user removes or adds multiple votes, this event will be called as many times as votes that are added or removed.

New in version 2.4.

Parameters
  • user (Union[User, Member]) – The user that performed the action.

  • answer (PollAnswer) – The answer the user voted or removed their vote from.

discord.on_raw_poll_vote_add(payload)
discord.on_raw_poll_vote_remove(payload)

Called when a Poll gains or loses a vote. Unlike on_poll_vote_add() and on_poll_vote_remove() this is called regardless of the state of the internal user and message cache.

This requires Intents.message_content and Intents.polls to be enabled.

Note

If the poll allows multiple answers and the user removes or adds multiple votes, this event will be called as many times as votes that are added or removed.

New in version 2.4.

Parameters

payload (RawPollVoteActionEvent) – 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.

Warning

This event does not have a way of differentiating whether a reaction is a burst reaction (also known as “super reaction”) or not. If you need this, consider using on_raw_reaction_add() instead.

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

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

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.

Warning

This event does not have a way of differentiating whether a reaction is a burst reaction (also known as “super reaction”) or not. If you need this, consider using on_raw_reaction_remove() instead.

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

  • user (Union[Member, User]) – The user whose reaction was removed.

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

Roles

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

Called when a Guild creates or deletes a new 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.

Scheduled Events

discord.on_scheduled_event_create(event)
discord.on_scheduled_event_delete(event)

Called when a ScheduledEvent is created or deleted.

This requires Intents.guild_scheduled_events to be enabled.

New in version 2.0.

Parameters

event (ScheduledEvent) – The scheduled event that was created or deleted.

discord.on_scheduled_event_update(before, after)

Called when a ScheduledEvent is updated.

This requires Intents.guild_scheduled_events to be enabled.

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

  • The scheduled start/end times are changed.

  • The channel is changed.

  • The description is changed.

  • The status is changed.

  • The image is changed.

New in version 2.0.

Parameters
discord.on_scheduled_event_user_add(event, user)
discord.on_scheduled_event_user_remove(event, user)

Called when a user is added or removed from a ScheduledEvent.

This requires Intents.guild_scheduled_events to be enabled.

New in version 2.0.

Parameters
  • event (ScheduledEvent) – The scheduled event that the user was added or removed from.

  • user (User) – The user that was added or removed.

Soundboard

discord.on_soundboard_sound_create(sound)
discord.on_soundboard_sound_delete(sound)

Called when a SoundboardSound is created or deleted.

New in version 2.5.

Parameters

sound (SoundboardSound) – The soundboard sound that was created or deleted.

discord.on_soundboard_sound_update(before, after)

Called when a SoundboardSound is updated.

The following examples illustrate when this event is called:

  • The name is changed.

  • The emoji is changed.

  • The volume is changed.

New in version 2.5.

Parameters

sound (SoundboardSound) – The soundboard sound that was updated.

Stages

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

Subscriptions

discord.on_subscription_create(subscription)

Called when a subscription is created.

New in version 2.5.

Parameters

subscription (Subscription) – The subscription that was created.

discord.on_subscription_update(subscription)

Called when a subscription is updated.

New in version 2.5.

Parameters

subscription (Subscription) – The subscription that was updated.

discord.on_subscription_delete(subscription)

Called when a subscription is deleted.

New in version 2.5.

Parameters

subscription (Subscription) – The subscription that was deleted.

Threads

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

discord.on_thread_join(thread)

Called whenever a thread is joined.

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

discord.on_thread_update(before, after)

Called whenever a thread is updated. If the thread could not be found in the internal cache this event will not be called. Threads will not be in the cache if they are archived.

If you need this information use on_raw_thread_update() instead.

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.

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 thread could not be found in the internal cache this event will not be called. Threads will not be in the cache if they are archived.

If you need this information use on_raw_thread_delete() instead.

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_update(payload)

Called whenever a thread is updated. Unlike on_thread_update() this is called regardless of the thread being in the internal thread cache or not.

This requires Intents.guilds to be enabled.

New in version 2.0.

Parameters

payload (RawThreadUpdateEvent) – The raw event payload data.

discord.on_raw_thread_delete(payload)

Called whenever a thread is deleted. Unlike on_thread_delete() this is called regardless of the thread being in the internal thread cache or not.

This requires Intents.guilds to be enabled.

New in version 2.0.

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_raw_thread_member_remove(payload)

Called when a ThreadMember leaves a Thread. Unlike on_thread_member_remove() this is called regardless of the member being in the internal thread’s members cache or not.

This requires Intents.members to be enabled.

New in version 2.0.

Parameters

payload (RawThreadMembersUpdate) – The raw event payload data.

Voice

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_voice_channel_effect(effect)

Called when a Member sends a VoiceChannelEffect in a voice channel the bot is in.

This requires Intents.voice_states to be enabled.

New in version 2.5.

Parameters

effect (VoiceChannelEffect) – The effect that is sent.

Utility Functions

discord.utils.find(predicate, iterable, /)

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.

Changed in version 2.0: Both parameters are now positional-only.

Changed in version 2.0: The iterable parameter supports asynchronous iterables.

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

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

Changed in version 2.0: The iterable parameter supports asynchronous iterables.

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

Async iterables:

msg = await discord.utils.get(channel.history(), author__name='Dave')
Parameters
discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)

A helper function to setup logging.

This is superficially similar to logging.basicConfig() but uses different defaults and a colour formatter if the stream can display colour.

This is used by the Client to set up logging if log_handler is not None.

New in version 2.0.

Parameters
  • handler (logging.Handler) –

    The log handler to use for the library’s logger.

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

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

  • level (int) – The default log level for the library’s logger. Defaults to logging.INFO.

  • root (bool) – Whether to set up the root logger rather than the library logger. Unlike the default for Client, this defaults to True.

await discord.utils.maybe_coroutine(f, *args, **kwargs)

This function is a coroutine.

A helper function that will await the result of a function if it’s a coroutine or return the result if it’s not.

This is useful for functions that may or may not be coroutines.

New in version 2.2.

Parameters
  • f (Callable[..., Any]) – The function or coroutine to call.

  • *args – The arguments to pass to the function.

  • **kwargs – The keyword arguments to pass to the function.

Returns

The result of the function or coroutine.

Return type

Any

discord.utils.snowflake_time(id, /)

Returns the creation time of the given snowflake.

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

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.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(dt, high=False) - 1 to be inclusive, high=True to be exclusive.

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

Changed in version 2.0: The high parameter is now keyword-only and the dt parameter is now positional-only.

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 or not to set the lower 22 bit to high or low.

Returns

The snowflake representing the time given.

Return type

int

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

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

Changed in version 2.0: permissions, guild, redirect_uri, scopes and state parameters are now keyword-only.

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', 'applications.commands').

    New in version 1.7.

  • disable_guild_select (bool) –

    Whether to disallow the user from changing the guild dropdown.

    New in version 2.0.

  • state (str) –

    The state to return after the authorization.

    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

class discord.ResolvedInvite

A data class which represents a resolved invite returned from discord.utils.resolve_invite().

code

The invite code.

Type

str

event

The id of the scheduled event that the invite refers to.

Type

Optional[int]

discord.utils.resolve_invite(invite)

Resolves an invite from a Invite, URL or code.

Changed in version 2.0: Now returns a ResolvedInvite instead of a str.

Parameters

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

Raises

ValueError – The invite is not a valid Discord invite, e.g. is not a URL or does not contain alphanumeric characters.

Returns

A data class containing the invite code and the event ID.

Return type

ResolvedInvite

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[Iterator, AsyncIterator]

discord.utils.MISSING

A type safe sentinel used in the library to represent something as missing. Used to distinguish from None values.

New in version 2.0.

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

forum

A forum channel.

New in version 2.0.

media

A media channel.

New in version 2.4.

lobby

A lobby channel.

New in version 3.0.

ephemeral_dm

An ephemeral DM channel.

New in version 3.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.

chat_input_command

The system message denoting that a 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 a context menu command was executed.

New in version 2.0.

auto_moderation_action

The system message sent when an AutoMod rule is triggered. This is only sent if the rule is configured to sent an alert when triggered.

New in version 2.0.

role_subscription_purchase

The system message sent when a user purchases or renews a role subscription.

New in version 2.2.

interaction_premium_upsell

The system message sent when a user is given an advertisement to purchase a premium tier for an application during an interaction.

New in version 2.2.

stage_start

The system message sent when the stage starts.

New in version 2.2.

stage_end

The system message sent when the stage ends.

New in version 2.2.

stage_speaker

The system message sent when the stage speaker changes.

New in version 2.2.

stage_raise_hand

The system message sent when a user is requesting to speak by raising their hands.

New in version 2.2.

stage_topic

The system message sent when the stage topic changes.

New in version 2.2.

guild_application_premium_subscription

The system message sent when an application’s premium subscription is purchased for the guild.

New in version 2.2.

guild_incident_alert_mode_enabled

The system message sent when security actions is enabled.

New in version 2.4.

guild_incident_alert_mode_disabled

The system message sent when security actions is disabled.

New in version 2.4.

guild_incident_report_raid

The system message sent when a raid is reported.

New in version 2.4.

guild_incident_report_false_alarm

The system message sent when a false alarm is reported.

New in version 2.4.

purchase_notification

The system message sent when a purchase is made in the guild.

New in version 2.5.

poll_result

The system message sent when a poll has closed.

New in version 2.5.

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.

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 Moderator Programs Alumni.

bot_http_interactions

The user is a bot that only uses HTTP interactions and is shown in the online member list.

New in version 2.0.

spammer

The user is flagged as a spammer by Discord.

New in version 2.0.

active_developer

The user is an active developer.

New in version 2.1.

provisional_account

The user is a provisional account.

New in version 3.0.

quarantined

The user is quarantined.

New in version 3.0.

collaborator

The user is a collaborator and considered staff.

New in version 3.0.

restricted_collaborator

The user is a restricted collaborator and considered staff.

New in version 3.0.

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

Members receive notifications for messages they are mentioned in.

class discord.ContentFilter

Specifies a Guild's explicit content filter, which is the machine learning algorithms that Discord uses to detect if an image contains pornography or otherwise explicit content.

New in version 2.0.

x == y

Checks if two content filter levels are equal.

x != y

Checks if two content filter levels are not equal.

x > y

Checks if a content filter level is higher than another.

x < y

Checks if a content filter level is lower than another.

x >= y

Checks if a content filter level is higher or equal to another.

x <= y

Checks if a content filter level is lower or equal to another.

disabled

The guild does not have the content filter enabled.

no_role

The guild has the content filter enabled for members without a role.

all_members

The guild has the content filter enabled for every member.

class discord.Status

Specifies a Member ‘s status.

online

The member is online.

offline

The member is offline.

idle

The member is idle.

dnd

The member is “Do Not Disturb”.

do_not_disturb

An alias for dnd.

invisible

The member is “invisible”. In reality, this is only used when sending a presence a la Client.change_presence(). When you receive a user’s presence this will be offline instead.

class discord.AuditLogAction

Represents the type of action being done for a AuditLogEntry, which is retrievable via Guild.audit_logs().

guild_update

The guild has updated. Things that trigger this include:

  • Changing the guild vanity URL

  • Changing the guild invite splash

  • Changing the guild AFK channel or timeout

  • Changing the guild voice server region

  • Changing the guild icon, banner, or discovery splash

  • Changing the guild moderation settings

  • Changing things related to the guild widget

When this is the action, the type of target is the Guild.

Possible attributes for AuditLogDiff:

  • afk_channel

  • system_channel

  • afk_timeout

  • default_notifications

  • explicit_content_filter

  • mfa_level

  • name

  • owner

  • splash

  • discovery_splash

  • icon

  • banner

  • vanity_url_code

  • description

  • preferred_locale

  • prune_delete_days

  • public_updates_channel

  • rules_channel

  • verification_level

  • widget_channel

  • widget_enabled

  • premium_progress_bar_enabled

  • system_channel_flags

channel_create

A new channel was created.

When this is the action, the type of target is either a abc.GuildChannel or Object with an ID.

A more filled out object in the Object case can be found by using after.

Possible attributes for AuditLogDiff:

  • name

  • type

  • overwrites

channel_update

A channel was updated. Things that trigger this include:

  • The channel name or topic was changed

  • The channel bitrate was changed

When this is the action, the type of target is the abc.GuildChannel or Object with an ID.

A more filled out object in the Object case can be found by using after or before.

Possible attributes for AuditLogDiff:

  • name

  • type

  • position

  • overwrites

  • topic

  • bitrate

  • rtc_region

  • video_quality_mode

  • default_auto_archive_duration

  • nsfw

  • slowmode_delay

  • user_limit

channel_delete

A channel was deleted.

When this is the action, the type of target is an Object with an ID.

A more filled out object can be found by using the before object.

Possible attributes for AuditLogDiff:

  • name

  • type

  • overwrites

  • flags

  • nsfw

  • slowmode_delay

overwrite_create

A channel permission overwrite was created.

When this is the action, the type of target is the abc.GuildChannel or Object with an ID.

When this is the action, the type of extra is either a Role or Member. If the object is not found then it is a Object with an ID being filled, a name, and a type attribute set to either 'role' or 'member' to help dictate what type of ID it is.

Possible attributes for AuditLogDiff:

  • deny

  • allow

  • id

  • type

overwrite_update

A channel permission overwrite was changed, this is typically when the permission values change.

See overwrite_create for more information on how the target and extra fields are set.

Possible attributes for AuditLogDiff:

  • deny

  • allow

  • id

  • type

overwrite_delete

A channel permission overwrite was deleted.

See overwrite_create for more information on how the target and extra fields are set.

Possible attributes for AuditLogDiff:

  • deny

  • allow

  • id

  • type

kick

A member was kicked.

When this is the action, the type of target is the User or Object who got kicked.

When this is the action, the type of extra is set to an unspecified proxy object with one attribute:

  • integration_type: An optional string that denotes the type of integration that did the action.

When this is the action, changes is empty.

member_prune

A member prune was triggered.

When this is the action, the type of target is set to None.

When this is the action, the type of extra is set to an unspecified proxy object with two attributes:

  • delete_member_days: An integer specifying how far the prune was.

  • members_removed: An integer specifying how many members were removed.

When this is the action, changes is empty.

ban

A member was banned.

When this is the action, the type of target is the User or Object who got banned.

When this is the action, changes is empty.

unban

A member was unbanned.

When this is the action, the type of target is the User or Object who got unbanned.

When this is the action, changes is empty.

member_update

A member has updated. This triggers in the following situations:

  • A nickname was changed

  • They were server muted or deafened (or it was undo’d)

When this is the action, the type of target is the Member, User, or Object who got updated.

Possible attributes for AuditLogDiff:

  • nick

  • mute

  • deaf

  • timed_out_until

member_role_update

A member’s role has been updated. This triggers when a member either gains a role or loses a role.

When this is the action, the type of target is the Member, User, or Object who got the role.

When this is the action, the type of extra is set to an unspecified proxy object with one attribute:

  • integration_type: An optional string that denotes the type of integration that did the action.

Possible attributes for AuditLogDiff:

  • roles

member_move

A member’s voice channel has been updated. This triggers when a member is moved to a different voice channel.

When this is the action, the type of extra is set to an unspecified proxy object with two attributes:

  • channel: An abc.Connectable or Object with the channel ID where the members were moved.

  • count: An integer specifying how many members were moved.

New in version 1.3.

member_disconnect

A member’s voice state has changed. This triggers when a member is force disconnected from voice.

When this is the action, the type of extra is set to an unspecified proxy object with one attribute:

  • count: An integer specifying how many members were disconnected.

New in version 1.3.

bot_add

A bot was added to the guild.

When this is the action, the type of target is the Member, User, or Object which was added to the guild.

New in version 1.3.

role_create

A new role was created.

When this is the action, the type of target is the Role or a Object with the ID.

Possible attributes for AuditLogDiff:

  • colour

  • mentionable

  • hoist

  • icon

  • unicode_emoji

  • name

  • permissions

role_update

A role was updated. This triggers in the following situations:

  • The name has changed

  • The permissions have changed

  • The colour has changed

  • The role icon (or unicode emoji) has changed

  • Its hoist/mentionable state has changed

When this is the action, the type of target is the Role or a Object with the ID.

Possible attributes for AuditLogDiff:

  • colour

  • mentionable

  • hoist

  • icon

  • unicode_emoji

  • name

  • permissions

role_delete

A role was deleted.

When this is the action, the type of target is the Role or a Object with the ID.

Possible attributes for AuditLogDiff:

  • colour

  • mentionable

  • hoist

  • name

  • permissions

invite_create

An invite was created.

When this is the action, the type of target is the Invite that was created.

Possible attributes for AuditLogDiff:

  • max_age

  • code

  • temporary

  • inviter

  • channel

  • uses

  • max_uses

invite_update

An invite was updated.

When this is the action, the type of target is the Invite that was updated.

invite_delete

An invite was deleted.

When this is the action, the type of target is the Invite that was deleted.

Possible attributes for AuditLogDiff:

  • max_age

  • code

  • temporary

  • inviter

  • channel

  • uses

  • max_uses

webhook_create

A webhook was created.

When this is the action, the type of target is the Object with the webhook ID.

Possible attributes for AuditLogDiff:

  • channel

  • name

  • type (always set to 1 if so)

webhook_update

A webhook was updated. This trigger in the following situations:

  • The webhook name changed

  • The webhook channel changed

When this is the action, the type of target is the Object with the webhook ID.

Possible attributes for AuditLogDiff:

  • channel

  • name

  • avatar

webhook_delete

A webhook was deleted.

When this is the action, the type of target is the Object with the webhook ID.

Possible attributes for AuditLogDiff:

  • channel

  • name

  • type (always set to 1 if so)

emoji_create

An emoji was created.

When this is the action, the type of target is the Emoji or Object with the emoji ID.

Possible attributes for AuditLogDiff:

  • name

emoji_update

An emoji was updated. This triggers when the name has changed.

When this is the action, the type of target is the Emoji or Object with the emoji ID.

Possible attributes for AuditLogDiff:

  • name

emoji_delete

An emoji was deleted.

When this is the action, the type of target is the Object with the emoji ID.

Possible attributes for AuditLogDiff:

  • name

message_delete

A message was deleted by a moderator. Note that this only triggers if the message was deleted by someone other than the author.

When this is the action, the type of target is the Member, User, or Object who had their message deleted.

When this is the action, the type of extra is set to an unspecified proxy object with two attributes:

  • count: An integer specifying how many messages were deleted.

  • channel: A TextChannel or Object with the channel ID where the message got deleted.

message_bulk_delete

Messages were bulk deleted by a moderator.

When this is the action, the type of target is the TextChannel or Object with the ID of the channel that was purged.

When this is the action, the type of extra is set to an unspecified proxy object with one attribute:

  • count: An integer specifying how many messages were deleted.

New in version 1.3.

message_pin

A message was pinned in a channel.

When this is the action, the type of target is the Member, User, or Object who had their message pinned.

When this is the action, the type of extra is set to an unspecified proxy object with two attributes:

  • channel: A TextChannel or Object with the channel ID where the message was pinned.

  • message_id: the ID of the message which was pinned.

New in version 1.3.

message_unpin

A message was unpinned in a channel.

When this is the action, the type of target is the Member, User, or Object who had their message unpinned.

When this is the action, the type of extra is set to an unspecified proxy object with two attributes:

  • channel: A TextChannel or Object with the channel ID where the message was unpinned.

  • message_id: the ID of the message which was unpinned.

New in version 1.3.

integration_create

A guild integration was created.

When this is the action, the type of target is a PartialIntegration or Object with the integration ID of the integration which was created.

New in version 1.3.

integration_update

A guild integration was updated.

When this is the action, the type of target is a PartialIntegration or Object with the integration ID of the integration which was updated.

New in version 1.3.

integration_delete

A guild integration was deleted.

When this is the action, the type of target is a PartialIntegration or Object with the integration ID of the integration which was deleted.

New in version 1.3.

stage_instance_create

A stage instance was started.

When this is the action, the type of target is the StageInstance or Object with the ID of the stage instance which was created.

Possible attributes for AuditLogDiff:

  • topic

  • privacy_level

New in version 2.0.

stage_instance_update

A stage instance was updated.

When this is the action, the type of target is the StageInstance or Object with the ID of the stage instance which was updated.

Possible attributes for AuditLogDiff:

  • topic

  • privacy_level

New in version 2.0.

stage_instance_delete

A stage instance was ended.

New in version 2.0.

sticker_create

A sticker was created.

When this is the action, the type of target is the GuildSticker or Object with the ID of the sticker which was created.

Possible attributes for AuditLogDiff:

  • name

  • emoji

  • type

  • format_type

  • description

  • available

New in version 2.0.

sticker_update

A sticker was updated.

When this is the action, the type of target is the GuildSticker or Object with the ID of the sticker which was updated.

Possible attributes for AuditLogDiff:

  • name

  • emoji

  • type

  • format_type

  • description

  • available

New in version 2.0.

sticker_delete

A sticker was deleted.

When this is the action, the type of target is the GuildSticker or Object with the ID of the sticker which was updated.

Possible attributes for AuditLogDiff:

  • name

  • emoji

  • type

  • format_type

  • description

  • available

New in version 2.0.

scheduled_event_create

A scheduled event was created.

When this is the action, the type of target is the ScheduledEvent or Object with the ID of the event which was created.

Possible attributes for AuditLogDiff: - name - channel - description - privacy_level - status - entity_type - cover_image

New in version 2.0.

scheduled_event_update

A scheduled event was created.

When this is the action, the type of target is the ScheduledEvent or Object with the ID of the event which was updated.

Possible attributes for AuditLogDiff: - name - channel - description - privacy_level - status - entity_type - cover_image

New in version 2.0.

scheduled_event_delete

A scheduled event was created.

When this is the action, the type of target is the ScheduledEvent or Object with the ID of the event which was deleted.

Possible attributes for AuditLogDiff: - name - channel - description - privacy_level - status - entity_type - cover_image

New in version 2.0.

thread_create

A thread was created.

When this is the action, the type of target is the Thread or Object with the ID of the thread which was created.

Possible attributes for AuditLogDiff:

  • name

  • archived

  • locked

  • auto_archive_duration

  • invitable

New in version 2.0.

thread_update

A thread was updated.

When this is the action, the type of target is the Thread or Object with the ID of the thread which was updated.

Possible attributes for AuditLogDiff:

  • name

  • archived

  • locked

  • auto_archive_duration

  • invitable

New in version 2.0.

thread_delete

A thread was deleted.

When this is the action, the type of target is the Thread or Object with the ID of the thread which was deleted.

Possible attributes for AuditLogDiff:

  • name

  • archived

  • locked

  • auto_archive_duration

  • invitable

New in version 2.0.

app_command_permission_update

An application command or integrations application command permissions were updated.

When this is the action, the type of target is a PartialIntegration for an integrations general permissions, AppCommand for a specific commands permissions, or Object with the ID of the command or integration which was updated.

When this is the action, the type of extra is set to an PartialIntegration or Object with the ID of application that command or integration belongs to.

Possible attributes for AuditLogDiff:

  • app_command_permissions

New in version 2.0.

automod_rule_create

An automod rule was created.

When this is the action, the type of target is a AutoModRule or Object with the ID of the automod rule that was created.

Possible attributes for AuditLogDiff:

  • name

  • enabled

  • event_type

  • trigger_type

  • trigger

  • actions

  • exempt_roles

  • exempt_channels

New in version 2.0.

automod_rule_update

An automod rule was updated.

When this is the action, the type of target is a AutoModRule or Object with the ID of the automod rule that was created.

Possible attributes for AuditLogDiff:

  • name

  • enabled

  • event_type

  • trigger_type

  • trigger

  • actions

  • exempt_roles

  • exempt_channels

New in version 2.0.

automod_rule_delete

An automod rule was deleted.

When this is the action, the type of target is a AutoModRule or Object with the ID of the automod rule that was created.

Possible attributes for AuditLogDiff:

  • name

  • enabled

  • event_type

  • trigger_type

  • trigger

  • actions

  • exempt_roles

  • exempt_channels

New in version 2.0.

automod_block_message

An automod rule blocked a message from being sent.

When this is the action, the type of target is a Member with the ID of the person who triggered the automod rule.

When this is the action, the type of extra is set to an unspecified proxy object with 3 attributes:

  • automod_rule_name: The name of the automod rule that was triggered.

  • automod_rule_trigger_type: A AutoModRuleTriggerType representation of the rule type that was triggered.

  • channel: The channel in which the automod rule was triggered.

When this is the action, AuditLogEntry.changes is empty.

New in version 2.0.

automod_flag_message

An automod rule flagged a message.

When this is the action, the type of target is a Member with the ID of the person who triggered the automod rule.

When this is the action, the type of extra is set to an unspecified proxy object with 3 attributes:

  • automod_rule_name: The name of the automod rule that was triggered.

  • automod_rule_trigger_type: A AutoModRuleTriggerType representation of the rule type that was triggered.

  • channel: The channel in which the automod rule was triggered.

When this is the action, AuditLogEntry.changes is empty.

New in version 2.1.

automod_timeout_member

An automod rule timed-out a member.

When this is the action, the type of target is a Member with the ID of the person who triggered the automod rule.

When this is the action, the type of extra is set to an unspecified proxy object with 3 attributes:

  • automod_rule_name: The name of the automod rule that was triggered.

  • automod_rule_trigger_type: A AutoModRuleTriggerType representation of the rule type that was triggered.

  • channel: The channel in which the automod rule was triggered.

When this is the action, AuditLogEntry.changes is empty.

New in version 2.1.

creator_monetization_request_created

A request to monetize the server was created.

New in version 2.4.

creator_monetization_terms_accepted

The terms and conditions for creator monetization were accepted.

New in version 2.4.

soundboard_sound_create

A soundboard sound was created.

Possible attributes for AuditLogDiff:

  • name

  • emoji

  • volume

New in version 2.5.

soundboard_sound_update

A soundboard sound was updated.

Possible attributes for AuditLogDiff:

  • name

  • emoji

  • volume

New in version 2.5.

soundboard_sound_delete

A soundboard sound was deleted.

Possible attributes for AuditLogDiff:

  • name

  • emoji

  • volume

New in version 2.5.

class discord.AuditLogActionCategory

Represents the category that the AuditLogAction belongs to.

This can be retrieved via AuditLogEntry.category.

create

The action is the creation of something.

delete

The action is the deletion of something.

update

The action is the update of something.

class discord.ApplicationType

Represents the type of an Application.

New in version 3.0.

game

The application is a game.

music

The application is music-related.

ticketed_events

The application can use ticketed event.

guild_role_subscriptions

The application can make custom guild role subscriptions.

class discord.TeamMembershipState

Represents the membership state of a team member retrieved through Client.application_info().

New in version 1.3.

invited

Represents an invited member.

accepted

Represents a member currently in the team.

class discord.TeamMemberRole

Represents the type of role of a team member retrieved through Client.application_info().

New in version 2.4.

admin

The team member is an admin. This allows them to invite members to the team, access credentials, edit the application, and do most things the owner can do. However they cannot do destructive actions.

developer

The team member is a developer. This allows them to access information, like the client secret or public key. They can also configure interaction endpoints or reset the bot token. Developers cannot invite anyone to the team nor can they do destructive actions.

read_only

The team member is a read-only member. This allows them to access information, but not edit anything.

class discord.WebhookType

Represents the type of webhook that can be received.

New in version 1.3.

incoming

Represents a webhook that can post messages to channels with a token.

channel_follower

Represents a webhook that is internally managed by Discord, used for following channels.

application

Represents a webhook that is used for interactions or applications.

New in version 2.0.

class discord.ExpireBehaviour

Represents the behaviour the Integration should perform when a user’s subscription has finished.

There is an alias for this called ExpireBehavior.

New in version 1.4.

remove_role

This will remove the StreamIntegration.role from the user when their subscription is finished.

kick

This will kick the user when their subscription is finished.

class discord.DefaultAvatar

Represents the default avatar of a Discord User

blurple

Represents the default avatar with the colour blurple. See also Colour.blurple

grey

Represents the default avatar with the colour grey. See also Colour.greyple

gray

An alias for grey.

green

Represents the default avatar with the colour green. See also Colour.green

orange

Represents the default avatar with the colour orange. See also Colour.orange

red

Represents the default avatar with the colour red. See also Colour.red

pink

Represents the default avatar with the colour pink. See also Colour.pink

New in version 2.3.

class discord.StickerType

Represents the type of sticker.

New in version 2.0.

standard

Represents a standard sticker that all Nitro users can use.

guild

Represents a custom sticker created in a guild.

class discord.StickerFormatType

Represents the type of sticker images.

New in version 1.6.

png

Represents a sticker with a png image.

apng

Represents a sticker with an apng image.

lottie

Represents a sticker with a lottie image.

gif

Represents a sticker with a gif image.

New in version 2.2.

class discord.InviteTarget

Represents the invite type for voice channel invites.

New in version 2.0.

unknown

The invite doesn’t target anyone or anything.

stream

A stream invite that targets a user.

embedded_application

A stream invite that targets an embedded application.

class discord.VideoQualityMode

Represents the camera video quality mode for voice channel participants.

New in version 2.0.

auto

Represents auto camera video quality.

full

Represents full camera video quality.

class discord.PrivacyLevel

Represents the privacy level of a stage instance or scheduled event.

New in version 2.0.

guild_only

The stage instance or scheduled event is only accessible within the guild.

class discord.NSFWLevel

Represents the NSFW level of a guild.

New in version 2.0.

x == y

Checks if two NSFW levels are equal.

x != y

Checks if two NSFW levels are not equal.

x > y

Checks if a NSFW level is higher than another.

x < y

Checks if a NSFW level is lower than another.

x >= y

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

x <= y

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

default

The guild has not been categorised yet.

explicit

The guild contains NSFW content.

safe

The guild does not contain any NSFW content.

age_restricted

The guild may contain NSFW content.

class discord.RelationshipType

Specifies the type of Relationship or GameRelationship..

New in version 3.0.

friend

You are friends with this user.

blocked

You have blocked this user.

incoming_request

The user has sent you a friend request.

outgoing_request

You have sent a friend request to this user.

implicit

You frecently interact with this user. See UserAffinity for more information.

class discord.PremiumType

Represents the user’s Discord Nitro subscription type.

New in version 3.0.

none

The user does not have a Discord Nitro subscription.

nitro

Represents the new, full Discord Nitro.

nitro_classic

Represents the classic Discord Nitro.

nitro_basic

Represents the basic Discord Nitro.

New in version 2.0.

class discord.PaymentSourceType

Represents the type of a payment source.

New in version 3.0.

unknown

The payment source is unknown.

credit_card

The payment source is a credit card.

paypal

The payment source is a PayPal account.

giropay

The payment source is a Giropay account.

sofort

The payment source is a Sofort account.

przelewy24

The payment source is a Przelewy24 account.

sepa_debit

The payment source is a SEPA debit account.

paysafecard

The payment source is a Paysafe card.

gcash

The payment source is a GCash account.

grabpay

The payment source is a GrabPay (Malaysia) account.

momo_wallet

The payment source is a MoMo Wallet account.

venmo

The payment source is a Venmo account.

gopay_wallet

The payment source is a GoPay Wallet account.

kakaopay

The payment source is a KakaoPay account.

bancontact

The payment source is a Bancontact account.

eps

The payment source is an EPS account.

ideal

The payment source is an iDEAL account.

cash_app

The payment source is a Cash App account.

class discord.OAuth2CodeChallengeMethod

Represents a method used to generate code challenge.

sha256

The code challenge is hashed using SHA256.

class discord.OAuth2ResponseType

Represents what should be retrieved when authorizing application.

code

Retrieve the code for exchanging.

token

Retrieve the access token directly.

class discord.OperatingSystem

Represents the operating system of a SKU’s system requirements.

New in version 3.0.

windows

Represents Windows.

mac

Represents macOS.

linux

Represents Linux.

android

Represents Android.

ios

Represents iOS.

playstation

Represents PlayStation.

xbox

Represents Xbox.

unknown

Represents an unknown operating system.

class discord.Locale

Supported locales by Discord.

New in version 2.0.

american_english

The en-US locale.

british_english

The en-GB locale.

bulgarian

The bg locale.

chinese

The zh-CN locale.

taiwan_chinese

The zh-TW locale.

croatian

The hr locale.

czech

The cs locale.

indonesian

The id locale.

New in version 2.2.

danish

The da locale.

dutch

The nl locale.

finnish

The fi locale.

french

The fr locale.

german

The de locale.

greek

The el locale.

hindi

The hi locale.

hungarian

The hu locale.

italian

The it locale.

japanese

The ja locale.

korean

The ko locale.

latin_american_spanish

The es-419 locale.

New in version 2.4.

lithuanian

The lt locale.

norwegian

The no locale.

polish

The pl locale.

brazil_portuguese

The pt-BR locale.

romanian

The ro locale.

russian

The ru locale.

spain_spanish

The es-ES locale.

swedish

The sv-SE locale.

thai

The th locale.

turkish

The tr locale.

ukrainian

The uk locale.

vietnamese

The vi locale.

class discord.MFALevel

Represents the Multi-Factor Authentication requirement level of a guild.

New in version 2.0.

x == y

Checks if two MFA levels are equal.

x != y

Checks if two MFA levels are not equal.

x > y

Checks if a MFA level is higher than another.

x < y

Checks if a MFA level is lower than another.

x >= y

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

x <= y

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

disabled

The guild has no MFA requirement.

require_2fa

The guild requires 2 factor authentication.

class discord.EntityType

Represents the type of entity that a scheduled event is for.

New in version 2.0.

stage_instance

The scheduled event will occur in a stage instance.

voice

The scheduled event will occur in a voice channel.

external

The scheduled event will occur externally.

class discord.EventStatus

Represents the status of an event.

New in version 2.0.

scheduled

The event is scheduled.

active

The event is active.

completed

The event has ended.

cancelled

The event has been cancelled.

canceled

An alias for cancelled.

ended

An alias for completed.

class discord.ConnectionType

Represents the type of connection a user has with Discord.

New in version 3.0.

amazon_music

The user has an Amazon Music connection.

battle_net

The user has a Battle.net connection.

bluesky

The user has a Bluesky connection.

bungie

The user has a Bungie connection.

contacts

The user has a contact sync connection.

crunchyroll

The user has a Crunchyroll connection.

domain

The user has a domain connection.

ebay

The user has an eBay connection.

epic_games

The user has an Epic Games connection.

facebook

The user has a Facebook connection.

github

The user has a GitHub connection.

instagram

The user has Instagram connection.

league_of_legends

The user has a League of Legends connection.

mastodon

The user has a Mastodon connection.

paypal

The user has a PayPal connection.

playstation

The user has a PlayStation connection.

playstation_stg

The user has a PlayStation staging connection.

reddit

The user has a Reddit connection.

roblox

The user has a Roblox connection.

riot_games

The user has a Riot Games connection.

soundcloud

The user has a SoundCloud connection.

spotify

The user has a Spotify connection.

skype

The user has a Skype connection.

steam

The user has a Steam connection.

tiktok

The user has a TikTok connection.

twitch

The user has a Twitch connection.

twitter

The user has a Twitter connection.

youtube

The user has a YouTube connection.

xbox

The user has an Xbox Live connection.

class discord.ClientType

Represents a type of Discord client.

New in version 3.0.

web

Represents the web client.

mobile

Represents a mobile client.

desktop

Represents a desktop client.

embedded

Represents an embedded client.

unknown

Represents an unknown client.

class discord.GiftStyle

Represents the special style of a gift.

New in version 3.0.

snowglobe

The gift is a snowglobe.

box

The gift is a box.

class discord.ComponentType

Represents the component type of a component.

New in version 2.0.

action_row

Represents a component which holds different components in a row.

button

Represents a button component.

text_input

Represents a text box component.

select

Represents a select component.

string_select

An alias to select. Represents a default select component.

user_select

Represents a user select component.

role_select

Represents a role select component.

mentionable_select

Represents a select in which both users and roles can be selected.

channel_select

Represents a channel select component.

section

Represents a component which holds different components in a section.

New in version 3.0.

text_display

Represents a text display component.

New in version 3.0.

thumbnail

Represents a thumbnail component.

New in version 3.0.

Represents a media gallery component.

New in version 3.0.

file

Represents a file component.

New in version 3.0.

separator

Represents a separator component.

New in version 3.0.

content_inventory_entry

Represents an entry from Activity Feed.

New in version 3.0.

container

Represents a component which holds different components in a container.

New in version 3.0.

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.

premium

Represents a button denoting that buying a SKU is required to perform this action.

New in version 2.4.

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

Represents the style of the text box component.

New in version 2.0.

short

Represents a short text box.

paragraph

Represents a long form text box.

long

An alias for paragraph.

class discord.AppCommandOptionType

The application command’s option type. This is usually the type of parameter an application command takes.

New in version 2.0.

subcommand

A subcommand.

subcommand_group

A subcommand group.

string

A string parameter.

integer

A integer parameter.

boolean

A boolean parameter.

user

A user parameter.

channel

A channel parameter.

role

A role parameter.

mentionable

A mentionable parameter.

number

A number parameter.

attachment

An attachment parameter.

class discord.AppCommandType

The type of application command.

New in version 2.0.

chat_input

A slash command.

user

A user context menu command.

message

A message context menu command.

primary_entry_point

A primary entry-point for the application.

New in version 3.0.

class discord.AppCommandPermissionType

The application command’s permission type.

New in version 2.0.

role

The permission is for a role.

channel

The permission is for one or all channels.

user

The permission is for a user.

class discord.SeparatorSpacing

The separator’s size type.

New in version 3.0.

small

A small separator.

large

A large separator.

class discord.AutoModRuleTriggerType

Represents the trigger type of an automod rule.

New in version 2.0.

keyword

The rule will trigger when a keyword is mentioned.

The rule will trigger when a harmful link is posted.

spam

The rule will trigger when a spam message is posted.

keyword_preset

The rule will trigger when something triggers based on the set keyword preset types.

mention_spam

The rule will trigger when combined number of role and user mentions is greater than the set limit.

member_profile

The rule will trigger when a user’s profile contains a keyword.

New in version 2.4.

class discord.AutoModRuleEventType

Represents the event type of an automod rule.

New in version 2.0.

message_send

The rule will trigger when a message is sent.

member_update

The rule will trigger when a member’s profile is updated.

New in version 2.4.

class discord.AutoModRuleActionType

Represents the action type of an automod rule.

New in version 2.0.

block_message

The rule will block a message from being sent.

send_alert_message

The rule will send an alert message to a predefined channel.

timeout

The rule will timeout a user.

block_member_interactions

Similar to timeout, except the user will be timed out indefinitely. This will request the user to edit it’s profile.

New in version 2.4.

class discord.ForumLayoutType

Represents how a forum’s posts are layed out in the client.

New in version 2.2.

not_set

No default has been set, so it is up to the client to know how to lay it out.

list_view

Displays posts as a list.

gallery_view

Displays posts as a collection of tiles.

class discord.ForumOrderType

Represents how a forum’s posts are sorted in the client.

New in version 2.3.

latest_activity

Sort forum posts by activity.

creation_date

Sort forum posts by creation time (from most recent to oldest).

class discord.SelectDefaultValueType

Represents the default value of a select menu.

New in version 2.4.

user

The underlying type of the ID is a user.

role

The underlying type of the ID is a role.

channel

The underlying type of the ID is a channel or thread.

class discord.SKUType

Represents the type of a SKU.

New in version 2.4.

durable

The SKU is a durable one-time purchase.

consumable

The SKU is a consumable one-time purchase.

subscription

The SKU is a recurring subscription.

subscription_group

The SKU is a system-generated group which is created for each SKUType.subscription.

class discord.EntitlementType

Represents the type of an entitlement.

New in version 2.4.

purchase

The entitlement is from a purchase.

premium_subscription

The entitlement is a Discord premium subscription.

developer_gift

The entitlement is gifted by the developer.

test_mode_purchase

The entitlement is from a free test mode purchase.

free_purchase

The entitlement is a free purchase.

user_gift

The entitlement is gifted by a user.

premium_purchase

The entitlement is a premium subscription perk.

application_subscription

The entitlement is an application subscription.

free_staff_purchase

The entitlement is claimed for free by a Discord employee.

New in version 3.0.

quest_reward

The entitlement is from a quest reward.

New in version 3.0.

fractional_redemption

The entitlement is for a fractional premium subscription.

New in version 3.0.

virtual_currency_redemption

The entitlement was purchased with Discord Orbs.

New in version 3.0.

guild_powerup

The entitlement was purchased with premium guild subscriptions (boosts).

New in version 3.0.

class discord.EntitlementOwnerType

Represents the type of an entitlement owner.

New in version 2.4.

guild

The entitlement owner is a guild.

user

The entitlement owner is a user.

class discord.PollLayoutType

Represents how a poll answers are shown.

New in version 2.4.

default

The default layout.

class discord.InviteType

Represents the type of an invite.

New in version 2.4.

guild

The invite is a guild invite.

group_dm

The invite is a group DM invite.

friend

The invite is a friend invite.

class discord.ReactionType

Represents the type of a reaction.

New in version 2.4.

normal

A normal reaction.

burst

A burst reaction, also known as a “super reaction”.

class discord.VoiceChannelEffectAnimationType

Represents the animation type of a voice channel effect.

New in version 2.5.

premium

A fun animation, sent by a Nitro subscriber.

basic

The standard animation.

class discord.SubscriptionStatus

Represents the status of an subscription.

New in version 2.5.

active

The subscription is active.

ending

The subscription is active but will not renew.

inactive

The subscription is inactive and not being charged.

class discord.MessageReferenceType

Represents the type of a message reference.

New in version 2.5.

default

A standard reference used by message replies (MessageType.reply), crossposted messaged created by a followed channel integration, and messages of type:

forward

A forwarded message.

reply

An alias for default.

Webhook Support

discord.py-oauth2 offers support for creating, editing, and executing webhooks through the Webhook class.

Webhook

class discord.Webhook

Represents an asynchronous Discord webhook.

Webhooks are a form to send messages to channels in Discord without a bot user or authentication.

There are two main ways to use Webhooks. The first is through the ones received by the library such as Guild.webhooks(), TextChannel.webhooks(), VoiceChannel.webhooks() and ForumChannel.webhooks(). The ones received by the library will automatically be bound using the library’s internal HTTP session.

The second form involves creating a webhook object manually using the from_url() or partial() classmethods.

For example, creating a webhook from a URL and using aiohttp:

from discord import Webhook
import aiohttp

async def foo():
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('url-here', session=session)
        await webhook.send('Hello World', username='Foo')

For a synchronous counterpart, see SyncWebhook.

x == y

Checks if two webhooks are equal.

x != y

Checks if two webhooks are not equal.

hash(x)

Returns the webhooks’s hash.

Changed in version 1.4: Webhooks are now comparable and hashable.

id

The webhook’s ID

Type

int

type

The type of the webhook.

New in version 1.3.

Type

WebhookType

token

The authentication token of the webhook. If this is None then the webhook cannot be used to make requests.

Type

Optional[str]

guild_id

The guild ID this webhook is for.

Type

Optional[int]

channel_id

The channel ID this webhook is for.

Type

Optional[int]

user

The user this webhook was created by. If the webhook was received without authentication then this will be None.

Type

Optional[abc.User]

name

The default name of the webhook.

Type

Optional[str]

source_guild

The guild of the channel that this webhook is following. Only given if type is WebhookType.channel_follower.

New in version 2.0.

Type

Optional[PartialWebhookGuild]

source_channel

The channel that this webhook is following. Only given if type is WebhookType.channel_follower.

New in version 2.0.

Type

Optional[PartialWebhookChannel]

property url

Returns the webhook’s url.

Type

str

classmethod partial(id, token, *, session=..., client=..., bot_token=None)

Creates a partial Webhook.

Parameters
  • id (int) – The ID of the webhook.

  • token (str) – The authentication token of the webhook.

  • session (aiohttp.ClientSession) –

    The session to use to send requests with. Note that the library does not manage the session and will not close it.

    New in version 2.0.

  • client (Client) –

    The client to initialise this webhook with. This allows it to attach the client’s internal state. If session is not given while this is given then the client’s internal session will be used.

    New in version 2.2.

  • bot_token (Optional[str]) –

    The bot authentication token for authenticated requests involving the webhook.

    New in version 2.0.

Raises

TypeError – Neither session nor client were given.

Returns

A partial Webhook. A partial webhook is just a webhook object with an ID and a token.

Return type

Webhook

classmethod from_url(url, *, session=..., client=..., bot_token=None)

Creates a partial Webhook from a webhook URL.

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

Parameters
  • url (str) – The URL of the webhook.

  • session (aiohttp.ClientSession) –

    The session to use to send requests with. Note that the library does not manage the session and will not close it.

    New in version 2.0.

  • client (Client) –

    The client to initialise this webhook with. This allows it to attach the client’s internal state. If session is not given while this is given then the client’s internal session will be used.

    New in version 2.2.

  • bot_token (Optional[str]) –

    The bot authentication token for authenticated requests involving the webhook.

    New in version 2.0.

Raises
Returns

A partial Webhook. A partial webhook is just a webhook object with an ID and a token.

Return type

Webhook

await fetch(*, prefer_auth=True)

This function is a coroutine.

Fetches the current webhook.

This could be used to get a full webhook from a partial webhook.

New in version 2.0.

Note

When fetching with an unauthenticated webhook, i.e. is_authenticated() returns False, then the returned webhook does not contain any user information.

Parameters

prefer_auth (bool) – Whether to use the bot token over the webhook token if available. Defaults to True.

Raises
  • HTTPException – Could not fetch the webhook

  • NotFound – Could not find the webhook by this ID

  • ValueError – This webhook does not have a token associated with it.

Returns

The fetched webhook.

Return type

Webhook

await delete(*, reason=None, prefer_auth=True)

This function is a coroutine.

Deletes this Webhook.

Parameters
  • reason (Optional[str]) –

    The reason for deleting this webhook. Shows up on the audit log.

    New in version 1.4.

  • prefer_auth (bool) –

    Whether to use the bot token over the webhook token if available. Defaults to True.

    New in version 2.0.

Raises
  • HTTPException – Deleting the webhook failed.

  • NotFound – This webhook does not exist.

  • Forbidden – You do not have permissions to delete this webhook.

  • ValueError – This webhook does not have a token associated with it.

await edit(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)

This function is a coroutine.

Edits this Webhook.

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

Parameters
  • name (Optional[str]) – The webhook’s new default name.

  • avatar (Optional[bytes]) – A bytes-like object representing the webhook’s new default avatar.

  • channel (Optional[abc.Snowflake]) –

    The webhook’s new channel. This requires an authenticated webhook.

    New in version 2.0.

  • reason (Optional[str]) –

    The reason for editing this webhook. Shows up on the audit log.

    New in version 1.4.

  • prefer_auth (bool) –

    Whether to use the bot token over the webhook token if available. Defaults to True.

    New in version 2.0.

Raises
  • HTTPException – Editing the webhook failed.

  • NotFound – This webhook does not exist.

  • ValueError – This webhook does not have a token associated with it or it tried editing a channel without authentication.

property avatar

Returns an Asset for the avatar the webhook has.

If the webhook does not have a traditional avatar, None is returned. If you want the avatar that a webhook has displayed, consider display_avatar.

Type

Optional[Asset]

property channel

The channel this webhook belongs to.

If this is a partial webhook, then this will always return None.

Type

Optional[Union[ForumChannel, VoiceChannel, TextChannel]]

property created_at

Returns the webhook’s creation time in UTC.

Type

datetime.datetime

property default_avatar

Returns the default avatar.

New in version 2.0.

Type

Asset

property display_avatar

Returns the webhook’s display avatar.

This is either webhook’s default avatar or uploaded avatar.

New in version 2.0.

Type

Asset

property guild

The guild this webhook belongs to.

If this is a partial webhook, then this will always return None.

Type

Optional[Guild]

is_authenticated()

bool: Whether the webhook is authenticated with a bot token.

New in version 2.0.

is_partial()

bool: Whether the webhook is a “partial” webhook.

New in version 2.0.

await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., thread=..., thread_name=..., wait=False, suppress_embeds=False, silent=False, applied_tags=..., poll=...)

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.

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

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. If the webhook is partial or is not managed by the library, then you can only send URL buttons. Otherwise, you can send views with any type of components.

    New in version 2.0.

  • thread (Snowflake) –

    The thread to send this webhook to.

    New in version 2.0.

  • thread_name (str) –

    The thread name to create with this webhook if the webhook belongs to a ForumChannel. Note that this is mutually exclusive with the thread parameter, as this will create a new thread with the given name.

    New in version 2.0.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This sends the message without any embeds if set to True.

    New in version 2.0.

  • silent (bool) –

    Whether to suppress push and desktop notifications for the message. This will increment the mention counter in the UI, but will not actually send a notification.

    New in version 2.2.

  • applied_tags (List[ForumTag]) –

    Tags to apply to the thread if the webhook belongs to a ForumChannel.

    New in version 2.4.

  • poll (Poll) –

    The poll to send with this message.

    Warning

    When sending a Poll via webhook, you cannot manually end it.

    New in version 2.4.

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 or thread and thread_name.

  • ValueError – The length of embeds was invalid, there was no token associated with this webhook or ephemeral was passed with the improper webhook type or there was no state attached with this webhook when giving it a view that had components other than URL buttons.

Returns

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

Return type

Optional[WebhookMessage]

await fetch_message(id, /, *, thread=...)

This function is a coroutine.

Retrieves a single WebhookMessage owned by this webhook.

New in version 2.0.

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

  • thread (Snowflake) – The thread to look in.

Raises
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

  • ValueError – There was no token associated with this webhook.

Returns

The message asked for.

Return type

WebhookMessage

await edit_message(message_id, *, content=..., embeds=..., embed=..., attachments=..., allowed_mentions=None, thread=...)

This function is a coroutine.

Edits a message owned by this webhook.

This is a lower level interface to WebhookMessage.edit() in case you only have an ID.

New in version 1.6.

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

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

Parameters
  • message_id (int) – The message ID to edit.

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

  • attachments (List[Union[Attachment, File]]) –

    A list of attachments to keep in the message as well as new files to upload. If [] is passed then all attachments are removed.

    New in version 2.0.

  • 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. The webhook must have state attached, similar to send().

    New in version 2.0.

  • thread (Snowflake) –

    The thread the webhook message belongs to.

    New in version 2.0.

Raises
  • HTTPException – Editing the message failed.

  • Forbidden – Edited a message that is not yours.

  • TypeError – You specified both embed and embeds

  • ValueError – The length of embeds was invalid, there was no token associated with this webhook or the webhook had no state.

Returns

The newly edited webhook message.

Return type

WebhookMessage

await delete_message(message_id, /, *, thread=...)

This function is a coroutine.

Deletes a message owned by this webhook.

This is a lower level interface to WebhookMessage.delete() in case you only have an ID.

New in version 1.6.

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

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

Parameters
  • message_id (int) – The message ID to delete.

  • thread (Snowflake) –

    The thread the webhook message belongs to.

    New in version 2.0.

Raises
  • HTTPException – Deleting the message failed.

  • Forbidden – Deleted a message that is not yours.

  • ValueError – This webhook does not have a token associated with it.

WebhookMessage

class discord.WebhookMessage

Represents a message sent from your webhook.

This allows you to edit or delete a message sent by your webhook.

This inherits from discord.Message with changes to edit() and delete() to work.

New in version 1.6.

await edit(*, content=..., embeds=..., embed=..., attachments=..., allowed_mentions=None)

This function is a coroutine.

Edits the message.

New in version 1.6.

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

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

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.

  • attachments (List[Union[Attachment, File]]) –

    A list of attachments to keep in the message as well as new files to upload. If [] is passed then all attachments are removed.

    Note

    New files will always appear after current attachments.

    New in version 2.0.

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

    New in version 2.0.

Raises
  • HTTPException – Editing the message failed.

  • Forbidden – Edited a message that is not yours.

  • TypeError – You specified both embed and embeds

  • ValueError – The length of embeds was invalid or there was no token associated with this webhook.

Returns

The newly edited message.

Return type

WebhookMessage

await add_files(*files)

This function is a coroutine.

Adds new files to the end of the message attachments.

New in version 2.0.

Parameters

*files (File) – New files to add to the message.

Raises
Returns

The newly edited message.

Return type

WebhookMessage

await remove_attachments(*attachments)

This function is a coroutine.

Removes attachments from the message.

New in version 2.0.

Parameters

*attachments (Attachment) – Attachments to remove from the message.

Raises
Returns

The newly edited message.

Return type

WebhookMessage

await delete(*, delay=None)

This function is a coroutine.

Deletes the message.

Parameters

delay (Optional[float]) – If provided, the number of seconds to wait before deleting the message. The waiting is done in the background and deletion failures are ignored.

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

  • NotFound – The message was deleted already.

  • HTTPException – Deleting the message failed.

await accept_activity_invite(*, session_id=None)

This function is a coroutine.

Accepts an activity invite included.

The message must have activity set.

Parameters

session_id (Optional[str]) – The session ID. Only required if user presence is unavailable (e.g. due to being not connected to Gateway).

Raises
  • Forbidden – You are not allowed to accept activity invites.

  • HTTPException – Accepting activity invite failed.

clean_content

A property that returns the content in a “cleaned up” manner. This basically means that mentions are transformed into the way the client shows it. e.g. <#id> will transform into #name.

This will also transform @everyone and @here mentions into non-mentions.

Note

This does not affect markdown. If you want to escape or remove markdown then use utils.escape_markdown() or utils.remove_markdown() respectively, along with this function.

Type

str

property created_at

The message’s creation time in UTC.

Type

datetime.datetime

property edited_at

An aware UTC datetime object containing the edited time of the message.

Type

Optional[datetime.datetime]

property interaction

The interaction that this message is a response to.

New in version 2.0.

Deprecated since version 2.4: This attribute is deprecated and will be removed in a future version. Use interaction_metadata instead.

Type

Optional[MessageInteraction]

is_system()

bool: Whether the message is a system message.

A system message is a message that is constructed entirely by the Discord API in response to something.

New in version 1.3.

property jump_url

Returns a URL that allows the client to jump to this message.

Type

str

raw_channel_mentions

A property that returns an array of channel IDs matched with the syntax of <#channel_id> in the message content.

Type

List[int]

raw_mentions

A property that returns an array of user IDs matched with the syntax of <@user_id> in the message content.

This allows you to receive the user IDs of mentioned users even in a private message context.

Type

List[int]

raw_role_mentions

A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content.

Type

List[int]

system_content

A property that returns the content that is rendered regardless of the Message.type.

In the case of MessageType.default and MessageType.reply, this just returns the regular Message.content. Otherwise this returns an English message denoting the contents of the system message.

Type

str

property thread

The public thread created from this message, if it exists.

Note

For messages received via the gateway this does not retrieve archived threads, as they are not retained in the internal cache. Use fetch_thread() instead.

New in version 2.4.

Type

Optional[Thread]

to_reference(*, fail_if_not_exists=True, type=<MessageReferenceType.default: 0>)

Creates a MessageReference from the current message.

New in version 1.6.

Parameters
  • fail_if_not_exists (bool) –

    Whether the referenced message should raise HTTPException if the message no longer exists or Discord could not fetch the message.

    New in version 1.7.

  • type (MessageReferenceType) –

    The type of message reference.

    New in version 2.5.

Returns

The reference to this message.

Return type

MessageReference

SyncWebhook

class discord.SyncWebhook

Represents a synchronous Discord webhook.

For an asynchronous counterpart, see Webhook.

x == y

Checks if two webhooks are equal.

x != y

Checks if two webhooks are not equal.

hash(x)

Returns the webhooks’s hash.

Changed in version 1.4: Webhooks are now comparable and hashable.

id

The webhook’s ID

Type

int

type

The type of the webhook.

New in version 1.3.

Type

WebhookType

token

The authentication token of the webhook. If this is None then the webhook cannot be used to make requests.

Type

Optional[str]

guild_id

The guild ID this webhook is for.

Type

Optional[int]

channel_id

The channel ID this webhook is for.

Type

Optional[int]

user

The user this webhook was created by. If the webhook was received without authentication then this will be None.

Type

Optional[abc.User]

name

The default name of the webhook.

Type

Optional[str]

source_guild

The guild of the channel that this webhook is following. Only given if type is WebhookType.channel_follower.

New in version 2.0.

Type

Optional[PartialWebhookGuild]

source_channel

The channel that this webhook is following. Only given if type is WebhookType.channel_follower.

New in version 2.0.

Type

Optional[PartialWebhookChannel]

property url

Returns the webhook’s url.

Type

str

classmethod partial(id, token, *, session=..., bot_token=None)

Creates a partial Webhook.

Parameters
  • id (int) – The ID of the webhook.

  • token (str) – The authentication token of the webhook.

  • session (requests.Session) – The session to use to send requests with. Note that the library does not manage the session and will not close it. If not given, the requests auto session creation functions are used instead.

  • bot_token (Optional[str]) – The bot authentication token for authenticated requests involving the webhook.

Returns

A partial SyncWebhook. A partial SyncWebhook is just a SyncWebhook object with an ID and a token.

Return type

SyncWebhook

classmethod from_url(url, *, session=..., bot_token=None)

Creates a partial Webhook from a webhook URL.

Parameters
  • url (str) – The URL of the webhook.

  • session (requests.Session) – The session to use to send requests with. Note that the library does not manage the session and will not close it. If not given, the requests auto session creation functions are used instead.

  • bot_token (Optional[str]) – The bot authentication token for authenticated requests involving the webhook.

Raises

ValueError – The URL is invalid.

Returns

A partial SyncWebhook. A partial SyncWebhook is just a SyncWebhook object with an ID and a token.

Return type

SyncWebhook

fetch(*, prefer_auth=True)

Fetches the current webhook.

This could be used to get a full webhook from a partial webhook.

Note

When fetching with an unauthenticated webhook, i.e. is_authenticated() returns False, then the returned webhook does not contain any user information.

Parameters

prefer_auth (bool) – Whether to use the bot token over the webhook token if available. Defaults to True.

Raises
  • HTTPException – Could not fetch the webhook

  • NotFound – Could not find the webhook by this ID

  • ValueError – This webhook does not have a token associated with it.

Returns

The fetched webhook.

Return type

SyncWebhook

delete(*, reason=None, prefer_auth=True)

Deletes this Webhook.

Parameters
  • reason (Optional[str]) –

    The reason for deleting this webhook. Shows up on the audit log.

    New in version 1.4.

  • prefer_auth (bool) – Whether to use the bot token over the webhook token if available. Defaults to True.

Raises
  • HTTPException – Deleting the webhook failed.

  • NotFound – This webhook does not exist.

  • Forbidden – You do not have permissions to delete this webhook.

  • ValueError – This webhook does not have a token associated with it.

edit(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)

Edits this Webhook.

Parameters
  • name (Optional[str]) – The webhook’s new default name.

  • avatar (Optional[bytes]) – A bytes-like object representing the webhook’s new default avatar.

  • channel (Optional[abc.Snowflake]) – The webhook’s new channel. This requires an authenticated webhook.

  • reason (Optional[str]) –

    The reason for editing this webhook. Shows up on the audit log.

    New in version 1.4.

  • prefer_auth (bool) – Whether to use the bot token over the webhook token if available. Defaults to True.

Raises
  • HTTPException – Editing the webhook failed.

  • NotFound – This webhook does not exist.

  • ValueError – This webhook does not have a token associated with it or it tried editing a channel without authentication.

Returns

The newly edited webhook.

Return type

SyncWebhook

send(content=..., *, username=..., avatar_url=..., tts=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., thread=..., thread_name=..., wait=False, suppress_embeds=False, silent=False, applied_tags=..., poll=...)

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.

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

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

  • thread (Snowflake) –

    The thread to send this message to.

    New in version 2.0.

  • thread_name (str) –

    The thread name to create with this webhook if the webhook belongs to a ForumChannel. Note that this is mutually exclusive with the thread parameter, as this will create a new thread with the given name.

    New in version 2.0.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message. This sends the message without any embeds if set to True.

    New in version 2.0.

  • silent (bool) –

    Whether to suppress push and desktop notifications for the message. This will increment the mention counter in the UI, but will not actually send a notification.

    New in version 2.2.

  • poll (Poll) –

    The poll to send with this message.

    Warning

    When sending a Poll via webhook, you cannot manually end it.

    New in version 2.4.

  • view (View) –

    The view to send with the message. This can only have URL buttons, which donnot require a state to be attached to it.

    If you want to send a view with any component attached to it, check Webhook.send().

    New in version 2.5.

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 or thread and thread_name.

  • ValueError – The length of embeds was invalid, there was no token associated with this webhook or you tried to send a view with components other than URL buttons.

Returns

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

Return type

Optional[SyncWebhookMessage]

fetch_message(id, /, *, thread=...)

Retrieves a single SyncWebhookMessage owned by this webhook.

New in version 2.0.

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

  • thread (Snowflake) – The thread to look in.

Raises
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

  • ValueError – There was no token associated with this webhook.

Returns

The message asked for.

Return type

SyncWebhookMessage

property avatar

Returns an Asset for the avatar the webhook has.

If the webhook does not have a traditional avatar, None is returned. If you want the avatar that a webhook has displayed, consider display_avatar.

Type

Optional[Asset]

property channel

The channel this webhook belongs to.

If this is a partial webhook, then this will always return None.

Type

Optional[Union[ForumChannel, VoiceChannel, TextChannel]]

property created_at

Returns the webhook’s creation time in UTC.

Type

datetime.datetime

property default_avatar

Returns the default avatar.

New in version 2.0.

Type

Asset

property display_avatar

Returns the webhook’s display avatar.

This is either webhook’s default avatar or uploaded avatar.

New in version 2.0.

Type

Asset

edit_message(message_id, *, content=..., embeds=..., embed=..., attachments=..., allowed_mentions=None, thread=...)

Edits a message owned by this webhook.

This is a lower level interface to WebhookMessage.edit() in case you only have an ID.

New in version 1.6.

Parameters
  • message_id (int) – The message ID to edit.

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

  • attachments (List[Union[Attachment, File]]) –

    A list of attachments to keep in the message as well as new files to upload. If [] is passed then all attachments are removed.

    New in version 2.0.

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

  • thread (Snowflake) –

    The thread the webhook message belongs to.

    New in version 2.0.

Raises
  • HTTPException – Editing the message failed.

  • Forbidden – Edited a message that is not yours.

  • TypeError – You specified both embed and embeds

  • ValueError – The length of embeds was invalid or there was no token associated with this webhook.

property guild

The guild this webhook belongs to.

If this is a partial webhook, then this will always return None.

Type

Optional[Guild]

is_authenticated()

bool: Whether the webhook is authenticated with a bot token.

New in version 2.0.

is_partial()

bool: Whether the webhook is a “partial” webhook.

New in version 2.0.

delete_message(message_id, /, *, thread=...)

Deletes a message owned by this webhook.

This is a lower level interface to WebhookMessage.delete() in case you only have an ID.

New in version 1.6.

Parameters
  • message_id (int) – The message ID to delete.

  • thread (Snowflake) –

    The thread the webhook message belongs to.

    New in version 2.0.

Raises
  • HTTPException – Deleting the message failed.

  • Forbidden – Deleted a message that is not yours.

  • ValueError – This webhook does not have a token associated with it.

SyncWebhookMessage

Methods
class discord.SyncWebhookMessage

Represents a message sent from your webhook.

This allows you to edit or delete a message sent by your webhook.

This inherits from discord.Message with changes to edit() and delete() to work.

New in version 2.0.

edit(*, content=..., embeds=..., embed=..., attachments=..., allowed_mentions=None)

Edits the message.

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

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.

  • attachments (List[Union[Attachment, File]]) –

    A list of attachments to keep in the message as well as new files to upload. If [] is passed then all attachments are removed.

    Note

    New files will always appear after current attachments.

    New in version 2.0.

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

Raises
  • HTTPException – Editing the message failed.

  • Forbidden – Edited a message that is not yours.

  • TypeError – You specified both embed and embeds

  • ValueError – The length of embeds was invalid or there was no token associated with this webhook.

Returns

The newly edited message.

Return type

SyncWebhookMessage

add_files(*files)

Adds new files to the end of the message attachments.

New in version 2.0.

Parameters

*files (File) – New files to add to the message.

Raises
Returns

The newly edited message.

Return type

SyncWebhookMessage

remove_attachments(*attachments)

Removes attachments from the message.

New in version 2.0.

Parameters

*attachments (Attachment) – Attachments to remove from the message.

Raises
Returns

The newly edited message.

Return type

SyncWebhookMessage

delete(*, delay=None)

Deletes the message.

Parameters

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

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

  • NotFound – The message was deleted already.

  • HTTPException – Deleting the message failed.

Abstract Base Classes

An abstract base class (also known as an abc) is a class that models can inherit to get their behaviour. Abstract base classes should not be instantiated. They are mainly there for usage with isinstance() and issubclass().

This library has a module related to abstract base classes, in which all the ABCs are subclasses of typing.Protocol.

Snowflake

Attributes
class discord.abc.Snowflake

An ABC that details the common operations on a Discord model.

Almost all Discord models meet this abstract base class.

If you want to create a snowflake on your own, consider using Object.

id

The model’s unique ID.

Type

int

User

class discord.abc.User

An ABC that details the common operations on a Discord user.

The following implement this ABC:

This ABC must also implement Snowflake.

name

The user’s username.

Type

str

discriminator

The user’s discriminator. This is a legacy concept that is no longer used.

Type

str

global_name

The user’s global nickname.

Type

Optional[str]

bot

If the user is a bot account.

Type

bool

system

If the user is a system account.

Type

bool

display_name_style

The style for the display name.

New in version 3.0.

Type

Optional[DisplayNameStyle]

property display_name

Returns the user’s display name.

Type

str

property mention

Returns a string that allows you to mention the given user.

Type

str

property avatar

Returns an Asset that represents the user’s avatar, if present.

Type

Optional[Asset]

property avatar_decoration

Returns an Asset that represents the user’s avatar decoration, if present.

New in version 2.4.

Type

Optional[Asset]

property avatar_decoration_sku_id

Returns an integer that represents the user’s avatar decoration SKU ID, if present.

New in version 2.4.

Type

Optional[int]

property default_avatar

Returns the default avatar for a given user.

Type

Asset

property display_avatar

Returns the user’s display avatar.

For regular users this is just their default avatar or uploaded avatar.

New in version 2.0.

Type

Asset

property primary_guild

Returns the user’s primary guild.

New in version 3.0.

Type

PrimaryGuild

mentioned_in(message)

Checks if the user is mentioned in the specified message.

Parameters

message (Message) – The message to check if you’re mentioned in.

Returns

Indicates if the user is mentioned in the message.

Return type

bool

PrivateChannel

Attributes
class discord.abc.PrivateChannel

An ABC that details the common operations on a private Discord channel.

The following implement this ABC:

This ABC must also implement Snowflake.

me

The user presenting yourself.

Type

ClientUser

GuildChannel

class discord.abc.GuildChannel

An ABC that details the common operations on a Discord guild channel.

The following implement this ABC:

This ABC must also implement Snowflake.

name

The channel name.

Type

str

guild

The guild the channel belongs to.

Type

Guild

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

Type

int

property changed_roles

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type

List[Role]

property mention

The string that allows you to mention the channel.

Type

str

property jump_url

Returns a URL that allows the client to jump to the channel.

New in version 2.0.

Type

str

property created_at

Returns the channel’s creation time in UTC.

Type

datetime.datetime

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

Parameters

obj (Union[Role, User, Object]) – The role or user denoting whose overwrite to get.

Returns

The permission overwrites for this object.

Return type

PermissionOverwrite

property overwrites

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Changed in version 2.0: Overwrites can now be type-aware Object in case of cache lookup failure.

Returns

The channel’s permission overwrites.

Return type

Dict[Union[Role, Member, Object], PermissionOverwrite]

property category

The category this channel belongs to.

If there is no category then this is None.

Type

Optional[CategoryChannel]

property permissions_synced

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

New in version 1.3.

Type

bool

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

  • Implicit permissions

  • Member timeout

  • User installed app

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Changed in version 2.0: The object passed in can now be a role object.

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

Changed in version 2.4: User installed apps are now taken into account. The permissions returned for a user installed app mirrors the permissions Discord returns in app_permissions, though it is recommended to use that attribute instead.

Parameters

obj (Union[Member, Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

Returns

The resolved permissions for the member or role.

Return type

Permissions

Messageable

Methods
class discord.abc.Messageable

An ABC that details the common operations on a model that can send messages.

The following classes implement this ABC:

await send(content=None, *, file=None, files=None, delete_after=None, allowed_mentions=None, metadata=...)

This function is a coroutine.

Sends a message to the destination with the content given.

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

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

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

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

  • file (File) – The file to upload.

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

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

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    New in version 1.4.

  • metadata (Optional[Dict[str, str]]) – The message’s metadata. Can be only up to 25 entries, and 1024 characters per key and value.

Raises
  • HTTPException – Sending the message failed.

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

  • NotFound – You sent a message with the same nonce as one that has been explicitly deleted shortly earlier.

  • ValueError – The files list is not of the appropriate size.

  • TypeError – You specified both file and files.

Returns

The message that was sent.

Return type

Message

Connectable

Methods
class discord.abc.Connectable

An ABC that details the common operations on a channel that can connect to a voice server.

The following implement this ABC:

await connect(*, timeout=30.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, _channel=None, self_deaf=False, self_mute=False, self_video=False)

This function is a coroutine.

Connects to voice and creates a VoiceClient to establish your connection to the voice server.

This requires voice_states.

Parameters
  • timeout (float) – The timeout in seconds to wait the connection to complete.

  • reconnect (bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.

  • cls (Type[VoiceProtocol]) – A type that subclasses VoiceProtocol to connect with. Defaults to VoiceClient.

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

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

  • self_video (bool) – Indicates if the client should show camera.

Raises
Returns

A voice client that is fully connected to the voice server.

Return type

VoiceProtocol

Discord Models

Models are classes that are received from Discord and are not meant to be created by the user of the library.

Danger

The classes listed below are not intended to be created by users and are also read-only.

For example, this means that you should not make your own User instances nor should you modify the User instance yourself.

If you want to get one of these model classes instances they’d have to be through the cache, and a common way of doing so is through the utils.find() function or attributes of model classes that you receive from the events specified in the Event Reference.

Note

Nearly all classes here have __slots__ defined which means that it is impossible to have dynamic attributes to the data classes.

ClientUser

class discord.ClientUser

Represents your Discord user.

x == y

Checks if two users are equal.

x != y

Checks if two users are not equal.

hash(x)

Return the user’s hash.

str(x)

Returns the user’s handle (e.g. name or name#discriminator).

name

The user’s username.

Type

str

id

The user’s unique ID.

Type

int

discriminator

The user’s discriminator. This is a legacy concept that is no longer used.

Type

str

global_name

The user’s global nickname, taking precedence over the username in display.

New in version 2.3.

Type

Optional[str]

bot

Specifies if the user is a bot account.

Type

bool

system

Specifies if the user is a system user (i.e. represents Discord officially).

New in version 1.3.

Type

bool

display_name_style

The style for the display name.

New in version 3.0.

Type

Optional[DisplayNameStyle]

verified

Specifies if the user’s email is verified.

Type

bool

email

The email the user used when registering.

Type

Optional[str]

locale

The IETF language tag used to identify the language the user is using.

Type

Optional[str]

mfa_enabled

Specifies if the user has MFA turned on and working.

Type

bool

premium_type

Specifies the type of premium a user has (i.e. Nitro, Nitro Classic, or Nitro Basic).

Type

PremiumType

await edit(*, global_name=...)

This function is a coroutine.

Edits the current profile of the client.

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

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

Parameters

global_name (str) – The new global name you wish to change to.

Raises

HTTPException – Editing your profile failed.

Returns

The newly edited client user.

Return type

ClientUser

property mutual_guilds

The guilds that the user shares with the client.

Note

This will only return mutual guilds within the client’s internal cache.

New in version 1.7.

Type

List[Guild]

property accent_color

Returns the user’s accent color, if applicable.

A user’s accent color is only shown if they do not have a banner. This will only be available if the user explicitly sets a color.

There is an alias for this named accent_colour.

New in version 2.0.

Note

This information is only available via discord.Client.fetch_user().

Type

Optional[discord.Color]

property accent_colour

Returns the user’s accent colour, if applicable.

A user’s accent colour is only shown if they do not have a banner. This will only be available if the user explicitly sets a colour.

This is an alias of accent_color.

New in version 2.0.

Note

This information is only available via discord.Client.fetch_user().

Type

Optional[discord.Color]

property avatar

Returns an Asset for the avatar the user has.

If the user has not uploaded a global avatar, None is returned. If you want the avatar that a user has displayed, consider display_avatar.

Type

Optional[discord.Asset]

property avatar_decoration

Returns an Asset for the avatar decoration the user has.

If the user has not set an avatar decoration, None is returned.

New in version 2.4.

Type

Optional[discord.Asset]

property avatar_decoration_sku_id

Returns the SKU ID of the avatar decoration the user has.

If the user has not set an avatar decoration, None is returned.

New in version 2.4.

Type

Optional[int]

property banner

Returns the user’s banner asset, if available.

New in version 2.0.

Note

This information is only available via discord.Client.fetch_user().

Type

Optional[discord.Asset]

property color

A property that returns a color denoting the rendered color for the user. This always returns Color.default().

There is an alias for this named colour.

Type

discord.Color

property colour

A property that returns a colour denoting the rendered colour for the user. This always returns Colour.default().

This is an alias of color.

Type

discord.Colour

property created_at

Returns the user’s creation time in UTC.

This is when the user’s Discord account was created.

Type

datetime.datetime

property default_avatar

Returns the default avatar for a given user.

Type

discord.Asset

property display_avatar

Returns the user’s display avatar.

For regular users this is just their default avatar or uploaded avatar.

New in version 2.0.

Type

discord.Asset

property display_name

Returns the user’s display name.

For regular users this is just their global name or their username, but if they have a guild specific nickname then that is returned instead.

Type

str

property game_relationship

Returns the GameRelationship with this user if applicable, None otherwise.

Type

Optional[GameRelationship]

is_blocked()

bool: Checks if the user is blocked.

is_friend()

bool: Checks if the user is your friend.

is_game_friend()

bool: Checks if the user is your friend in-game.

is_ignored()

bool: Checks if the user is ignored.

property mention

Returns a string that allows you to mention the given user.

Type

str

mentioned_in(message)

Checks if the user is mentioned in the specified message.

Parameters

message (discord.Message) – The message to check if you’re mentioned in.

Returns

Indicates if the user is mentioned in the message.

Return type

bool

property primary_guild

Returns the user’s primary guild.

Type

discord.PrimaryGuild

property public_flags

The publicly available flags the user has.

Type

discord.PublicUserFlags

property relationship

Returns the Relationship with this user if applicable, None otherwise.

Type

Optional[Relationship]

property voice

Returns the user’s current voice state.

Type

Optional[discord.VoiceState]

User

class discord.User

Represents a Discord user.

x == y

Checks if two users are equal.

x != y

Checks if two users are not equal.

hash(x)

Return the user’s hash.

str(x)

Returns the user’s handle (e.g. name or name#discriminator).

name

The user’s username.

Type

str

id

The user’s unique ID.

Type

int

discriminator

The user’s discriminator. This is a legacy concept that is no longer used.

Type

str

global_name

The user’s global nickname, taking precedence over the username in display.

New in version 2.3.

Type

Optional[str]

bot

Specifies if the user is a bot account.

Type

bool

system

Specifies if the user is a system user (i.e. represents Discord officially).

Type

bool

display_name_style

The style for the display name.

New in version 3.0.

Type

Optional[DisplayNameStyle]

property dm_channel

Returns the channel associated with this user if it exists.

If this returns None, you can create a DM channel by calling the create_dm() coroutine function.

Type

Optional[Union[DMChannel, EphemeralDMChannel]]

property mutual_groups

The groups that the user shares with the client.

Note

This will only return mutual groups within the client’s internal cache.

Type

List[GroupChannel]

property mutual_guilds

The guilds that the user shares with the client.

Note

This will only return mutual guilds within the client’s internal cache.

New in version 1.7.

Type

List[discord.Guild]

await create_dm()

This function is a coroutine.

Creates a discord.DMChannel with this user.

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

Returns

The channel that was created.

Return type

Union[DMChannel, EphemeralDMChannel]

await block()

This function is a coroutine.

Blocks the user.

Raises
await unblock()

This function is a coroutine.

Unblocks the user.

Raises
await remove_friend()

This function is a coroutine.

Removes the user as a friend.

Raises
  • Forbidden – Not allowed to remove this user as a friend.

  • HTTPException – Removing the user as a friend failed.

await remove_game_friend()

This function is a coroutine.

Removes the user as a in-game friend.

Raises
  • Forbidden – Not allowed to remove this user as a in-game friend.

  • HTTPException – Removing the user as a in-game friend failed.

await send_friend_request()

This function is a coroutine.

Sends the user a friend request.

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

  • HTTPException – Sending the friend request failed.

property accent_color

Returns the user’s accent color, if applicable.

A user’s accent color is only shown if they do not have a banner. This will only be available if the user explicitly sets a color.

There is an alias for this named accent_colour.

New in version 2.0.

Note

This information is only available via discord.Client.fetch_user().

Type

Optional[discord.Color]

property accent_colour

Returns the user’s accent colour, if applicable.

A user’s accent colour is only shown if they do not have a banner. This will only be available if the user explicitly sets a colour.

This is an alias of accent_color.

New in version 2.0.

Note

This information is only available via discord.Client.fetch_user().

Type

Optional[discord.Color]

property avatar

Returns an Asset for the avatar the user has.

If the user has not uploaded a global avatar, None is returned. If you want the avatar that a user has displayed, consider display_avatar.

Type

Optional[discord.Asset]

property avatar_decoration

Returns an Asset for the avatar decoration the user has.

If the user has not set an avatar decoration, None is returned.

New in version 2.4.

Type

Optional[discord.Asset]

property avatar_decoration_sku_id

Returns the SKU ID of the avatar decoration the user has.

If the user has not set an avatar decoration, None is returned.

New in version 2.4.

Type

Optional[int]

property banner

Returns the user’s banner asset, if available.

New in version 2.0.

Note

This information is only available via discord.Client.fetch_user().

Type

Optional[discord.Asset]

property color

A property that returns a color denoting the rendered color for the user. This always returns Color.default().

There is an alias for this named colour.

Type

discord.Color

property colour

A property that returns a colour denoting the rendered colour for the user. This always returns Colour.default().

This is an alias of color.

Type

discord.Colour

property created_at

Returns the user’s creation time in UTC.

This is when the user’s Discord account was created.

Type

datetime.datetime

property default_avatar

Returns the default avatar for a given user.

Type

discord.Asset

property display_avatar

Returns the user’s display avatar.

For regular users this is just their default avatar or uploaded avatar.

New in version 2.0.

Type

discord.Asset

property display_name

Returns the user’s display name.

For regular users this is just their global name or their username, but if they have a guild specific nickname then that is returned instead.

Type

str

property game_relationship

Returns the GameRelationship with this user if applicable, None otherwise.

Type

Optional[GameRelationship]

is_blocked()

bool: Checks if the user is blocked.

is_friend()

bool: Checks if the user is your friend.

is_game_friend()

bool: Checks if the user is your friend in-game.

is_ignored()

bool: Checks if the user is ignored.

property mention

Returns a string that allows you to mention the given user.

Type

str

mentioned_in(message)

Checks if the user is mentioned in the specified message.

Parameters

message (discord.Message) – The message to check if you’re mentioned in.

Returns

Indicates if the user is mentioned in the message.

Return type

bool

property primary_guild

Returns the user’s primary guild.

Type

discord.PrimaryGuild

property public_flags

The publicly available flags the user has.

Type

discord.PublicUserFlags

property relationship

Returns the Relationship with this user if applicable, None otherwise.

Type

Optional[Relationship]

await send(content=None, *, file=None, files=None, delete_after=None, allowed_mentions=None, metadata=...)

This function is a coroutine.

Sends a message to the destination with the content given.

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

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

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

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

  • file (File) – The file to upload.

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

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

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    New in version 1.4.

  • metadata (Optional[Dict[str, str]]) – The message’s metadata. Can be only up to 25 entries, and 1024 characters per key and value.

Raises
  • HTTPException – Sending the message failed.

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

  • NotFound – You sent a message with the same nonce as one that has been explicitly deleted shortly earlier.

  • ValueError – The files list is not of the appropriate size.

  • TypeError – You specified both file and files.

Returns

The message that was sent.

Return type

Message

await send_game_friend_request()

This function is a coroutine.

Sends the user a in-game friend request.

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

  • HTTPException – Sending the game friend request failed.

property voice

Returns the user’s current voice state.

Type

Optional[discord.VoiceState]

Connection

class discord.Connection

Represents a Discord user connection.

New in version 3.0.

x == y

Checks if two connections are equal.

x != y

Checks if two connections are not equal.

hash(x)

Returns the connection’s hash.

str(x)

Returns the connection’s name.

id

The connection’s account ID.

Type

str

type

The connection service type (e.g. YouTube, Twitch, etc.).

Type

ConnectionType

name

The connection’s account name.

Type

str

verified

Whether the connection is verified.

Type

bool

metadata

Various metadata about the connection.

The contents of this are always subject to change.

Type

Optional[dict]

metadata_visible

Whether the connection’s metadata is visible.

Type

bool

revoked

Whether the connection is revoked.

Type

bool

integrations

The integrations attached to the connection.

Type

List[Integration]

friend_sync

Whether friends are synced over the connection.

Type

bool

show_activity

Whether activities from this connection will be shown in presences.

Type

bool

Whether the connection is authorized both ways (i.e. it’s both a connection and an authorization).

Type

bool

visible

Whether the connection is visible on the user’s profile.

Type

bool

Relationship

class discord.Relationship

Represents a relationship in Discord.

A relationship is like a friendship, a person who is blocked, etc.

x == y

Checks if two relationships are equal.

x != y

Checks if two relationships are not equal.

hash(x)

Return the relationship’s hash.

type

The type of relationship you have.

Type

RelationshipType

user

The user you have the relationship with.

Type

User

nick

The user’s friend nickname (if applicable).

Type

Optional[str]

client_status

Model which holds information about the status of the member on various clients/platforms via presence updates.

Type

ClientStatus

activities

The activities that the user is currently doing.

Note

Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.

Type

Tuple[Union[BaseActivity, Spotify]]

spam_request

Whether the friend request was flagged as spam.

Type

bool

stranger_request

Whether the friend request was sent by a user without a mutual friend or small mutual guild.

Type

bool

user_ignored

Whether the target user has been ignored by the current user.

Type

bool

origin_application_id

The application’s ID that created the relationship.

Type

Optional[int]

since

When the relationship was created. Only available for type RelationshipType.friend, RelationshipType.blocked, and RelationshipType.incoming_request.

Type

Optional[datetime]

has_played_game

Whether the user have played the current application.

Type

bool

property id

Returns the relationship’s ID.

Type

int

property status

The user’s overall status.

Note

This is only reliably provided for type RelationshipType.friend.

Type

Status

property raw_status

The user’s overall status as a string value.

Note

This is only reliably provided for type RelationshipType.friend.

Type

str

property mobile_status

The user’s status on a mobile device, if applicable.

Note

This is only reliably provided for type RelationshipType.friend.

Type

Status

property desktop_status

The user’s status on the desktop client, if applicable.

Note

This is only reliably provided for type RelationshipType.friend.

Type

Status

property web_status

The user’s status on the web client, if applicable.

Note

This is only reliably provided for type RelationshipType.friend.

Type

Status

property embedded_status

The user’s status on the embedded client, if applicable.

Note

This is only reliably provided for type RelationshipType.friend.

Type

Status

is_on_mobile()

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

Note

This is only reliably provided for type RelationshipType.friend.

property activity

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

Note

This is only reliably provided for type RelationshipType.friend.

Note

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

Note

A user may have multiple activities, these can be accessed under activities.

Type

Optional[Union[BaseActivity, Spotify]]

await delete()

This function is a coroutine.

Deletes the relationship.

Depending on the type, this could mean unfriending or unblocking the user, denying an incoming friend request, discarding an outgoing friend request, etc.

Raises

HTTPException – Deleting the relationship failed.

await accept()

This function is a coroutine.

Accepts the relationship request. Only applicable for type RelationshipType.incoming_request.

Raises

HTTPException – Accepting the relationship failed.

GameRelationship

discord.GameRelationship
class discord.GameRelationship

Represents a in-game relationship in Discord.

A game relationship is like a friendship, a friend request to/from someone, etc.

New in version 3.0.

x == y

Checks if two relationships are equal.

x != y

Checks if two relationships are not equal.

hash(x)

Returns the relationship’s hash.

application_id

The application’s ID the game relationship belongs to.

Type

int

type

The type of relationship you have.

Type

RelationshipType

user

The user you have the relationship with.

Type

User

client_status

Model which holds information about the status of the member on various clients/platforms via presence updates.

Type

ClientStatus

activities

The activities that the user is currently doing.

Note

Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.

Type

Tuple[Union[BaseActivity, Spotify]]

since

When the relationship was created.

Type

datetime

dm_access_type

The DM access level for the relationship. Currently unknown.

Type

int

property id

Returns the relationship’s ID.

Type

int

property status

The user’s overall status.

Note

This is only reliably provided for type RelationshipType.friend.

Type

Status

property raw_status

The user’s overall status as a string value.

Note

This is only reliably provided for type RelationshipType.friend.

Type

str

property mobile_status

The user’s status on a mobile device, if applicable.

Note

This is only reliably provided for type RelationshipType.friend.

Type

Status

property desktop_status

The user’s status on the desktop client, if applicable.

Note

This is only reliably provided for type RelationshipType.friend.

Type

Status

property web_status

The user’s status on the web client, if applicable.

Note

This is only reliably provided for type RelationshipType.friend.

Type

Status

property embedded_status

The user’s status on the embedded client, if applicable.

Note

This is only reliably provided for type RelationshipType.friend.

Type

Status

is_on_mobile()

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

Note

This is only reliably provided for type RelationshipType.friend.

property activity

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

Note

This is only reliably provided for type RelationshipType.friend.

Note

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

Note

A user may have multiple activities, these can be accessed under activities.

Type

Optional[Union[BaseActivity, Spotify]]

await delete()

This function is a coroutine.

Deletes the game relationship.

Depending on the type, this could mean unfriending the user, denying an incoming friend request, discarding an outgoing friend request, etc.

Raises

HTTPException – Deleting the relationship failed.

await accept()

This function is a coroutine.

Accepts the game relationship request. Only applicable for type RelationshipType.incoming_request.

Raises

HTTPException – Accepting the relationship failed.

Settings

class discord.UserSettings

Represents user settings.

Depending on where they were retrieved from, only some attributes might be present, and rest of attributes are set to their default values.

New in version 3.0.

status

The current status. Defaults to online.

You must have activities.read or presences.read OAuth2 scope for this attribute to be populated.

Type

Status

show_current_game

Whether to show the current game. Defaults to True.

You must have activities.read or presences.read OAuth2 scope for this attribute to be populated.

Type

bool

guild_folders

A list of guild folders.

You must have guilds OAuth2 scope for this attribute to be populated.

Type

List[GuildFolder]

custom_activity

The current custom status.

You must have activities.read or presences.read OAuth2 scope for this attribute to be populated.

Type

Optional[CustomActivity]

allow_activity_party_privacy_friends

Whether to allow friends to join your activity without sending a request.

Defaults to True.

You must have activities.read or presences.write OAuth2 scope for this attribute to be populated.

Type

bool

allow_activity_party_privacy_voice_channel

Whether to allow people in the same voice channel as you to join your activity without sending a request. Does not apply to Community guilds.

Defaults to True.

You must have activities.read or presences.write OAuth2 scope for this attribute to be populated.

Type

bool

receive_in_game_dms

A setting for receiving in-game DMs via the social layer API.

Defaults to all.

Type

SlayerSDKReceiveInGameDMs

soundboard_volume

The volume of the soundboard (0-100).

You must have voice OAuth2 scope for this attribute to be populated.

Warning

This attribute is not updated in real-time, and as such may be out of date sometimes.

Type

Optional[float]

await edit(*, status=..., custom_activity=..., receive_in_game_dms=...)

This function is a coroutine.

Edits the user settings.

All parameters are optional.

Parameters
  • status (Optional[Status]) – The status to set. Pass None to set online.

  • custom_activity (Optional[CustomActivity]) – The custom status to set.

  • receive_in_game_dms (Optional[SlayerSDKReceiveInGameDMs]) –

    The option for receiving in-game DMs via the social layer API.

    Pass None to set all

Raises

HTTPException – Editing the user settings failed.

Returns

The newly updated user settings.

Return type

UserSettings

class discord.GuildFolder

Represents a guild folder (or position if id is None).

New in version 3.0.

id

The folder’s ID.

Type

Optional[int]

name

The folder’s name.

Type

Optional[str]

guild_ids

The guild’s IDs in this folder.

Type

List[int]

raw_color

The folder’s color.

Type

Optional[int]

property color

A property that returns the color for the folder.

There is an alias for this named colour.

Type

Optional[Color]

property colour

A property that returns the colour for the folder.

This is an alias of color.

Type

Optional[Colour]

property guilds

The guilds in this folder.

Type

List[Guild]

class discord.AudioContext
Attributes
Methods
class discord.AudioSettingsManager

Manager for audio settings.

New in version 3.0.

data

The audio settings cache.

Type

Dict[AudioContext, Dict[int, AudioSettings]]

get(context, user_id, *, if_not_exists=True)

Retrieves audio settings from cache.

Parameters
  • context (AudioContext) – The audio context for settings.

  • user_id (int) – The user’s ID to retrieve audio settings for.

  • if_not_exists (bool) –

    Whether to always return non-None value if audio settings were not found for provided user.

    Defaults to True.

Returns

The audio settings.

Return type

Optional[AudioSettings]

of(context)

Retrieve all audio settings for provided context.

This is equivalent to:

return manager.data.get(context, {})
Returns

The mapping of user IDs to audio settings for them.

Return type

Dict[int, AudioSettings]

Attributes
class discord.MuteConfig

An object representing an object’s mute status.

x == y

Checks if two items are muted.

x != y

Checks if two items are not muted.

str(x)

Returns the mute status as a string.

int(x)

Returns the mute status as an int.

New in version 3.0.

muted

Indicates if the object is muted.

Type

bool

until

When the mute will expire.

Type

Optional[datetime.datetime]

Entitlement

class discord.Entitlement

Represents a Discord entitlement.

New in version 3.0.

x == y

Checks if two entitlements are equal.

x != y

Checks if two entitlements are not equal.

hash(x)

Returns the entitlement’s hash.

id

The entitlement’s ID.

Type

int

type

The type of the entitlement.

Type

EntitlementType

sku_id

The ID of the SKU that the entitlement belongs to.

Type

int

application_id

The ID of the application that the entitlement belongs to.

Type

int

user_id

The ID of the user that is granted access to the entitlement.

Type

int

guild_id

The guild’s ID who is granted access to the SKU.

Type

Optional[int]

parent_id

The parent entitlement’s ID.

Type

Optional[int]

deleted

Whether the entitlement has been deleted.

Type

bool

consumed

For consumable items, whether the entitlement has been consumed.

Type

bool

branch_ids

The IDs of the granted application branches.

Type

List[int]

starts_at

A UTC start date after which the entitlement is valid.

Type

Optional[datetime]

ends_at

A UTC date after which entitlement is no longer valid.

Type

Optional[datetime]

promotion_id

The ID of the promotion this entitlement is from.

Type

Optional[int]

subscription_id

The ID of the subscription this entitlement is from.

Type

Optional[int]

gift_batch_id

The ID of the batch the gift attached to this entitlement from.

Type

Optional[int]

gifter_id

The user’s ID who gifted this entitlement.

Type

Optional[int]

gift_style

The style of the gift attached to this entitlement.

Type

Optional[GiftStyle]

fulfillment_status

The tenant fulfillment status of the entitlement.

Type

Optional[EntitlementFulfillmentStatus]

fulfilled_at

When the entitlement was fulfilled.

Type

Optional[datetime]

source_type

The type of the source this entitlement is from.

Type

Optional[EntitlementSourceType]

tenant_metadata

The tenant metadata for the entitlement.

Type

Optional[TenantMetadata]

sku

The granted SKU.

Type

Optional[SKU]

property gift_flags

The gift’s flags.

Type

GiftFlags

property user

The user that is granted access to the entitlement.

Type

Optional[User]

property guild

The guild that is granted access to the entitlement.

Type

Optional[Guild]

property created_at

Returns the entitlement’s creation time in UTC.

Type

datetime.datetime

is_expired()

bool: Returns True if the entitlement is expired. Will be always False for test entitlements.

await consume()

This function is a coroutine.

Marks a one-time purchase entitlement as consumed.

Raises
await delete()

This function is a coroutine.

Deletes the entitlement.

Raises
class discord.Gift

Represents a Discord gift.

New in version 3.0.

x == y

Checks if two gifts are equal.

x != y

Checks if two gifts are not equal.

hash(x)

Returns the gift’s hash.

str(x)

Returns the gift’s URL.

code

The code of the gift.

Type

str

sku_id

The granted SKU’s ID.

Type

int

application_id

The application’s ID that owns granted SKU.

Type

int

uses

How many times the gift has been used.

Type

int

max_uses

The maximum number of times the gift can be used.

Type

int

redeemed

Whether you redeemed this gift.

Type

bool

expires_at

When the gift expires.

Type

Optional[datetime]

batch_id

The batch’s ID this gift is from.

Type

Optional[int]

entitlement_branch_ids

The IDs of the application branches granted by this gift.

Type

List[int]

style

The gift’s style.

Type

Optional[GiftStyle]

user

The user who created this gift.

Type

Optional[User]

subscription_plan_id

The ID of the subscription plan this gift grants.

Type

Optional[int]

property flags

The flags of the gift this entitlement is attached to.

Type

GiftFlags

property url

The URL to this gift.

Type

str

OAuth2

class discord.OAuth2Authorization

Represents an OAuth2 authorization.

application

The application the OAuth2 authorization is associated with.

Type

PartialAppInfo

scopes

The scopes that this OAuth2 authorization grants.

Type

List[str]

expires_at

When the authorization will expire.

Type

datetime

user

The user that created this OAuth2 authorization.

This attribute will be None if identify scope is not granted.

Type

Optional[ClientUser]

class discord.AccessToken

Represents an OAuth2 access token.

type

The type of the token. This always will be Bearer.

Type

str

access_token

The access token.

Type

str

id_token

The ID token. Only applicable when retrieving token for a provisional account.

Type

str

scopes

The scopes the token has.

Type

List[str]

expires_in

Duration in seconds, after which the access token expires.

Type

int

refresh_token

The refresh token for retrieving new access tokens.

When retrieving token for a provisional account, this is populated only for certain authentication providers.

Type

str

guild

The guild to which the bot was added, if applicable.

Type

Optional[Guild]

webhook

The created webhook, if applicable.

Type

Optional[Webhook]

class discord.OAuth2DeviceFlow

Represents an OAuth2 Device flow.

device_code

The internal device code which should be exchanged.

Type

str

code

The code that should be shown to user.

Type

str

verification_uri

The verification URI, without user_code query string parameter.

You can show this URL and value of user_code to user.

Type

str

complete_verification_uri

The verification URI, with an user_code query string parameter. For example: https://discord.com/activate?user_code=ZAW6C586.

This generally should be embedded into QR code and shown to user.

Type

str

expires_in

Duration in seconds after which the flow will be aborted.

Type

int

interval

The interval in seconds for polling the endpoint.

Type

int

await poll(*, external_auth_token=None, external_auth_type=None)

This function is a coroutine.

Starts polling for an access token.

Parameters
  • external_auth_token (Optional[str]) – The external authentication token. If this is provided, then external_auth_type must be provided as well.

  • external_auth_type (Optional[ExternalAuthenticationProviderType]) – The external authentication provider type. If this is provided, then external_auth_token must be provided as well.

Raises
  • LoginFailure – The user aborted the process, or the device code expired.

  • HTTPException – Exchanging the token failed for other reasons.

Returns

The access token.

Return type

AccessToken

GameInvite

class discord.GameInvite

Represents a game invite.

New in version 3.0.

x == y

Checks if two game invites are the same.

x != y

Checks if two game invites are not the same.

hash(x)

Returns the game invite’s hash.

str(x)

Returns a string representation of the game invite.

id

The ID of the game invite.

Type

int

created_at

When the game invite was created.

Type

datetime

ttl

Duration in seconds when the game invite expires in.

Type

int

inviter_id

The ID of the user that invited you to game.

Type

int

recipient_id

The ID of the user that received the game invite.

Type

int

platform_type

The platform type. Currently only xbox is permitted here.

Type

ConnectionType

launch_parameters

The launch parameters, typically a JSON string.

Type

str

parsed_launch_parameters

A dictionary representing the parameters for launching game. It contains the following optional and nullable keys:

  • titleId: A string representing the ID of game invite title. (?)

  • inviteToken: A string representing the game invite token.

Type

Dict[str, Any]

installed

Whether the game is installed.

Type

bool

joinable

Whether the game is joinable.

Type

bool

fallback_url

The URL for installing the game.

Type

Optional[str]

game_icon_url

The game’s icon URL.

Warning

When accessing from discord.Client.create_game_invite(), this will not be a proxied URL.

Type

str

game_name

The game’s name.

Type

str

property inviter

The user that created this invite.

Type

Optional[User]

property recipient

The user that received this game invite.

Type

Optional[User]

PartialStream

Attributes
Methods
class discord.PartialStream

Represents a partial stream.

key

The stream key.

Type

str

await delete()

This function is a coroutine.

Deletes the stream.

This is a WebSocket operation.

await edit(*, paused=..., thumbnail=..., camera_thumbnail=...)

This function is a coroutine.

Edits the stream.

All parameters are optional.

Parameters
  • paused (bool) –

    Whether to pause the stream.

    This is a WebSocket operation.

  • thumbnail (bytes) –

    The stream preview to upload.

    This is an HTTP operation.

  • camera_thumbnail (bytes) –

    The camera stream preview to upload.

    This is an HTTP operation.

Raises

HTTPException – The stream key was invalid, or editing the stream failed.

Returns

The newly updated stream.

Return type

Self

await watch()

This function is a coroutine.

Starts watching the stream.

This is a WebSocket operation.

Stream

class discord.Stream

Represents a stream.

key

The stream key.

Type

str

rtc_server_id

The ID of the RTC server for the stream. This is used when connecting to voice.

May be zero in on_stream_update() if stream was not cached.

Type

int

region

The voice region the stream is in.

Type

str

viewer_ids

The IDs of the viewers currently watching the stream.

Type

List[int]

paused

Whether the stream is paused.

Type

bool

unavailable

Whether the stream is currently unavailable due to outage.

Type

bool

Harvest

class discord.Harvest

Represents an user’s data harvest.

New in version 3.0.

id

The ID of the harvest.

Type

int

user_id

The ID of the user being harvested.

Type

int

email

The email the harvest will be sent to.

Type

str

state

The state of the harvest.

Type

HarvestState

status

The status of the harvest.

Type

HarvestStatus

created_at

When the harvest was created.

Type

datetime

completed_at

When the harvest was completed.

Type

Optional[datetime]

polled_at

When the harvest was last polled.

Type

Optional[datetime]

backends

A dictionary of each backend being harvested to its state.

Type

Dict[HarvestBackendType, HarvestBackendState]

updated_at

When the harvest was last updated.

Type

datetime

shadow_run

Whether the harvest is a shadow run.

Type

bool

user_is_staff

Whether the user being harvested is a Discord employee.

Type

bool

is_provisional

Whether the user being harvested is a provisional user account.

Type

bool

sla_email_sent

Whether an email has been sent informing the user that the archive is taking longer than expected.

Type

bool

bypass_cooldown

Whether the harvest bypasses the cooldown period for requesting harvests.

Type

bool

AutoMod

class discord.AutoModRule

Represents an auto moderation rule.

New in version 2.0.

id

The ID of the rule.

Type

int

guild

The guild the rule is for.

Type

Guild

name

The name of the rule.

Type

str

creator_id

The ID of the user that created the rule.

Type

int

trigger

The rule’s trigger.

Type

AutoModTrigger

enabled

Whether the rule is enabled.

Type

bool

exempt_role_ids

The IDs of the roles that are exempt from the rule.

Type

Set[int]

exempt_channel_ids

The IDs of the channels that are exempt from the rule.

Type

Set[int]

event_type

The type of event that will trigger the the rule.

Type

AutoModRuleEventType

property creator

The member that created this rule.

Type

Optional[Member]

exempt_roles

The roles that are exempt from this rule.

Type

List[Role]

exempt_channels

The channels that are exempt from this rule.

Type

List[Union[abc.GuildChannel, Thread]]

actions

The actions that are taken when this rule is triggered.

Type

List[AutoModRuleAction]

is_exempt(obj, /)

Check if an object is exempt from the automod rule.

Parameters

obj (abc.Snowflake) – The role, channel, or thread to check.

Returns

Whether the object is exempt from the automod rule.

Return type

bool

class discord.AutoModAction

Represents an action that was taken as the result of a moderation rule.

New in version 2.0.

action

The action that was taken.

Type

AutoModRuleAction

message_id

The message ID that triggered the action. This is only available if the action is done on an edited message.

Type

Optional[int]

rule_id

The ID of the rule that was triggered.

Type

int

rule_trigger_type

The trigger type of the rule that was triggered.

Type

AutoModRuleTriggerType

guild_id

The ID of the guild where the rule was triggered.

Type

int

user_id

The ID of the user that triggered the rule.

Type

int

channel_id

The ID of the channel where the rule was triggered.

Type

int

alert_system_message_id

The ID of the system message that was sent to the predefined alert channel.

Type

Optional[int]

content

The content of the message that triggered the rule. Requires the Intents.message_content or it will always return an empty string.

Type

str

matched_keyword

The matched keyword from the triggering message.

Type

Optional[str]

matched_content

The matched content from the triggering message. Requires the Intents.message_content or it will always return None.

Type

Optional[str]

property guild

The guild this action was taken in.

Type

Guild

property channel

The channel this action was taken in.

Type

Optional[Union[abc.GuildChannel, Thread]]

property member

The member this action was taken against /who triggered this rule.

Type

Optional[Member]

Attachment

class discord.Attachment

Represents an attachment from Discord.

str(x)

Returns the URL of the attachment.

x == y

Checks if the attachment is equal to another attachment.

x != y

Checks if the attachment is not equal to another attachment.

hash(x)

Returns the hash of the attachment.

Changed in version 1.7: Attachment can now be casted to str and is hashable.

id

The attachment ID.

Type

int

size

The attachment size in bytes.

Type

int

height

The attachment’s height, in pixels. Only applicable to images and videos.

Type

Optional[int]

width

The attachment’s width, in pixels. Only applicable to images and videos.

Type

Optional[int]

filename

The attachment’s filename.

Type

str

url

The attachment URL. If the message this attachment was attached to is deleted, then this will 404.

Type

str

proxy_url

The proxy URL. This is a cached version of the url in the case of images. When the message is deleted, this URL might be valid for a few minutes or not valid at all.

Type

str

content_type

The attachment’s media type

New in version 1.7.

Type

Optional[str]

description

The attachment’s description. Only applicable to images.

New in version 2.0.

Type

Optional[str]

ephemeral

Whether the attachment is ephemeral.

New in version 2.0.

Type

bool

duration

The duration of the audio file in seconds. Returns None if it’s not a voice message.

New in version 2.3.

Type

Optional[float]

waveform

The waveform (amplitudes) of the audio in bytes. Returns None if it’s not a voice message.

New in version 2.3.

Type

Optional[bytes]

title

The normalised version of the attachment’s filename.

New in version 2.5.

Type

Optional[str]

property flags

The attachment’s flags.

Type

AttachmentFlags

is_spoiler()

bool: Whether this attachment contains a spoiler.

is_voice_message()

bool: Whether this attachment is a voice message.

await save(fp, *, seek_begin=True, use_cached=False)

This function is a coroutine.

Saves this attachment into a file-like object.

Parameters
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is successfully done.

  • use_cached (bool) – Whether to use proxy_url rather than url when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.

Raises
Returns

The number of bytes written.

Return type

int

await read(*, use_cached=False)

This function is a coroutine.

Retrieves the content of this attachment as a bytes object.

New in version 1.1.

Parameters

use_cached (bool) – Whether to use proxy_url rather than url when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.

Raises
  • HTTPException – Downloading the attachment failed.

  • Forbidden – You do not have permissions to access this attachment

  • NotFound – The attachment was deleted.

Returns

The contents of the attachment.

Return type

bytes

await to_file(*, filename=..., description=..., use_cached=False, spoiler=False)

This function is a coroutine.

Converts the attachment into a File suitable for sending via abc.Messageable.send().

New in version 1.3.

Parameters
  • filename (Optional[str]) –

    The filename to use for the file. If not specified then the filename of the attachment is used instead.

    New in version 2.0.

  • description (Optional[str]) –

    The description to use for the file. If not specified then the description of the attachment is used instead.

    New in version 2.0.

  • use_cached (bool) –

    Whether to use proxy_url rather than url when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.

    New in version 1.4.

  • spoiler (bool) –

    Whether the file is a spoiler.

    New in version 1.4.

Raises
  • HTTPException – Downloading the attachment failed.

  • Forbidden – You do not have permissions to access this attachment

  • NotFound – The attachment was deleted.

Returns

The attachment as a file suitable for sending.

Return type

File

Asset

Attributes
class discord.Asset

Represents a CDN asset on Discord.

str(x)

Returns the URL of the CDN asset.

len(x)

Returns the length of the CDN asset’s URL.

x == y

Checks if the asset is equal to another asset.

x != y

Checks if the asset is not equal to another asset.

hash(x)

Returns the hash of the asset.

property url

Returns the underlying URL of the asset.

Type

str

property key

Returns the identifying key of the asset.

Type

str

is_animated()

bool: Returns whether the asset is animated.

replace(*, size=..., format=..., static_format=...)

Returns a new asset with the passed components replaced.

Changed in version 2.0: static_format is now preferred over format if both are present and the asset is not animated.

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

Parameters
  • size (int) – The new size of the asset.

  • format (str) – The new format to change it to. Must be either ‘webp’, ‘jpeg’, ‘jpg’, ‘png’, or ‘gif’ if it’s animated.

  • static_format (str) – The new format to change it to if the asset isn’t animated. Must be either ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’.

Raises

ValueError – An invalid size or format was passed.

Returns

The newly updated asset.

Return type

Asset

with_size(size, /)

Returns a new asset with the specified size.

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

Parameters

size (int) – The new size of the asset.

Raises

ValueError – The asset had an invalid size.

Returns

The new updated asset.

Return type

Asset

with_format(format, /)

Returns a new asset with the specified format.

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

Parameters

format (str) – The new format of the asset.

Raises

ValueError – The asset had an invalid format.

Returns

The new updated asset.

Return type

Asset

with_static_format(format, /)

Returns a new asset with the specified static format.

This only changes the format if the underlying asset is not animated. Otherwise, the asset is not changed.

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

Parameters

format (str) – The new static format of the asset.

Raises

ValueError – The asset had an invalid format.

Returns

The new updated asset.

Return type

Asset

await read()

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

Raises
Returns

The content of the asset.

Return type

bytes

await save(fp, *, seek_begin=True)

This function is a coroutine.

Saves this asset into a file-like object.

Parameters
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is successfully done.

Raises
Returns

The number of bytes written.

Return type

int

await to_file(*, filename=..., description=None, spoiler=False)

This function is a coroutine.

Converts the asset into a File suitable for sending via abc.Messageable.send().

New in version 2.0.

Parameters
  • filename (Optional[str]) – The filename of the file. If not provided, then the filename from the asset’s URL is used.

  • description (Optional[str]) – The description for the file.

  • spoiler (bool) – Whether the file is a spoiler.

Raises
Returns

The asset as a file suitable for sending.

Return type

File

Call

class discord.PrivateCall

Represents the actual group call from Discord.

This is accompanied with a CallMessage denoting the information.

New in version 3.0.

channel

The channel the call is in.

Type

DMChannel

unavailable

Denotes if this call is unavailable.

Type

bool

region

The region the call is being hosted at.

Type

str

property ringing

A list of users that are currently being rung to join the call.

Type

List[abc.User]

property initiator

Returns the user that started the call. Returns None if the message is not cached.

Type

Optional[abc.User]

property connected

Returns whether you’re in the call (this does not mean you’re in the call through the library).

Type

bool

property members

Returns all users that are currently in this call.

Type

List[abc.User]

property voice_states

Returns a mapping of user IDs who have voice states in this call.

Type

Mapping[int, VoiceState]

message

The message associated with this call. Sometimes may not be cached.

Type

Optional[Message]

await change_region(region)

This function is a coroutine.

Changes the channel’s voice region.

Parameters

region (str) – A region to change the voice region to.

Raises

HTTPException – Failed to change the channel’s voice region.

voice_state_for(user)

Retrieves the VoiceState for a specified User.

If the User has no voice state then this function returns None.

Parameters

user (User) – The user to retrieve the voice state for.

Returns

The voice state associated with this user.

Return type

Optional[VoiceState]

class discord.GroupCall

Represents a Discord group call.

This is accompanied with a CallMessage denoting the information.

New in version 3.0.

channel

The channel the group call is in.

Type

GroupChannel

unavailable

Denotes if this group call is unavailable.

Type

bool

region

The region the group call is being hosted in.

Type

str

await change_region(region)

This function is a coroutine.

Changes the channel’s voice region.

Parameters

region (str) – A region to change the voice region to.

Raises

HTTPException – Failed to change the channel’s voice region.

property connected

Returns whether you’re in the call (this does not mean you’re in the call through the library).

Type

bool

property initiator

Returns the user that started the call. Returns None if the message is not cached.

Type

Optional[abc.User]

property members

Returns all users that are currently in this call.

Type

List[abc.User]

message

The message associated with this call. Sometimes may not be cached.

Type

Optional[Message]

property ringing

A list of users that are currently being rung to join the call.

Type

List[abc.User]

voice_state_for(user)

Retrieves the VoiceState for a specified User.

If the User has no voice state then this function returns None.

Parameters

user (User) – The user to retrieve the voice state for.

Returns

The voice state associated with this user.

Return type

Optional[VoiceState]

property voice_states

Returns a mapping of user IDs who have voice states in this call.

Type

Mapping[int, VoiceState]

class discord.CallMessage

Represents a group call message from Discord.

This is only received in cases where the message type is equivalent to MessageType.call.

New in version 3.0.

ended_timestamp

An aware UTC datetime object that represents the time that the call has ended.

Type

Optional[datetime.datetime]

participants

A list of users that participated in the call.

Type

List[User]

message

The message associated with this call message.

Type

Message

property call_ended

Indicates if the call has ended.

Type

bool

property initiator

Returns the user that started the call.

Type

User

property channel

The private channel associated with this message.

Type

PrivateChannel

property duration

Queries the duration of the call.

If the call has not ended then the current duration will be returned.

Returns

The timedelta object representing the duration.

Return type

datetime.timedelta

property participants

A list of users that participated in the call.

Type

List[User]

Message

class discord.Message

Represents a message from Discord.

x == y

Checks if two messages are equal.

x != y

Checks if two messages are not equal.

hash(x)

Returns the message’s hash.

tts

Specifies if the message was done with text-to-speech. This can only be accurately received in on_message() due to a Discord limitation.

Type

bool

type

The type of message. In most cases this should not be checked, but it is helpful in cases where it might be a system message for system_content.

Type

MessageType

author

A Member that sent the message. If channel is a private channel or the user has the left the guild, then it is a User instead.

Type

Union[Member, abc.User]

content

The actual contents of the message. If Intents.message_content is not enabled this will always be an empty string unless the bot is mentioned or the message is a direct message.

Type

str

nonce

The value used by the Discord client to verify that the message is successfully sent. This is not stored long term within Discord’s servers and is only used ephemerally.

Type

Optional[Union[str, int]]

embeds

A list of embeds the message has. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.

Type

List[Embed]

channel

The TextChannel or Thread that the message was sent from. Could be a DMChannel or GroupChannel if it’s a private message.

Type

Union[TextChannel, StageChannel, VoiceChannel, Thread, DMChannel, GroupChannel, PartialMessageable]

reference

The message that this message references. This is only applicable to message replies (MessageType.reply), crossposted messages created by a followed channel integration, forwarded messages, and messages of type:

New in version 1.5.

Type

Optional[MessageReference]

mention_everyone

Specifies if the message mentions everyone.

Note

This does not check if the @everyone or the @here text is in the message itself. Rather this boolean indicates if either the @everyone or the @here text is in the message and it did end up mentioning.

Type

bool

mentions

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

Type

List[abc.User]

channel_mentions

A list of abc.GuildChannel or Thread that were mentioned. If the message is in a private message then the list is always empty.

Type

List[Union[abc.GuildChannel, Thread]]

role_mentions

A list of Role that were mentioned. If the message is in a private message then the list is always empty.

Type

List[Role]

id

The message ID.

Type

int

webhook_id

If this message was sent by a webhook, then this is the webhook ID’s that sent this message.

Type

Optional[int]

attachments

A list of attachments given to a message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.

Type

List[Attachment]

pinned

Specifies if the message is currently pinned.

Type

bool

flags

Extra features of the message.

New in version 1.3.

Type

MessageFlags

reactions

Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.

Type

List[Reaction]

activity

The activity associated with this message. Sent with Rich-Presence related messages that for example, request joining, spectating, or listening to or with another member.

It is a dictionary with the following optional keys:

  • type: An integer denoting the type of message activity being requested.

  • party_id: The party ID associated with the party.

Type

Optional[dict]

application

The rich presence enabled application associated with this message.

Changed in version 2.0: Type is now MessageApplication instead of dict.

Type

Optional[MessageApplication]

stickers

A list of sticker items given to the message.

New in version 1.6.

Type

List[StickerItem]

components

A list of components in the message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.

New in version 2.0.

Type

List[Union[ActionRow, Button, SelectMenu]]

role_subscription

The data of the role subscription purchase or renewal that prompted this MessageType.role_subscription_purchase message.

New in version 2.2.

Type

Optional[RoleSubscriptionInfo]

application_id

The application ID of the application that created this message if this message was sent by an application-owned webhook or an interaction.

New in version 2.2.

Type

Optional[int]

position

A generally increasing integer with potentially gaps or duplicates that represents the approximate position of the message in a thread.

New in version 2.2.

Type

Optional[int]

guild

The guild that the message belongs to, if applicable.

Type

Optional[Guild]

interaction_metadata

The metadata of the interaction that this message is a response to.

New in version 2.4.

Type

Optional[MessageInteractionMetadata]

poll

The poll attached to this message.

New in version 2.4.

Type

Optional[Poll]

call

The call associated with this message.

New in version 2.5.

Type

Optional[CallMessage]

purchase_notification

The data of the purchase notification that prompted this MessageType.purchase_notification message.

New in version 2.5.

Type

Optional[PurchaseNotification]

message_snapshots

The message snapshots attached to this message.

New in version 2.5.

Type

List[MessageSnapshot]

disclosure_type

The message disclosure type.

Type

Optional[AppDisclosureType]

metadata

The message metadata.

This can only be accurately received in on_message() and on_lobby_message() due to a Discord limitation.

Type

Optional[Dict[str, str]]

recipient_id

The DM channel recipient’s ID, sometimes can be your user ID.

Type

Optional[int]

raw_mentions

A property that returns an array of user IDs matched with the syntax of <@user_id> in the message content.

This allows you to receive the user IDs of mentioned users even in a private message context.

Type

List[int]

raw_channel_mentions

A property that returns an array of channel IDs matched with the syntax of <#channel_id> in the message content.

Type

List[int]

raw_role_mentions

A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content.

Type

List[int]

clean_content

A property that returns the content in a “cleaned up” manner. This basically means that mentions are transformed into the way the client shows it. e.g. <#id> will transform into #name.

This will also transform @everyone and @here mentions into non-mentions.

Note

This does not affect markdown. If you want to escape or remove markdown then use utils.escape_markdown() or utils.remove_markdown() respectively, along with this function.

Type

str

property created_at

The message’s creation time in UTC.

Type

datetime.datetime

property edited_at

An aware UTC datetime object containing the edited time of the message.

Type

Optional[datetime.datetime]

property thread

The public thread created from this message, if it exists.

Note

For messages received via the gateway this does not retrieve archived threads, as they are not retained in the internal cache. Use fetch_thread() instead.

New in version 2.4.

Type

Optional[Thread]

property interaction

The interaction that this message is a response to.

New in version 2.0.

Deprecated since version 2.4: This attribute is deprecated and will be removed in a future version. Use interaction_metadata instead.

Type

Optional[MessageInteraction]

await delete(*, delay=None)

This function is a coroutine.

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you must have manage_messages.

Changed in version 1.1: Added the new delay keyword-only parameter.

Parameters

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

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

  • NotFound – The message was deleted already

  • HTTPException – Deleting the message failed.

is_system()

bool: Whether the message is a system message.

A system message is a message that is constructed entirely by the Discord API in response to something.

New in version 1.3.

property jump_url

Returns a URL that allows the client to jump to this message.

Type

str

to_reference(*, fail_if_not_exists=True, type=<MessageReferenceType.default: 0>)

Creates a MessageReference from the current message.

New in version 1.6.

Parameters
  • fail_if_not_exists (bool) –

    Whether the referenced message should raise HTTPException if the message no longer exists or Discord could not fetch the message.

    New in version 1.7.

  • type (MessageReferenceType) –

    The type of message reference.

    New in version 2.5.

Returns

The reference to this message.

Return type

MessageReference

system_content

A property that returns the content that is rendered regardless of the Message.type.

In the case of MessageType.default and MessageType.reply, this just returns the regular Message.content. Otherwise this returns an English message denoting the contents of the system message.

Type

str

await edit(*, content=..., attachments=..., delete_after=None, allowed_mentions=...)

This function is a coroutine.

Edits the message.

The content must be able to be transformed into a string via str(content).

Changed in version 1.3: The suppress keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.

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

Parameters
  • content (Optional[str]) – The new content to replace the message with. Could be None to remove the content.

  • attachments (List[Union[Attachment, File]]) –

    A list of attachments to keep in the message as well as new files to upload. If [] is passed then all attachments are removed.

    Note

    New files will always appear after current attachments.

    New in version 2.0.

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

  • allowed_mentions (Optional[AllowedMentions]) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    New in version 1.4.

Raises
  • HTTPException – Editing the message failed.

  • Forbidden – Tried to suppress a message without permissions or edited a message’s content or embed that isn’t yours.

  • NotFound – This message does not exist.

Returns

The newly edited message.

Return type

Message

await add_files(*files)

This function is a coroutine.

Adds new files to the end of the message attachments.

New in version 2.0.

Parameters

*files (File) – New files to add to the message.

Raises
Returns

The newly edited message.

Return type

Message

await remove_attachments(*attachments)

This function is a coroutine.

Removes attachments from the message.

New in version 2.0.

Parameters

*attachments (Attachment) – Attachments to remove from the message.

Raises
Returns

The newly edited message.

Return type

Message

await accept_activity_invite(*, session_id=None)

This function is a coroutine.

Accepts an activity invite included.

The message must have activity set.

Parameters

session_id (Optional[str]) – The session ID. Only required if user presence is unavailable (e.g. due to being not connected to Gateway).

Raises
  • Forbidden – You are not allowed to accept activity invites.

  • HTTPException – Accepting activity invite failed.

DeletedReferencedMessage

Attributes
class discord.DeletedReferencedMessage

A special sentinel type given when the resolved message reference points to a deleted message.

The purpose of this class is to separate referenced messages that could not be fetched and those that were previously fetched but have since been deleted.

New in version 1.6.

property id

The message ID of the deleted referenced message.

Type

int

property channel_id

The channel ID of the deleted referenced message.

Type

int

property guild_id

The guild ID of the deleted referenced message.

Type

Optional[int]

Reaction

class discord.Reaction

Represents a reaction to a message.

Depending on the way this object was created, some of the attributes can have a value of None.

x == y

Checks if two reactions are equal. This works by checking if the emoji is the same. So two messages with the same reaction will be considered “equal”.

x != y

Checks if two reactions are not equal.

hash(x)

Returns the reaction’s hash.

str(x)

Returns the string form of the reaction’s emoji.

emoji

The reaction emoji. May be a custom emoji, or a unicode emoji.

Type

Union[Emoji, PartialEmoji, str]

count

Number of times this reaction was made. This is a sum of normal_count and burst_count.

Type

int

me

If the user sent this reaction.

Type

bool

message

Message this reaction is for.

Type

Message

me_burst

If the user sent this super reaction.

New in version 2.4.

Type

bool

normal_count

The number of times this reaction was made using normal reactions. This is not available in the gateway events such as on_reaction_add() or on_reaction_remove().

New in version 2.4.

Type

int

burst_count

The number of times this reaction was made using super reactions. This is not available in the gateway events such as on_reaction_add() or on_reaction_remove().

New in version 2.4.

Type

int

is_custom_emoji()

bool: If this is a custom emoji.

MessageInteraction

Attributes
class discord.MessageInteraction

Represents the interaction that a Message is a response to.

New in version 2.0.

x == y

Checks if two message interactions are equal.

x != y

Checks if two message interactions are not equal.

hash(x)

Returns the message interaction’s hash.

id

The interaction ID.

Type

int

type

The interaction type.

Type

InteractionType

name

The name of the interaction.

Type

str

user

The user or member that invoked the interaction.

Type

Union[User, Member]

property created_at

The interaction’s creation time in UTC.

Type

datetime.datetime

Component

Attributes
class discord.Component

Represents a Discord Bot UI Kit Component.

The components supported by Discord are:

This class is abstract and cannot be instantiated.

New in version 2.0.

property type

The type of component.

Type

ComponentType

Attributes
class discord.ActionRow

Represents a Discord Bot UI Kit Action Row.

This is a component that holds up to 5 children components in a row.

This inherits from Component.

New in version 2.0.

id

The ID of this component.

New in version 3.0.

Type

Optional[int]

children

The children components that this holds, if any.

Type

List[Union[Button, SelectMenu, TextInput]]

property type

The type of component.

Type

ComponentType

class discord.Button

Represents a button from the Discord Bot UI Kit.

This inherits from Component.

New in version 2.0.

id

The ID of this component.

New in version 3.0.

Type

Optional[int]

style

The style of the button.

Type

ButtonStyle

custom_id

The ID of the button that gets received during an interaction. If this button is for a URL, it does not have a custom ID.

Type

Optional[str]

url

The URL this button sends you to.

Type

Optional[str]

disabled

Whether the button is disabled or not.

Type

bool

label

The label of the button, if any.

Type

Optional[str]

emoji

The emoji of the button, if available.

Type

Optional[PartialEmoji]

sku_id

The SKU ID this button sends you to, if available.

New in version 2.4.

Type

Optional[int]

property type

The type of component.

Type

ComponentType

class discord.SelectMenu

Represents a select menu from the Discord Bot UI Kit.

A select menu is functionally the same as a dropdown, however on mobile it renders a bit differently.

New in version 2.0.

id

The ID of this component.

New in version 3.0.

Type

Optional[int]

type

The type of component.

Type

ComponentType

custom_id

The ID of the select menu that gets received during an interaction.

Type

Optional[str]

placeholder

The placeholder text that is shown if nothing is selected, if any.

Type

Optional[str]

min_values

The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 0 and 25.

Type

int

max_values

The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

Type

int

options

A list of options that can be selected in this menu.

Type

List[SelectOption]

disabled

Whether the select is disabled or not.

Type

bool

channel_types

A list of channel types that are allowed to be chosen in this select menu.

Type

List[ChannelType]

class discord.SelectOption

Represents a select menu’s option.

While these can be created by users, it’s not very useful since user accounts can not send any components.

New in version 2.0.

Parameters
  • label (str) – The label of the option. This is displayed to users. Can only be up to 100 characters.

  • value (str) – The value of the option. This is not displayed to users. If not provided when constructed then it defaults to the label. Can only be up to 100 characters.

  • description (Optional[str]) – An additional description of the option, if any. Can only be up to 100 characters.

  • emoji (Optional[Union[str, Emoji, PartialEmoji]]) – The emoji of the option, if available.

  • default (bool) – Whether this option is selected by default.

label

The label of the option. This is displayed to users.

Type

str

value

The value of the option. This is not displayed to users. If not provided when constructed then it defaults to the label.

Type

str

description

An additional description of the option, if any.

Type

Optional[str]

default

Whether this option is selected by default.

Type

bool

property emoji

The emoji of the option, if available.

Type

Optional[PartialEmoji]

class discord.TextInput

Represents a text input from the Discord Bot UI Kit.

New in version 2.0.

id

The ID of this component.

New in version 3.0.

Type

Optional[int]

custom_id

The ID of the text input that gets received during an interaction.

Type

Optional[str]

label

The label to display above the text input.

Type

str

style

The style of the text input.

Type

TextStyle

placeholder

The placeholder text to display when the text input is empty.

Type

Optional[str]

value

The default value of the text input.

Type

Optional[str]

required

Whether the text input is required.

Type

bool

min_length

The minimum length of the text input.

Type

Optional[int]

max_length

The maximum length of the text input.

Type

Optional[int]

property type

The type of component.

Type

ComponentType

property default

The default value of the text input.

This is an alias to value.

Type

Optional[str]

class discord.Section

Represents a section from the Discord Bot UI Kit.

This inherits from Component.

New in version 3.0.

id

The ID of this component.

Type

Optional[int]

components

The components on this section.

Warning

The types of children components are subject to change (but not removed). Never assume this will contain only TextDisplay's.

Type

List[TextDisplay]

accessory

The section accessory.

Warning

The types of children components are subject to change (but not removed). Never assume this will be only Button or Thumbnail.

Type

Union[Button, Thumbnail]

property type

The type of component.

Type

ComponentType

Attributes
class discord.TextDisplay

Represents a text display from the Discord Bot UI Kit.

This inherits from Component.

New in version 3.0.

id

The ID of this component.

Type

Optional[int]

content

The content that this display shows.

Type

str

property type

The type of component.

Type

ComponentType

class discord.UnfurledMediaItem

Represents an unfurled media item.

New in version 3.0.

Parameters

url (str) – The URL of this media item. This can be an arbitrary url or a reference to a local file uploaded as an attachment within the message, which can be accessed with the attachment://<filename> format.

url

The URL of this media item.

Type

str

proxy_url

The proxy URL. This is a cached version of the url in the case of images. When the message is deleted, this URL might be valid for a few minutes or not valid at all.

Type

Optional[str]

height

The media item’s height, in pixels. Only applicable to images and videos.

Type

Optional[int]

width

The media item’s width, in pixels. Only applicable to images and videos.

Type

Optional[int]

content_type

The media item’s content type.

Type

str

placeholder

The media item’s placeholder.

Type

Optional[str]

loading_state

The loading state of this media item.

Type

Optional[MediaItemLoadingState]

content_scan_version

The version of the content scan filter.

Type

Optiona[int]

attachment_id

The ID of the attachment this media item points to, only available if the URL points to a local file uploaded within the component message.

Type

Optional[int]

property content_scan_flags

The media scan flags.

Type

MediaScanFlags

property flags

This media item’s flags.

Type

AttachmentFlags

await read()

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

Raises
Returns

The content of the asset.

Return type

bytes

await save(fp, *, seek_begin=True)

This function is a coroutine.

Saves this asset into a file-like object.

Parameters
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is successfully done.

Raises
Returns

The number of bytes written.

Return type

int

await to_file(*, filename=..., description=None, spoiler=False)

This function is a coroutine.

Converts the asset into a File suitable for sending via abc.Messageable.send().

New in version 2.0.

Parameters
  • filename (Optional[str]) – The filename of the file. If not provided, then the filename from the asset’s URL is used.

  • description (Optional[str]) – The description for the file.

  • spoiler (bool) – Whether the file is a spoiler.

Raises
Returns

The asset as a file suitable for sending.

Return type

File

class discord.MediaGalleryItem

Represents a MediaGalleryComponent media item.

New in version 3.0.

media

The media item data. This can be a string representing a local file uploaded as an attachment in the message, which can be accessed using the attachment://<filename> format, or an arbitrary url.

Type

Union[str, UnfurledMediaItem]

description

The description to show within this item. Up to 256 characters. Defaults to None.

Type

Optional[str]

spoiler

Whether this item is flagged as a spoiler.

Type

bool

class discord.Thumbnail

Represents a thumbnail from the Discord Bot UI Kit.

This inherits from Component.

New in version 3.0.

id

The ID of this component.

Type

Optional[int]

media

The media item data.

Type

UnfurledMediaItem

description

The description to show within this item. Up to 256 characters.

Type

Optional[str]

spoiler

Whether this item is flagged as a spoiler.

Type

bool

property type

The type of component.

Type

ComponentType

Attributes
class discord.MediaGallery

Represents a media gallery from the Discord Bot UI Kit.

This inherits from Component.

New in version 3.0.

id

The ID of this component.

Type

Optional[int]

items

The items in this media gallery.

Type

List[MediaGalleryItem]

property type

The type of component.

Type

ComponentType

Attributes
class discord.FileComponent

Represents a file from the Discord Bot UI Kit.

This inherits from Component.

New in version 3.0.

id

The ID of this component.

Type

Optional[int]

media

The unfurled attachment contents of the file.

Type

UnfurledMediaItem

spoiler

Whether this file is flagged as a spoiler.

Type

bool

name

The displayed file name.

Type

str

size

The file size in MiB.

Type

int

property type

The type of component.

Type

ComponentType

Attributes
class discord.Separator

Represents a Separator from the Discord Bot UI Kit.

This inherits from Component.

New in version 3.0.

id

The ID of this component.

Type

Optional[int]

visible

Whether this separator is visible and shows a divider.

Type

bool

spacing

The spacing size of the separator.

Type

SeparatorSpacing

property type

The type of component.

Type

ComponentType

Attributes
class discord.ContentInventoryEntry

Represents an activity feed entry.

This inherits from Component.

New in version 3.0.

id

The ID of this component.

Type

Optional[int]

property type

The type of component.

Type

ComponentType

class discord.Container

Represents a Container from the Discord Bot UI Kit.

This inherits from Component.

New in version 3.0.

id

The ID of this component.

Type

Optional[int]

children

This container’s children.

Type

List[Component]

spoiler

Whether this container is flagged as a spoiler.

Type

bool

property accent_color

The container’s accent color.

Type

Optional[Color]

property accent_colour

The container’s accent color.

Type

Optional[Color]

property type

The type of component.

Type

ComponentType

AppCommand

class discord.BaseCommand

An ABC that represents an application command.

The following implement this ABC:

New in version 3.0.

id

The command’s ID.

Type

int

application_id

The ID of the application this command belongs to.

Type

int

version

The command’s version.

Type

int

type

The type of application command.

Type

AppCommandType

name

The command’s name.

Type

str

name_localized

The localized command’s name.

Type

Optional[str]

name_localizations

The localized names of the application command. Used for display purposes.

Type

Dict[Locale, str]

description

The command’s description.

Type

str

description_localized

The localized command’s description.

Type

str

description_localizations

The localized descriptions of the application command. Used for display purposes.

Type

Dict[Locale, str]

guild_id

The ID of the guild this command is registered in. A value of None denotes that it is a global command.

Type

Optional[int]

dm_permission

A boolean that indicates whether this command can be run in direct messages.

Type

bool

allowed_contexts

The contexts that this command is allowed to be used in. Overrides the dm_permission attribute.

Type

Optional[AppCommandContext]

allowed_installs

The installation contexts that this command is allowed to be installed in.

Type

Optional[AppInstallationType]

nsfw

Whether the command is NSFW and should only work in NSFW channels.

Type

bool

property default_member_permissions

The default permissions required to use this command.

Note

This may be overrided on a guild-by-guild basis.

Type

Optional[Permissions]

property guild

Returns the guild this command is registered to if it exists.

Type

Optional[Guild]

property mention

Returns a string that allows you to mention the command.

Type

str

is_group()

bool: Whether this command is a group.

await delete()

This function is a coroutine.

Deletes the application command.

Raises
  • NotFound – The application command was not found.

  • Forbidden – You do not have permission to delete this application command.

  • HTTPException – Deleting the application command failed.

  • TypeError – The application command was global.

class discord.SlashCommand

Represents a slash command.

This inherits from BaseCommand.

New in version 3.0.

x == y

Checks if two commands are equal.

x != y

Checks if two commands are not equal.

hash(x)

Return the command’s hash.

str(x)

Returns the command’s name.

options

A list of options.

Type

List[Union[Argument, SlashCommandGroup]]

property type

The type of application command. This is always AppCommandType.chat_input.

Type

AppCommandType

is_group()

Query whether this command is a group.

Returns

Whether this command is a group.

Return type

bool

await edit(*, name=..., name_localizations=..., description=..., description_localizations=..., options=..., default_member_permissions=..., dm_permission=..., allowed_contexts=..., allowed_installs=...)

This function is a coroutine.

Edits the command.

All parameters are optional.

Parameters
  • name (str) – The new name for the slash command. Must be between 1 and 32 characters long.

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

    The new name localizations for the slash command.

    Each value must be between 1 and 32 characters.

  • description (str) – The new description for the slash command. Can be only up to 100 characters.

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

    The new description localizations for the slash command.

    Each value can be only up to 100 characters.

  • options (List[Union[Option, SlashCommandGroup]]) – The new options for the slash command.

  • default_member_permissions (Optional[Permissions]) – The new default permissions needed to use this slash command. Pass value of None to remove any permission requirements.

  • dm_permission (bool) –

    Indicates if the application command can be used in DMs.

    Deprecated since version 3.0: Edit allowed_contexts instead.

  • allowed_contexts (Optional[AppCommandContext]) – The new contexts that this command should be allowed to be used in. Overrides the dm_permission parameter.

  • allowed_installs (Optional[AppInstallationType]) – The new installation contexts that this command should be allowed to be installed in.

Raises
  • NotFound – The application command was not found.

  • Forbidden – You do not have permission to edit this application command.

  • HTTPException – Editing the application command failed.

  • TypeError – The application command was global.

Returns

The newly edited slash command.

Return type

SlashCommand

property default_member_permissions

The default permissions required to use this command.

Note

This may be overrided on a guild-by-guild basis.

Type

Optional[Permissions]

await delete()

This function is a coroutine.

Deletes the application command.

Raises
  • NotFound – The application command was not found.

  • Forbidden – You do not have permission to delete this application command.

  • HTTPException – Deleting the application command failed.

  • TypeError – The application command was global.

property guild

Returns the guild this command is registered to if it exists.

Type

Optional[Guild]

property mention

Returns a string that allows you to mention the command.

Type

str

Methods
class discord.UserCommand

Represents an user command.

This inherits from BaseCommand.

New in version 3.0.

x == y

Checks if two commands are equal.

x != y

Checks if two commands are not equal.

hash(x)

Return the command’s hash.

str(x)

Returns the command’s name.

property type

The type of application command. This is always AppCommandType.user.

Type

AppCommandType

await edit(*, name=..., name_localizations=..., description=..., description_localizations=..., default_member_permissions=..., dm_permission=..., allowed_contexts=..., allowed_installs=...)

This function is a coroutine.

Edits the command.

All parameters are optional.

Parameters
  • name (str) – The new name for the user command. Must be between 1 and 32 characters long.

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

    The new name localizations for the user command.

    Each value must be between 1 and 32 characters.

  • description (str) – The new description for the user command. Can be only up to 100 characters.

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

    The new description localizations for the user command.

    Each value can be only up to 100 characters.

  • default_member_permissions (Optional[Permissions]) – The new default permissions needed to use this user command. Pass value of None to remove any permission requirements.

  • dm_permission (bool) –

    Indicates if the application command can be used in DMs.

    Deprecated since version 3.0: Edit allowed_contexts instead.

  • allowed_contexts (Optional[AppCommandContext]) – The new contexts that this command should be allowed to be used in. Overrides the dm_permission parameter.

  • allowed_installs (Optional[AppInstallationType]) – The new installation contexts that this command should be allowed to be installed in.

Raises
  • NotFound – The application command was not found.

  • Forbidden – You do not have permission to edit this application command.

  • HTTPException – Editing the application command failed.

  • TypeError – The application command was global.

Returns

The newly edited user command.

Return type

UserCommand

property default_member_permissions

The default permissions required to use this command.

Note

This may be overrided on a guild-by-guild basis.

Type

Optional[Permissions]

await delete()

This function is a coroutine.

Deletes the application command.

Raises
  • NotFound – The application command was not found.

  • Forbidden – You do not have permission to delete this application command.

  • HTTPException – Deleting the application command failed.

  • TypeError – The application command was global.

property guild

Returns the guild this command is registered to if it exists.

Type

Optional[Guild]

is_group()

bool: Whether this command is a group.

property mention

Returns a string that allows you to mention the command.

Type

str

Methods
class discord.MessageCommand

Represents a message command.

This inherits from BaseCommand.

New in version 3.0.

x == y

Checks if two commands are equal.

x != y

Checks if two commands are not equal.

hash(x)

Return the command’s hash.

str(x)

Returns the command’s name.

property type

The type of application command. This is always AppCommandType.message.

Type

AppCommandType

await edit(*, name=..., name_localizations=..., description=..., description_localizations=..., default_member_permissions=..., dm_permission=..., allowed_contexts=..., allowed_installs=...)

This function is a coroutine.

Edits the command.

All parameters are optional.

Parameters
  • name (str) – The new name for the message command. Must be between 1 and 32 characters long.

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

    The new name localizations for the message command.

    Each value must be between 1 and 32 characters.

  • description (str) – The new description for the message command. Can be only up to 100 characters.

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

    The new description localizations for the message command.

    Each value can be only up to 100 characters.

  • default_member_permissions (Optional[Permissions]) – The new default permissions needed to use this message command. Pass value of None to remove any permission requirements.

  • dm_permission (bool) –

    Indicates if the application command can be used in DMs.

    Deprecated since version 3.0: Edit allowed_contexts instead.

  • allowed_contexts (Optional[AppCommandContext]) – The new contexts that this command should be allowed to be used in. Overrides the dm_permission parameter.

  • allowed_installs (Optional[AppInstallationType]) – The new installation contexts that this command should be allowed to be installed in.

Raises
  • NotFound – The application command was not found.

  • Forbidden – You do not have permission to edit this application command.

  • HTTPException – Editing the application command failed.

  • TypeError – The application command was global.

Returns

The newly edited message command.

Return type

MessageCommand

property default_member_permissions

The default permissions required to use this command.

Note

This may be overrided on a guild-by-guild basis.

Type

Optional[Permissions]

await delete()

This function is a coroutine.

Deletes the application command.

Raises
  • NotFound – The application command was not found.

  • Forbidden – You do not have permission to delete this application command.

  • HTTPException – Deleting the application command failed.

  • TypeError – The application command was global.

property guild

Returns the guild this command is registered to if it exists.

Type

Optional[Guild]

is_group()

bool: Whether this command is a group.

property mention

Returns a string that allows you to mention the command.

Type

str

class discord.PrimaryEntryPointCommand

Represents a primary entry-point command.

This inherits from BaseCommand.

New in version 3.0.

x == y

Checks if two commands are equal.

x != y

Checks if two commands are not equal.

hash(x)

Return the command’s hash.

str(x)

Returns the command’s name.

handler

Determines whether the interaction is handled by the app’s interactions handler or by Discord.

Type

Optional[AppCommandHandler]

property type

The type of application command. This is always AppCommandType.primary_entry_point.

Type

AppCommandType

property default_member_permissions

The default permissions required to use this command.

Note

This may be overrided on a guild-by-guild basis.

Type

Optional[Permissions]

await delete()

This function is a coroutine.

Deletes the application command.

Raises
  • NotFound – The application command was not found.

  • Forbidden – You do not have permission to delete this application command.

  • HTTPException – Deleting the application command failed.

  • TypeError – The application command was global.

property guild

Returns the guild this command is registered to if it exists.

Type

Optional[Guild]

is_group()

bool: Whether this command is a group.

property mention

Returns a string that allows you to mention the command.

Type

str

class discord.UnknownCommand

Represents a command that is not recognized by the library.

This inherits from BaseCommand.

New in version 3.0.

x == y

Checks if two commands are equal.

x != y

Checks if two commands are not equal.

hash(x)

Return the command’s hash.

str(x)

Returns the command’s name.

raw_type

The raw value for the command.

Type

int

raw_payload

The raw data.

Type

Dict[str, Any]

property type

The type of application command. This is always AppCommandType.unknown.

Type

AppCommandType

property default_member_permissions

The default permissions required to use this command.

Note

This may be overrided on a guild-by-guild basis.

Type

Optional[Permissions]

await delete()

This function is a coroutine.

Deletes the application command.

Raises
  • NotFound – The application command was not found.

  • Forbidden – You do not have permission to delete this application command.

  • HTTPException – Deleting the application command failed.

  • TypeError – The application command was global.

property guild

Returns the guild this command is registered to if it exists.

Type

Optional[Guild]

is_group()

bool: Whether this command is a group.

property mention

Returns a string that allows you to mention the command.

Type

str

class discord.Option

Represents an application command option.

New in version 3.0.

type

The type of option.

Type

AppCommandOptionType

name

The name of the option.

Type

str

name_localized

The localized name of the option.

Type

Optional[str]

name_localizations

The localized names of the option. Used for display purposes.

Type

Dict[Locale, str]

description

The description of the option.

Type

str

description_localized

The localized description of the option.

Type

Optional[str]

description_localizations

The localized descriptions of the option. Used for display purposes.

Type

Dict[Locale, str]

required

Whether the option is required.

Type

bool

choices

A list of choices for the command to choose from for this option.

Type

List[Choice]

parent

The parent application command that has this option.

Type

Union[SlashCommand, SlashCommandGroup]

channel_types

The channel types that are allowed for this option.

Type

List[ChannelType]

min_value

The minimum supported value for this option.

Type

Optional[Union[int, float]]

max_value

The maximum supported value for this option.

Type

Optional[Union[int, float]]

min_length

The minimum allowed length for this option.

Type

Optional[int]

max_length

The maximum allowed length for this option.

Type

Optional[int]

autocomplete

Whether the option has autocomplete.

Type

bool

class discord.SlashCommandGroup

Represents an application command subcommand.

New in version 3.0.

type

The type of subcommand.

Type

AppCommandOptionType

name

The name of the subcommand.

Type

str

description

The description of the subcommand.

Type

str

name_localizations

The localised names of the subcommand. Used for display purposes.

Type

Dict[Locale, str]

description_localizations

The localised descriptions of the subcommand. Used for display purposes.

Type

Dict[Locale, str]

options

A list of options.

Type

List[Union[Option, SlashCommandGroup]]

property qualified_name

Returns the fully qualified command name.

The qualified name includes the parent name as well. For example, in a command like /foo bar the qualified name is foo bar.

Type

str

property mention

Returns a string that allows you to mention the given SlashCommandGroup.

Type

str

property parent

The parent application command.

Type

Union[SlashCommand, SlashCommandGroup]

class discord.Choice

Represents an application command argument choice.

New in version 3.0.

x == y

Checks if two choices are equal.

x != y

Checks if two choices are not equal.

hash(x)

Returns the choice’s hash.

Parameters
  • name (str) – The name of the choice. Used for display purposes. Can only be up to 100 characters.

  • name_localized (Optional[str]) – The localized name of the choice.

  • name_localizations (Optional[Dict[Locale, str]]) – The localized names of the choice. Used for display purposes.

  • value (Union[str, int, float]) – The value of the choice. If it’s a string, it can only be up to 100 characters long.

Lobby

class discord.Lobby

Represents a Discord lobby.

New in version 3.0.

x == y

Checks if two lobbies are the same.

x != y

Checks if two lobbies are not the same.

hash(x)

Return the lobby’s hash.

id

The lobby’s ID.

Type

int

application_id

The application’s ID that created the lobby.

Type

int

metadata

The lobby’s metadata.

Type

Optional[Dict[str, str]]

members

The lobby’s members.

Type

List[LobbyMember]

linked_channel

The channel linked to the lobby.

Type

Optional[abc.GuildChannel]

property created_at

Returns the lobby’s creation time in UTC.

Type

datetime.datetime

property voice_states

Returns a mapping of member IDs who have voice states in this lobby.

Note

This function is intentionally low level to replace voice_members when the member cache is unavailable.

Returns

The mapping of member ID to their lobby voice state.

Return type

Mapping[int, LobbyVoiceState]

get_member(user_id, /)

Returns a member with the given ID.

Parameters

user_id (int) – The ID to search for.

Returns

The member or None if not found.

Return type

Optional[LobbyMember]

await leave()

This function is a coroutine.

Leaves the lobby.

Raises

HTTPException – Leaving failed.

await create_invite(*, target=None)

This function is a coroutine.

Creates an invite for channel linked to this lobby.

Parameters

target (Optional[User]) – The user to create the invite for. If None, the invite will be acceptable only by you.

Raises
  • Forbidden – You do not have permissions to create lobby invite.

  • HTTPException – Creating the lobby invite failed.

This function is a coroutine.

Links the lobby to a channel.

You must have can_link_lobby to do this.

Parameters

to (TextChannel) – The channel to link the lobby to.

Raises
  • Forbidden – You do not have permissions to link lobby to a channel.

  • HTTPException – Linking the lobby failed.

Returns

The newly updated lobby.

Return type

Lobby

This function is a coroutine.

Unlinks the lobby from a channel.

You must have can_link_lobby to do this.

Raises
  • Forbidden – You do not have permissions to unlink lobby from a channel.

  • HTTPException – Unlinking the lobby failed.

Returns

The newly updated lobby.

Return type

Lobby

PartialGuild

class discord.PartialGuild

Represents a very partial guild.

New in version 3.0.

x == y

Checks if two guilds are equal.

x != y

Checks if two guilds are not equal.

hash(x)

Returns the guild’s hash.

str(x)

Returns the guild’s name.

id

The guild’s ID.

Type

int

name

The guild’s name.

Type

str

features

A list of features that the guild has. The features that a guild can have are subject to arbitrary change by Discord. A list of guild features can be found in Discord Userdoccers.

Type

List[str]

property created_at

Returns the guild’s creation time in UTC.

Type

datetime.datetime

property icon

Returns the guild’s icon asset, if available.

Type

Optional[Asset]

await create_command(name, *, name_localizations=..., description=..., description_localizations=..., options=..., default_member_permissions=..., dm_permission=..., allowed_contexts=..., allowed_installs=..., type=<AppCommandType.chat_input: 1>)

This function is a coroutine.

Creates an application command for the guild.

New in version 3.0.

Parameters
  • name (str) – The name for the slash command. Must be between 1 and 32 characters long.

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

    The name localizations for the slash command.

    Each value must be between 1 and 32 characters.

  • description (Optional[str]) – The description for the slash command. Can be only up to 100 characters.

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

    The description localizations for the slash command.

    Each value can be only up to 100 characters.

  • options (List[Union[Option, SlashCommandGroup]]) – The options for the slash command.

  • default_member_permissions (Optional[Permissions]) – The default permissions needed to use this application command. Pass value of None to remove any permission requirements.

  • dm_permission (bool) –

    Indicates if the application command can be used in DMs.

    Deprecated since version 3.0: Edit allowed_contexts instead.

  • allowed_contexts (Optional[AppCommandContext]) – The contexts that this command should be allowed to be used in. Overrides the dm_permission parameter.

  • allowed_installs (Optional[AppInstallationType]) – The installation contexts that this command should be allowed to be installed in.

  • type (AppCommandType) – The type for the application command. Defaults to chat_input.

Raises
  • Forbidden – You do not have permission to create application command.

  • HTTPException – Creating the application command failed.

Returns

The application command created.

Return type

Union[SlashCommand, UserCommand, MessageCommand]

await create_message_command(name, *, name_localizations=..., description=..., description_localizations=..., default_member_permissions=..., dm_permission=..., allowed_contexts=..., allowed_installs=...)

This function is a coroutine.

Creates a message command for the guild.

The parameters are same as create_command() except options is removed.

New in version 3.0.

Raises
  • Forbidden – You do not have permission to create application command.

  • HTTPException – Creating the application command failed.

Returns

The message command created.

Return type

MessageCommand

await create_slash_command(name, *, name_localizations=..., description=..., description_localizations=..., options=..., default_member_permissions=..., dm_permission=..., allowed_contexts=..., allowed_installs=...)

This function is a coroutine.

Creates a slash command for the guild.

The parameters are same as create_command().

New in version 3.0.

Raises
  • Forbidden – You do not have permission to create application command.

  • HTTPException – Creating the application command failed.

Returns

The slash command created.

Return type

SlashCommand

await create_user_command(name, *, name_localizations=..., description=..., description_localizations=..., default_member_permissions=..., dm_permission=..., allowed_contexts=..., allowed_installs=...)

This function is a coroutine.

Creates an user command for the guild.

The parameters are same as create_command() except options is removed.

New in version 3.0.

Raises
  • Forbidden – You do not have permission to create application command.

  • HTTPException – Creating the application command failed.

Returns

The user command created.

Return type

UserCommand

await fetch_command(id, /)

This function is a coroutine.

Fetches an application command from the application.

Parameters

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

Raises
  • HTTPException – Fetching the command failed.

  • MissingApplicationID – The application ID could not be found.

  • NotFound – The application command was not found. This could also be because the command is a global command.

Returns

The retrieved command.

Return type

Union[SlashCommand, UserCommand, MessageCommand, UnknownCommand]

await fetch_commands()

This function is a coroutine.

Fetches the application’s current commands.

Raises
Returns

The application’s commands.

Return type

List[Union[SlashCommand, UserCommand, MessageCommand, UnknownCommand]]

await fetch_me()

This function is a coroutine.

Retrieve member version of yourself for this guild.

Similar to Client.fetch_me() except returns Member. This is essentially used to get the member version of yourself.

Raises
  • Forbidden – You do not have proper permissions to fetch member version of yourself for this guild.

  • HTTPException – Retrieving member version of yourself failed.

Returns

The member version of yourself.

Return type

Member

await widget()

This function is a coroutine.

Returns the widget of the guild.

Note

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

Raises
Returns

The guild’s widget.

Return type

Widget

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

This function is a coroutine.

Changes client’s voice state in the guild.

New in version 1.4.

Parameters
  • channel (Optional[Snowflake]) – Channel the client wants to join. You must explicitly pass None to disconnect.

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

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

  • self_video (bool) – Indicates if the client should show camera.

get_partial_slash_command(id, /, *, application_id=None)

Retrieve a very partial slash command that can be used to edit or delete the guild command.

Parameters
  • id (int) – The ID of the command.

  • application_id (Optional[int]) – The ID of the application the command belongs to. This generally should be automatically filled in.

Raises

MissingApplicationID – The ID of the application was not found.

Returns

The partial slash command.

Warning

Most of attributes will be fake, except for id, application_id, and guild_id.

Return type

SlashCommand

get_partial_user_command(id, /, *, application_id=None)

Retrieve a very partial user command that can be used to edit or delete the guild command.

Parameters
  • id (int) – The ID of the command.

  • application_id (Optional[int]) – The ID of the application the command belongs to. This generally should be automatically filled in.

Raises

MissingApplicationID – The ID of the application was not found.

Returns

The partial user command.

Warning

Most of attributes will be fake, except for id, application_id, and guild_id.

Return type

UserCommand

get_partial_message_command(id, /, *, application_id=None)

Retrieve a very partial message command that can be used to edit or delete the guild command.

Parameters
  • id (int) – The ID of the command.

  • application_id (Optional[int]) – The ID of the application the command belongs to. This generally should be automatically filled in.

Raises

MissingApplicationID – The ID of the application was not found.

Returns

The partial message command.

Warning

Most of attributes will be fake, except for id, application_id, and guild_id.

Return type

MessageCommand

UserGuild

class discord.UserGuild

Represents a Discord partial guild.

This is referred to as a “server” in the official Discord UI.

This inherits from UserGuild.

x == y

Checks if two guilds are equal.

x != y

Checks if two guilds are not equal.

hash(x)

Returns the guild’s hash.

str(x)

Returns the guild’s name.

owner

Whether you own the guild.

Type

bool

approximate_member_count

The approximate number of members in the guild. This is None unless the guild is obtained using Client.fetch_guild() or Client.fetch_guilds() with with_counts=True.

Type

Optional[int]

approximate_presence_count

The approximate number of members currently active in the guild. Offline members are excluded. This is None unless the guild is obtained using Client.fetch_guild() or Client.fetch_guilds() with with_counts=True.

Type

Optional[int]

property icon

Returns the guild’s icon asset, if available.

Type

Optional[Asset]

property banner

Returns the guild’s banner asset, if available.

Type

Optional[Asset]

Guild

class discord.Guild

Represents a Discord guild.

This is referred to as a “server” in the official Discord UI.

This inherits from UserGuild.

x == y

Checks if two guilds are equal.

x != y

Checks if two guilds are not equal.

hash(x)

Returns the guild’s hash.

str(x)

Returns the guild’s name.

emojis

All emojis that the guild owns.

Type

Tuple[Emoji, …]

stickers

All stickers that the guild owns.

New in version 2.0.

Type

Tuple[GuildSticker, …]

afk_timeout

The number of seconds until someone is moved to the AFK channel.

Type

int

owner_id

The guild owner’s ID. Use Guild.owner instead.

Type

int

unavailable

Indicates if the guild is unavailable. If this is True then the reliability of other attributes outside of Guild.id is slim and they might all be None. It is best to not do anything with the guild if it is unavailable.

Check the on_guild_unavailable() and on_guild_available() events.

Type

bool

max_presences

The maximum amount of presences for the guild.

Type

Optional[int]

max_members

The maximum amount of members for the guild.

Note

This attribute is only available via Client.fetch_guild().

Type

Optional[int]

max_video_channel_users

The maximum amount of users in a video channel.

New in version 1.4.

Type

Optional[int]

description

The guild’s description.

Type

Optional[str]

verification_level

The guild’s verification level.

Type

VerificationLevel

vanity_url_code

The guild’s vanity URL code, if any.

New in version 2.0.

Type

Optional[str]

explicit_content_filter

The guild’s explicit content filter.

Type

ContentFilter

default_notifications

The guild’s notification settings.

Type

NotificationLevel

premium_tier

The premium tier for this guild. Corresponds to “Nitro Server” in the official UI. The number goes from 0 to 3 inclusive.

Type

int

premium_subscription_count

The number of “boosts” this guild currently has.

Type

int

preferred_locale

The preferred locale for the guild. Used when filtering Server Discovery results to a specific language.

Changed in version 2.0: This field is now an enum instead of a str.

Type

Locale

nsfw_level

The guild’s NSFW level.

New in version 2.0.

Type

NSFWLevel

mfa_level

The guild’s Multi-Factor Authentication requirement level.

Changed in version 2.0: This field is now an enum instead of an int.

Type

MFALevel

premium_progress_bar_enabled

Indicates if the guild has premium AKA server boost level progress bar enabled.

New in version 2.0.

Type

bool

widget_enabled

Indicates if the guild has widget enabled.

New in version 2.0.

Type

bool

max_stage_video_users

The maximum amount of users in a stage video channel.

New in version 2.3.

Type

Optional[int]

property channels

A list of channels that belongs to this guild.

Type

Sequence[abc.GuildChannel]

property threads

A list of threads that you have permission to view.

New in version 2.0.

Type

Sequence[Thread]

property large

Indicates if the guild is a ‘large’ guild.

A large guild is defined as having more than large_threshold count members, which for this library is set to the maximum of 250.

Type

bool

property voice_channels

A list of voice channels that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.

Type

List[VoiceChannel]

property stage_channels

A list of stage channels that belongs to this guild.

New in version 1.7.

This is sorted by the position and are in UI order from top to bottom.

Type

List[StageChannel]

property me

Similar to Client.user except an instance of Member. This is essentially used to get the member version of yourself.

Type

Member

property voice_client

Returns the VoiceProtocol associated with this guild, if any.

Type

Optional[VoiceProtocol]

property text_channels

A list of text channels that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.

Type

List[TextChannel]

property categories

A list of categories that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.

Type

List[CategoryChannel]

property forums

A list of forum channels that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.

Type

List[ForumChannel]

by_category()

Returns every CategoryChannel and their associated channels.

These channels and categories are sorted in the official Discord UI order.

If the channels do not have a category, then the first element of the tuple is None.

Returns

The categories and their associated channels.

Return type

List[Tuple[Optional[CategoryChannel], List[abc.GuildChannel]]]

get_channel_or_thread(channel_id, /)

Returns a channel or thread with the given ID.

New in version 2.0.

Parameters

channel_id (int) – The ID to search for.

Returns

The returned channel or thread or None if not found.

Return type

Optional[Union[Thread, abc.GuildChannel]]

get_channel(channel_id, /)

Returns a channel with the given ID.

Note

This does not search for threads.

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

Parameters

channel_id (int) – The ID to search for.

Returns

The returned channel or None if not found.

Return type

Optional[abc.GuildChannel]

get_thread(thread_id, /)

Returns a thread with the given ID.

Note

This does not always retrieve archived threads, as they are not retained in the internal cache. Use fetch_channel() instead.

New in version 2.0.

Parameters

thread_id (int) – The ID to search for.

Returns

The returned thread or None if not found.

Return type

Optional[Thread]

get_emoji(emoji_id, /)

Returns an emoji with the given ID.

New in version 2.3.

Parameters

emoji_id (int) – The ID to search for.

Returns

The returned Emoji or None if not found.

Return type

Optional[Emoji]

property afk_channel

The channel that denotes the AFK channel.

If no channel is set, then this returns None.

Type

Optional[Union[VoiceChannel, StageChannel]]

property system_channel

Returns the guild’s channel used for system messages.

If no channel is set, then this returns None.

Type

Optional[TextChannel]

property system_channel_flags

Returns the guild’s system channel settings.

Type

SystemChannelFlags

property rules_channel

Return’s the guild’s channel used for the rules. The guild must be a Community guild.

If no channel is set, then this returns None.

New in version 1.3.

Type

Optional[TextChannel]

property public_updates_channel

Return’s the guild’s channel where admins and moderators of the guilds receive notices from Discord. The guild must be a Community guild.

If no channel is set, then this returns None.

New in version 1.4.

Type

Optional[TextChannel]

property safety_alerts_channel

Return’s the guild’s channel used for safety alerts, if set.

For example, this is used for the raid protection setting. The guild must have the COMMUNITY feature.

New in version 2.3.

Type

Optional[TextChannel]

property widget_channel

Returns the widget channel of the guild.

If no channel is set, then this returns None.

New in version 2.3.

Type

Optional[Union[TextChannel, ForumChannel, VoiceChannel, StageChannel]]

property emoji_limit

The maximum number of emoji slots this guild has.

Type

int

property sticker_limit

The maximum number of sticker slots this guild has.

New in version 2.0.

Type

int

property bitrate_limit

The maximum bitrate for voice channels this guild can have.

Type

float

property filesize_limit

The maximum number of bytes files can have when uploaded to this guild.

Type

int

property members

A list of members that belong to this guild.

Type

Sequence[Member]

get_member(user_id, /)

Returns a member with the given ID.

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

Parameters

user_id (int) – The ID to search for.

Returns

The member or None if not found.

Return type

Optional[Member]

property premium_subscribers

A list of members who have “boosted” this guild.

Type

List[Member]

property roles

Returns a sequence of the guild’s roles in hierarchy order.

The first element of this sequence will be the lowest role in the hierarchy.

Type

Sequence[Role]

get_role(role_id, /)

Returns a role with the given ID.

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

Parameters

role_id (int) – The ID to search for.

Returns

The role or None if not found.

Return type

Optional[Role]

property default_role

Gets the @everyone role that all members have by default.

Type

Role

property premium_subscriber_role

Gets the premium subscriber role, AKA “boost” role, in this guild.

New in version 1.6.

Type

Optional[Role]

property self_role

Gets the role associated with this client’s user, if any.

New in version 1.6.

Type

Optional[Role]

property stage_instances

Returns a sequence of the guild’s stage instances that are currently running.

New in version 2.0.

Type

Sequence[StageInstance]

get_stage_instance(stage_instance_id, /)

Returns a stage instance with the given ID.

New in version 2.0.

Parameters

stage_instance_id (int) – The ID to search for.

Returns

The stage instance or None if not found.

Return type

Optional[StageInstance]

property scheduled_events

Returns a sequence of the guild’s scheduled events.

New in version 2.0.

Type

Sequence[ScheduledEvent]

get_scheduled_event(scheduled_event_id, /)

Returns a scheduled event with the given ID.

New in version 2.0.

Parameters

scheduled_event_id (int) – The ID to search for.

Returns

The scheduled event or None if not found.

Return type

Optional[ScheduledEvent]

property soundboard_sounds

Returns a sequence of the guild’s soundboard sounds.

New in version 2.5.

Type

Sequence[SoundboardSound]

get_soundboard_sound(sound_id, /)

Returns a soundboard sound with the given ID.

New in version 2.5.

Parameters

sound_id (int) – The ID to search for.

Returns

The soundboard sound or None if not found.

Return type

Optional[SoundboardSound]

property owner

The member that owns the guild.

Type

Optional[Member]

property splash

Returns the guild’s invite splash asset, if available.

Type

Optional[Asset]

property discovery_splash

Returns the guild’s discovery splash asset, if available.

Type

Optional[Asset]

property member_count

Returns the member count if available.

Warning

Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires Intents.members to be specified.

Changed in version 2.0: Now returns an Optional[int].

Type

Optional[int]

property chunked

Returns a boolean indicating if the guild is “chunked”.

A chunked guild means that member_count is equal to the number of members stored in the internal members cache.

If this value returns False, then you should request for offline members.

Type

bool

property created_at

Returns the guild’s creation time in UTC.

Type

datetime.datetime

get_member_named(name, /)

Returns the first member found that matches the name provided.

The name is looked up in the following order:

  • Username#Discriminator (deprecated)

  • Username#0 (deprecated, only gets users that migrated from their discriminator)

  • Nickname

  • Global name

  • Username

If no member is found, None is returned.

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

Deprecated since version 2.3: Looking up users via discriminator due to Discord API change.

Parameters

name (str) – The name of the member to lookup.

Returns

The member in this guild with the associated name. If not found then None is returned.

Return type

Optional[Member]

property vanity_url

The Discord vanity invite URL for this guild, if available.

New in version 2.0.

Type

Optional[str]

property invites_paused_until

If invites are paused, returns when invites will get enabled in UTC, otherwise returns None.

New in version 2.4.

Type

Optional[datetime.datetime]

property dms_paused_until

If DMs are paused, returns when DMs will get enabled in UTC, otherwise returns None.

New in version 2.4.

Type

Optional[datetime.datetime]

property dm_spam_detected_at

Returns the time when DM spam was detected in the guild.

New in version 2.5.

Type

datetime.datetime

property raid_detected_at

Returns the time when a raid was detected in the guild.

New in version 2.5.

Type

Optional[datetime.datetime]

invites_paused()

bool: Whether invites are paused in the guild.

New in version 2.4.

dms_paused()

bool: Whether DMs are paused in the guild.

New in version 2.4.

is_dm_spam_detected()

bool: Whether DM spam was detected in the guild.

New in version 2.5.

is_raid_detected()

bool: Whether a raid was detected in the guild.

New in version 2.5.

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

This function is a coroutine.

Changes client’s voice state in the guild.

New in version 1.4.

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

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

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

  • self_video (bool) – Indicates if the client is using video. Do not use.

ScheduledEvent

class discord.ScheduledEvent

Represents a scheduled event in a guild.

New in version 2.0.

x == y

Checks if two scheduled events are equal.

x != y

Checks if two scheduled events are not equal.

hash(x)

Returns the scheduled event’s hash.

id

The scheduled event’s ID.

Type

int

name

The name of the scheduled event.

Type

str

description

The description of the scheduled event.

Type

Optional[str]

entity_type

The type of entity this event is for.

Type

EntityType

entity_id

The ID of the entity this event is for if available.

Type

Optional[int]

start_time

The time that the scheduled event will start in UTC.

Type

datetime.datetime

end_time

The time that the scheduled event will end in UTC.

Type

Optional[datetime.datetime]

privacy_level

The privacy level of the scheduled event.

Type

PrivacyLevel

status

The status of the scheduled event.

Type

EventStatus

user_count

The number of users subscribed to the scheduled event.

Type

int

creator

The user that created the scheduled event.

Type

Optional[User]

creator_id

The ID of the user that created the scheduled event.

New in version 2.2.

Type

Optional[int]

location

The location of the scheduled event.

Type

Optional[str]

property cover_image

The scheduled event’s cover image.

Type

Optional[Asset]

property guild

The guild this scheduled event is in.

Type

Optional[Guild]

property channel

The channel this scheduled event is in.

Type

Optional[Union[VoiceChannel, StageChannel]]

property url

The url for the scheduled event.

Type

str

Integration

class discord.Integration

Represents a guild integration.

New in version 1.4.

id

The integration ID.

Type

Union[int, str]

name

The integration name.

Type

str

guild

The guild of the integration.

Type

Union[Guild, UserGuild]

type

The integration type (i.e. Twitch).

Type

str

enabled

Whether the integration is currently enabled.

Type

bool

account

The account linked to this integration.

Type

IntegrationAccount

user

The user that added this integration.

Type

User

Attributes
class discord.IntegrationAccount

Represents an integration account.

New in version 1.4.

id

The account ID.

Type

str

name

The account name.

Type

str

class discord.BotIntegration

Represents a bot integration on discord.

New in version 2.0.

id

The integration ID.

Type

int

name

The integration name.

Type

str

guild

The guild of the integration.

Type

Guild

type

The integration type (i.e. Twitch).

Type

str

enabled

Whether the integration is currently enabled.

Type

bool

user

The user that added this integration.

Type

User

account

The integration account information.

Type

IntegrationAccount

application

The application tied to this integration.

Type

IntegrationApplication

class discord.IntegrationApplication

Represents an application for a bot integration.

New in version 2.0.

id

The ID for this application.

Type

int

name

The application’s name.

Type

str

icon

The application’s icon hash.

Type

Optional[str]

description

The application’s description. Can be an empty string.

Type

str

summary

The summary of the application. Can be an empty string.

Type

str

user

The bot user on this application.

Type

Optional[User]

class discord.StreamIntegration

Represents a stream integration for Twitch or YouTube.

New in version 2.0.

id

The integration ID.

Type

int

name

The integration name.

Type

str

guild

The guild of the integration.

Type

Guild

type

The integration type (i.e. Twitch).

Type

str

enabled

Whether the integration is currently enabled.

Type

bool

syncing

Where the integration is currently syncing.

Type

bool

enable_emoticons

Whether emoticons should be synced for this integration (currently twitch only).

Type

Optional[bool]

expire_behavior

The behavior of expiring subscribers. Aliased to expire_behaviour as well.

Type

ExpireBehavior

expire_grace_period

The grace period (in days) for expiring subscribers.

Type

int

user

The user for the integration.

Type

User

account

The integration account information.

Type

IntegrationAccount

synced_at

An aware UTC datetime representing when the integration was last synced.

Type

datetime.datetime

property expire_behaviour

An alias for expire_behavior.

Type

ExpireBehavior

property role

Optional[Role] The role which the integration uses for subscribers.

class discord.PartialIntegration

Represents a partial guild integration.

New in version 2.0.

id

The integration ID.

Type

int

name

The integration name.

Type

str

guild

The guild of the integration.

Type

Guild

type

The integration type (i.e. Twitch).

Type

str

account

The account linked to this integration.

Type

IntegrationAccount

application_id

The id of the application this integration belongs to.

Type

Optional[int]

Member

class discord.Member

Represents a Discord member to a Guild.

This implements a lot of the functionality of User.

x == y

Checks if two members are equal. Note that this works with User instances too.

x != y

Checks if two members are not equal. Note that this works with User instances too.

hash(x)

Returns the member’s hash.

str(x)

Returns the member’s handle (e.g. name or name#discriminator).

joined_at

An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.

Type

Optional[datetime.datetime]

activities

The activities that the user is currently doing.

Note

Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.

Type

Tuple[Union[BaseActivity, Spotify]]

guild

The guild that the member belongs to.

Type

Guild

nick

The guild specific nickname of the user. Takes precedence over the global name.

Type

Optional[str]

pending

Whether the member is pending member verification.

New in version 1.6.

Type

bool

premium_since

An aware datetime object that specifies the date and time in UTC when the member used their “Nitro boost” on the guild, if available. This could be None.

Type

Optional[datetime.datetime]

timed_out_until

An aware datetime object that specifies the date and time in UTC that the member’s time out will expire. This will be set to None or a time in the past if the user is not timed out.

New in version 2.0.

Type

Optional[datetime.datetime]

client_status

Model which holds information about the status of the member on various clients/platforms via presence updates.

New in version 2.5.

Type

ClientStatus

property name

Equivalent to User.name

property id

Equivalent to User.id

property discriminator

Equivalent to User.discriminator

property global_name

Equivalent to User.global_name

property bot

Equivalent to User.bot

property system

Equivalent to User.system

property created_at

Equivalent to User.created_at

property default_avatar

Equivalent to User.default_avatar

property avatar

Equivalent to User.avatar

property dm_channel

Equivalent to User.dm_channel

await create_dm()

This function is a coroutine.

Creates a discord.DMChannel with this user.

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

Returns

The channel that was created.

Return type

Union[DMChannel, EphemeralDMChannel]

property mutual_guilds

Equivalent to User.mutual_guilds

property mutual_groups

Equivalent to User.mutual_groups

property public_flags

Equivalent to User.public_flags

property banner

Equivalent to User.banner

property accent_color

Equivalent to User.accent_color

property accent_colour

Equivalent to User.accent_colour

property avatar_decoration

Equivalent to User.avatar_decoration

property avatar_decoration_sku_id

Equivalent to User.avatar_decoration_sku_id

property primary_guild

Equivalent to User.primary_guild

property display_name_style

Equivalent to User.display_name_style

property game_relationship

Equivalent to User.game_relationship

property relationship

Equivalent to User.relationship

is_friend()

bool: Checks if the user is your friend.

is_game_friend()

bool: Checks if the user is your friend in-game.

is_blocked()

bool: Checks if the user is blocked.

is_ignored()

bool: Checks if the user is ignored.

await block()

This function is a coroutine.

Blocks the user.

Raises
await unblock()

This function is a coroutine.

Unblocks the user.

Raises
await remove_friend()

This function is a coroutine.

Removes the user as a friend.

Raises
  • Forbidden – Not allowed to remove this user as a friend.

  • HTTPException – Removing the user as a friend failed.

await remove_game_friend()

This function is a coroutine.

Removes the user as a in-game friend.

Raises
  • Forbidden – Not allowed to remove this user as a in-game friend.

  • HTTPException – Removing the user as a in-game friend failed.

await send_friend_request()

This function is a coroutine.

Sends the user a friend request.

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

  • HTTPException – Sending the friend request failed.

await send_game_friend_request()

This function is a coroutine.

Sends the user a in-game friend request.

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

  • HTTPException – Sending the game friend request failed.

property raw_status

The member’s overall status as a string value.

New in version 1.5.

Type

str

property status

The member’s overall status. If the value is unknown, then it will be a str instead.

Type

Status

property mobile_status

The member’s status on a mobile device, if applicable.

Type

Status

property desktop_status

The member’s status on the desktop client, if applicable.

Type

Status

property web_status

The member’s status on the web client, if applicable.

Type

Status

property embedded_status

The member’s status on the embedded (PlayStation, Xbox, in-game) client, if applicable.

Type

Status

is_on_mobile()

A helper function that determines if a member is active on a mobile device.

Return type

bool

property color

A property that returns a color denoting the rendered color for the member. If the default color is the one rendered then an instance of Color.default() is returned.

There is an alias for this named color.

Type

Color

property colour

A property that returns a colour denoting the rendered colour for the member. If the default colour is the one rendered then an instance of Colour.default() is returned.

This is an alias of color.

Type

Colour

property roles

A list of Role that the member belongs to. Note that the first element of this list is always the default @everyone’ role.

These roles are sorted by their position in the role hierarchy.

Type

List[Role]

property display_icon

A property that returns the role icon that is rendered for this member. If no icon is shown then None is returned.

New in version 2.0.

Type

Optional[Union[str, Asset]]

property mention

Returns a string that allows you to mention the member.

Type

str

property display_name

Returns the user’s display name.

For regular users this is just their global name or their username, but if they have a guild specific nickname then that is returned instead.

Type

str

property display_avatar

Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.

Type

Asset

property guild_avatar

Returns an Asset for the guild avatar the member has. If unavailable, None is returned.

New in version 2.0.

Type

Optional[Asset]

property display_banner

Returns the member’s displayed banner, if any.

This is the member’s guild banner if available, otherwise it’s their global banner. If the member has no banner set then None is returned.

New in version 2.5.

Type

Optional[Asset]

property guild_banner

Returns an Asset for the guild banner the member has. If unavailable, None is returned.

New in version 2.5.

Type

Optional[Asset]

property activity

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

Note

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

Note

A user may have multiple activities, these can be accessed under activities.

Type

Optional[Union[BaseActivity, Spotify]]

mentioned_in(message)

Checks if the member is mentioned in the specified message.

Parameters

message (Message) – The message to check if you’re mentioned in.

Returns

Indicates if the member is mentioned in the message.

Return type

bool

property top_role

Returns the member’s highest role.

This is useful for figuring where a member stands in the role hierarchy chain.

Raises

TypeError – The guild is detached, meaning it’s partial and role cache is missing.

Type

Role

property guild_permissions

Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use abc.GuildChannel.permissions_for().

This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.

Changed in version 2.0: Member timeouts are taken into consideration.

Type

Permissions

property resolved_permissions

Returns the member’s resolved permissions from an interaction.

This is only available in interaction contexts and represents the resolved permissions of the member in the channel the interaction was executed in. This is more or less equivalent to calling abc.GuildChannel.permissions_for() but stored and returned as an attribute by the Discord API rather than computed.

New in version 2.0.

Type

Optional[Permissions]

property voice

Returns the member’s current voice state.

Type

Optional[VoiceState]

property flags

Returns the member’s flags.

New in version 2.2.

Type

MemberFlags

await send(content=None, *, file=None, files=None, delete_after=None, allowed_mentions=None, metadata=...)

This function is a coroutine.

Sends a message to the destination with the content given.

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

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

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

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

  • file (File) – The file to upload.

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

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

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    New in version 1.4.

  • metadata (Optional[Dict[str, str]]) – The message’s metadata. Can be only up to 25 entries, and 1024 characters per key and value.

Raises
  • HTTPException – Sending the message failed.

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

  • NotFound – You sent a message with the same nonce as one that has been explicitly deleted shortly earlier.

  • ValueError – The files list is not of the appropriate size.

  • TypeError – You specified both file and files.

Returns

The message that was sent.

Return type

Message

get_role(role_id, /)

Returns a role with the given ID from roles which the member has.

New in version 2.0.

Parameters

role_id (int) – The ID to search for.

Returns

The role or None if not found in the member’s roles.

Return type

Optional[Role]

is_timed_out()

Returns whether this member is timed out.

New in version 2.0.

Returns

True if the member is timed out. False otherwise.

Return type

bool

LobbyMember

class discord.LobbyMember

Represents a Discord member to a Lobby.

New in version 3.0.

id

The user’s ID.

Type

int

lobby

The lobby the member belongs to.

Type

Lobby

metadata

The member’s metadata.

Type

Optional[Dict[str, str]]

connected

Whether the member is connected to a call in the lobby.

Type

bool

property flags

Returns the lobby member’s flags.

Type

LobbyMemberFlags

property voice

Returns the member’s current voice state.

Type

Optional[LobbyVoiceState]

Spotify

class discord.Spotify

Represents a Spotify listening activity from Discord. This is a special case of Activity that makes it easier to work with the Spotify integration.

x == y

Checks if two activities are equal.

x != y

Checks if two activities are not equal.

hash(x)

Returns the activity’s hash.

str(x)

Returns the string ‘Spotify’.

property type

Returns the activity’s type. This is for compatibility with Activity.

It always returns ActivityType.listening.

Type

ActivityType

property created_at

When the user started listening in UTC.

New in version 1.3.

Type

Optional[datetime]

property color

Returns the Spotify integration color, as a Color.

There is an alias for this named colour.

Type

Color

property colour

Returns the Spotify integration colour, as a Colour.

This is an alias of color.

Type

Colour

property name

The activity’s name. This will always return “Spotify”.

Type

str

property title

The title of the song being played.

Type

str

property artists

The artists of the song being played.

Type

List[str]

property artist

The artist of the song being played.

This does not attempt to split the artist information into multiple artists. Useful if there’s only a single artist.

Type

str

property album

The album that the song being played belongs to.

Type

str

property album_cover_url

The album cover image URL from Spotify’s CDN.

Type

str

property track_id

The track ID used by Spotify to identify this song.

Type

str

property track_url

The track URL to listen on Spotify.

New in version 2.0.

Type

str

property start

When the user started playing this song in UTC.

Type

datetime

property end

When the user will stop playing this song in UTC.

Type

datetime

property duration

The duration of the song being played.

Type

timedelta

property party_id

The party ID of the listening party.

Type

str

VoiceState

class discord.VoiceState

Represents a Discord user’s voice state.

session_id

The Gateway session’s ID the voice state is tied to.

Type

Optional[str]

self_mute

Indicates if the user is currently muted by their own accord.

Type

bool

self_deaf

Indicates if the user is currently deafened by their own accord.

Type

bool

self_stream

Indicates if the user is currently streaming via ‘Go Live’ feature.

New in version 1.3.

Type

bool

self_video

Indicates if the user is currently broadcasting video.

Type

bool

afk

Indicates if the user is currently in the AFK channel in the guild.

Type

bool

mute

Indicates if the user is currently muted by the guild.

Doesn’t apply to private channels.

Type

bool

deaf

Indicates if the user is currently deafened by the guild.

Doesn’t apply to private channels.

Type

bool

suppress

Indicates if the user is suppressed from speaking.

Only applies to stage channels.

New in version 1.7.

Type

bool

requested_to_speak_at

An aware datetime object that specifies the date and time in UTC that the member requested to speak. It will be None if they are not requesting to speak anymore or have been accepted to speak.

Only applicable to stage channels.

New in version 1.7.

Type

Optional[datetime.datetime]

volume

The user’s volume.

New in version 3.0.

Type

Optional[float]

channel

The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.

Type

Optional[Union[VoiceChannel, StageChannel, DMChannel, GroupChannel]]

LobbyVoiceState

class discord.LobbyVoiceState

Represents a Discord user’s voice state in a lobby.

New in version 3.0.

deaf

Indicates if the user is currently deafened by the lobby.

Type

bool

mute

Indicates if the user is currently muted by the lobby.

Type

bool

self_mute

Indicates if the user is currently muted by their own accord.

Type

bool

self_deaf

Indicates if the user is currently deafened by their own accord.

Type

bool

self_stream

Indicates if the user is currently streaming via ‘Go Live’ feature.

Type

bool

self_video

Indicates if the user is currently broadcasting video.

Type

bool

suppress

Indicates if the user is suppressed from speaking.

Only applies to stage channels.

Type

bool

requested_to_speak_at

An aware datetime object that specifies the date and time in UTC that the member requested to speak. It will be None if they are not requesting to speak anymore or have been accepted to speak.

Only applicable to stage channels.

Type

Optional[datetime.datetime]

afk

Indicates if the user is currently in the AFK channel in the guild.

Type

bool

channel

The lobby that the user is currently connected to. None if the user is not currently in a lobby call.

Type

Optional[Lobby]

lobby

The lobby.

Type

Lobby

Emoji

class discord.Emoji

Represents a custom emoji.

Depending on the way this object was created, some of the attributes can have a value of None.

x == y

Checks if two emoji are the same.

x != y

Checks if two emoji are not the same.

hash(x)

Returns the emoji’s hash.

iter(x)

Returns an iterator of (field, value) pairs. This allows this class to be used as an iterable in list/dict/etc constructions.

str(x)

Returns the emoji rendered for Discord.

name

The name of the emoji.

Type

str

id

The emoji’s ID.

Type

int

require_colons

If colons are required to use this emoji in the client (:PJSalt: vs PJSalt).

Type

bool

animated

Whether an emoji is animated or not.

Type

bool

managed

If this emoji is managed by a Twitch integration.

Type

bool

guild_id

The guild ID the emoji belongs to.

Type

int

available

Whether the emoji is available for use.

Type

bool

user

The user that created the emoji. This can only be retrieved using Guild.fetch_emoji() and having manage_emojis.

Or if is_application_owned() is True, this is the team member that uploaded the emoji, or the bot user if it was uploaded using the API and this can only be retrieved using fetch_application_emoji() or fetch_application_emojis().

Type

Optional[User]

property created_at

Returns the emoji’s creation time in UTC.

Type

datetime.datetime

property url

Returns the URL of the emoji.

Type

str

property roles

A list of roles that is allowed to use this emoji.

If roles is empty, the emoji is unrestricted.

Type

List[Role]

property guild

The guild this emoji belongs to.

Type

Guild

is_usable()

bool: Whether the bot can use this emoji.

New in version 1.3.

is_application_owned()

bool: Whether the emoji is owned by an application.

New in version 2.5.

await read()

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

Raises
Returns

The content of the asset.

Return type

bytes

await save(fp, *, seek_begin=True)

This function is a coroutine.

Saves this asset into a file-like object.

Parameters
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is successfully done.

Raises
Returns

The number of bytes written.

Return type

int

await to_file(*, filename=..., description=None, spoiler=False)

This function is a coroutine.

Converts the asset into a File suitable for sending via abc.Messageable.send().

New in version 2.0.

Parameters
  • filename (Optional[str]) – The filename of the file. If not provided, then the filename from the asset’s URL is used.

  • description (Optional[str]) – The description for the file.

  • spoiler (bool) – Whether the file is a spoiler.

Raises
Returns

The asset as a file suitable for sending.

Return type

File

PartialEmoji

class discord.PartialEmoji

Represents a “partial” emoji.

This model will be given in two scenarios:

x == y

Checks if two emoji are the same.

x != y

Checks if two emoji are not the same.

hash(x)

Returns the emoji’s hash.

str(x)

Returns the emoji rendered for Discord.

name

The custom emoji name, if applicable, or the unicode codepoint of the non-custom emoji. This can be None if the emoji got deleted (e.g. removing a reaction with a deleted emoji).

Type

Optional[str]

animated

Whether the emoji is animated or not.

Type

bool

id

The ID of the custom emoji, if applicable.

Type

Optional[int]

classmethod from_str(value)

Converts a Discord string representation of an emoji to a PartialEmoji.

The formats accepted are:

  • a:name:id

  • <a:name:id>

  • name:id

  • <:name:id>

If the format does not match then it is assumed to be a unicode emoji.

New in version 2.0.

Parameters

value (str) – The string representation of an emoji.

Returns

The partial emoji from this string.

Return type

PartialEmoji

is_custom_emoji()

bool: Checks if this is a custom non-Unicode emoji.

is_unicode_emoji()

bool: Checks if this is a Unicode emoji.

property created_at

Returns the emoji’s creation time in UTC, or None if Unicode emoji.

New in version 1.6.

Type

Optional[datetime.datetime]

property url

Returns the URL of the emoji, if it is custom.

If this isn’t a custom emoji then an empty string is returned

Type

str

await read()

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

Raises
Returns

The content of the asset.

Return type

bytes

await save(fp, *, seek_begin=True)

This function is a coroutine.

Saves this asset into a file-like object.

Parameters
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is successfully done.

Raises
Returns

The number of bytes written.

Return type

int

await to_file(*, filename=..., description=None, spoiler=False)

This function is a coroutine.

Converts the asset into a File suitable for sending via abc.Messageable.send().

New in version 2.0.

Parameters
  • filename (Optional[str]) – The filename of the file. If not provided, then the filename from the asset’s URL is used.

  • description (Optional[str]) – The description for the file.

  • spoiler (bool) – Whether the file is a spoiler.

Raises
Returns

The asset as a file suitable for sending.

Return type

File

Role

class discord.Role

Represents a Discord role in a Guild.

x == y

Checks if two roles are equal.

x != y

Checks if two roles are not equal.

x > y

Checks if a role is higher than another in the hierarchy.

x < y

Checks if a role is lower than another in the hierarchy.

x >= y

Checks if a role is higher or equal to another in the hierarchy.

x <= y

Checks if a role is lower or equal to another in the hierarchy.

hash(x)

Return the role’s hash.

str(x)

Returns the role’s name.

id

The ID for the role.

Type

int

guild

The guild the role belongs to.

Type

Guild

name

The name of the role.

Type

str

hoist

Indicates if the role will be displayed separately from other members.

Type

bool

colors

The role colors.

Type

RoleColors

position

The position of the role. This number is usually positive. The bottom role has a position of 0.

Warning

Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.

Type

int

unicode_emoji

The role’s unicode emoji, if available.

Note

If icon is not None, it is displayed as role icon instead of the unicode emoji under this attribute.

If you want the icon that a role has displayed, consider using display_icon.

New in version 2.0.

Type

Optional[str]

managed

Indicates if the role is managed by the guild through some form of integrations such as Twitch.

Type

bool

mentionable

Indicates if the role can be mentioned by users.

Type

bool

tags

The role tags associated with this role.

Type

Optional[RoleTags]

is_default()

bool: Checks if the role is the default role.

is_bot_managed()

bool: Whether the role is associated with a bot.

New in version 1.6.

is_premium_subscriber()

bool: Whether the role is the premium subscriber, AKA “boost”, role for the guild.

New in version 1.6.

is_integration()

bool: Whether the role is managed by an integration.

New in version 1.6.

is_assignable()

bool: Whether the role is able to be assigned or removed by the bot.

New in version 2.0.

property secondary_color

Returns the role’s secondary color.

New in version 2.6.

Type

Optional[Color]

property secondary_colour

Alias for secondary_color.

New in version 2.6.

Type

Optional[Color]

property tertiary_color

Returns the role’s tertiary color.

New in version 2.6.

Type

Optional[Color]

property tertiary_colour

Alias for tertiary_color.

New in version 2.6.

Type

Optional[Color]

property permissions

Returns the role’s permissions.

Type

Permissions

property color

Returns the role’s primary color. An alias exists under colour.

Type

Color

property colour

Returns the role’s primary colour.

This is an alias of color.

Type

Colour

property icon

Returns the role’s icon asset, if available.

Note

If this is None, the role might instead have unicode emoji as its icon if unicode_emoji is not None.

If you want the icon that a role has displayed, consider using display_icon.

New in version 2.0.

Type

Optional[Asset]

property display_icon

Returns the role’s display icon, if available.

New in version 2.0.

Type

Optional[Union[Asset, str]]

property created_at

Returns the role’s creation time in UTC.

Type

datetime.datetime

property mention

Returns a string that allows you to mention a role.

Type

str

property members

Returns all the members with this role.

Type

List[Member]

property flags

Returns the role’s flags.

New in version 2.4.

Type

RoleFlags

RoleTags

class discord.RoleTags

Represents tags on a role.

A role tag is a piece of extra information attached to a managed role that gives it context for the reason the role is managed.

While this can be accessed, a useful interface is also provided in the Role and Guild classes as well.

New in version 1.6.

bot_id

The bot’s user ID that manages this role.

Type

Optional[int]

integration_id

The integration ID that manages the role.

Type

Optional[int]

subscription_listing_id

The ID of this role’s subscription SKU and listing.

New in version 2.2.

Type

Optional[int]

is_bot_managed()

bool: Whether the role is associated with a bot.

is_premium_subscriber()

bool: Whether the role is the premium subscriber, AKA “boost”, role for the guild.

is_integration()

bool: Whether the role is managed by an integration.

is_available_for_purchase()

bool: Whether the role is available for purchase.

New in version 2.2.

is_guild_connection()

bool: Whether the role is a guild’s linked role.

New in version 2.2.

PartialMessageable

class discord.PartialMessageable

Represents a partial messageable to aid with working messageable channels when only a channel ID is present.

The only way to construct this class is through Client.get_partial_messageable().

Note that this class is trimmed down and has no rich attributes.

New in version 2.0.

x == y

Checks if two partial messageables are equal.

x != y

Checks if two partial messageables are not equal.

hash(x)

Returns the partial messageable’s hash.

id

The channel ID associated with this partial messageable.

Type

int

guild_id

The guild ID associated with this partial messageable.

Type

Optional[int]

type

The channel type associated with this partial messageable, if given.

Type

Optional[ChannelType]

property guild

The guild this partial messageable is in.

Type

Optional[Guild]

property jump_url

Returns a URL that allows the client to jump to the channel.

Type

str

property created_at

Returns the channel’s creation time in UTC.

Type

datetime.datetime

await send(content=None, *, file=None, files=None, delete_after=None, allowed_mentions=None, metadata=...)

This function is a coroutine.

Sends a message to the destination with the content given.

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

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

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

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

  • file (File) – The file to upload.

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

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

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    New in version 1.4.

  • metadata (Optional[Dict[str, str]]) – The message’s metadata. Can be only up to 25 entries, and 1024 characters per key and value.

Raises
  • HTTPException – Sending the message failed.

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

  • NotFound – You sent a message with the same nonce as one that has been explicitly deleted shortly earlier.

  • ValueError – The files list is not of the appropriate size.

  • TypeError – You specified both file and files.

Returns

The message that was sent.

Return type

Message

permissions_for(obj=None, /)

Handles permission resolution for a User.

This function is there for compatibility with other channel types.

Since partial messageables cannot reasonably have the concept of permissions, this will always return Permissions.none().

Parameters

obj (User) – The user to check permissions for. This parameter is ignored but kept for compatibility with other permissions_for methods.

Returns

The resolved permissions.

Return type

Permissions

property mention

Returns a string that allows you to mention the channel.

New in version 2.5.

Type

str

get_partial_message(message_id, /)

Creates a PartialMessage from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

Parameters

message_id (int) – The message ID to create a partial message for.

Returns

The partial message.

Return type

PartialMessage

TextChannel

class discord.TextChannel

Represents a Discord guild text channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns the channel’s name.

name

The channel name.

Type

str

guild

The guild the channel belongs to.

Type

Guild

id

The channel ID.

Type

int

category_id

The category channel ID this channel belongs to, if applicable.

Type

Optional[int]

topic

The channel’s topic. None if it doesn’t exist.

Type

Optional[str]

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

Type

int

linked_lobby

The lobby linked to the channel.

New in version 3.0.

Type

Optional[LinkedLobby]

last_message_id

The last message ID of the message sent to this channel. It may not point to an existing or valid message.

Type

Optional[int]

slowmode_delay

The number of seconds a member must wait between sending messages in this channel. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode.

Type

int

nsfw

If the channel is marked as “not safe for work” or “age restricted”.

Type

bool

default_auto_archive_duration

The default auto archive duration in minutes for threads created in this channel.

New in version 2.0.

Type

int

default_thread_slowmode_delay

The default slowmode delay in seconds for threads created in this channel.

New in version 2.3.

Type

int

property type

The channel’s Discord type.

Type

ChannelType

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

  • Implicit permissions

  • Member timeout

  • User installed app

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Changed in version 2.0: The object passed in can now be a role object.

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

Changed in version 2.4: User installed apps are now taken into account. The permissions returned for a user installed app mirrors the permissions Discord returns in app_permissions, though it is recommended to use that attribute instead.

Parameters

obj (Union[Member, Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

Returns

The resolved permissions for the member or role.

Return type

Permissions

property members

Returns all members that can see this channel.

Type

List[Member]

property threads

Returns all the threads that you can see.

New in version 2.0.

Type

List[Thread]

is_nsfw()

bool: Checks if the channel is NSFW.

is_news()

bool: Checks if the channel is a news channel.

property last_message

Retrieves the last message from this channel in cache.

The message might not be valid or point to an existing message.

Reliable Fetching

For a slightly more reliable method of fetching the last message, consider using either history() or fetch_message() with the last_message_id attribute.

Returns

The last message in this channel or None if not found.

Return type

Optional[Message]

get_partial_message(message_id, /)

Creates a PartialMessage from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

New in version 1.6.

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

Parameters

message_id (int) – The message ID to create a partial message for.

Returns

The partial message.

Return type

PartialMessage

get_thread(thread_id, /)

Returns a thread with the given ID.

Note

This does not always retrieve archived threads, as they are not retained in the internal cache. Use Guild.fetch_channel() instead.

New in version 2.0.

Parameters

thread_id (int) – The ID to search for.

Returns

The returned thread or None if not found.

Return type

Optional[Thread]

property category

The category this channel belongs to.

If there is no category then this is None.

Type

Optional[CategoryChannel]

property changed_roles

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type

List[Role]

property created_at

Returns the channel’s creation time in UTC.

Type

datetime.datetime

property jump_url

Returns a URL that allows the client to jump to the channel.

New in version 2.0.

Type

str

property mention

The string that allows you to mention the channel.

Type

str

property overwrites

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Changed in version 2.0: Overwrites can now be type-aware Object in case of cache lookup failure.

Returns

The channel’s permission overwrites.

Return type

Dict[Union[Role, Member, Object], PermissionOverwrite]

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

Parameters

obj (Union[Role, User, Object]) – The role or user denoting whose overwrite to get.

Returns

The permission overwrites for this object.

Return type

PermissionOverwrite

property permissions_synced

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

New in version 1.3.

Type

bool

await send(content=None, *, file=None, files=None, delete_after=None, allowed_mentions=None, metadata=...)

This function is a coroutine.

Sends a message to the destination with the content given.

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

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

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

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

  • file (File) – The file to upload.

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

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

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    New in version 1.4.

  • metadata (Optional[Dict[str, str]]) – The message’s metadata. Can be only up to 25 entries, and 1024 characters per key and value.

Raises
  • HTTPException – Sending the message failed.

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

  • NotFound – You sent a message with the same nonce as one that has been explicitly deleted shortly earlier.

  • ValueError – The files list is not of the appropriate size.

  • TypeError – You specified both file and files.

Returns

The message that was sent.

Return type

Message

class discord.LinkedLobby

Represents channel link to a lobby.

New in version 3.0.

application_id

The application’s ID the lobby belongs to.

Type

int

lobby_id

The lobby’s ID the channel was linked to.

Type

int

linker_id

The user’s ID who linked channel to a lobby.

Type

int

linked_at

When the channel was linked to a lobby.

Type

datetime

property lobby

The lobby the channel was linked to.

Type

Optional[Lobby]

property linker

The user who linked channel to a lobby.

Type

Optional[User]

ForumChannel

class discord.ForumChannel

Represents a Discord guild forum channel.

New in version 2.0.

x == y

Checks if two forums are equal.

x != y

Checks if two forums are not equal.

hash(x)

Returns the forum’s hash.

str(x)

Returns the forum’s name.

name

The forum name.

Type

str

guild

The guild the forum belongs to.

Type

Guild

id

The forum ID.

Type

int

category_id

The category channel ID this forum belongs to, if applicable.

Type

Optional[int]

topic

The forum’s topic. None if it doesn’t exist. Called “Guidelines” in the UI. Can be up to 4096 characters long.

Type

Optional[str]

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

Type

int

last_message_id

The last thread ID that was created on this forum. This technically also coincides with the message ID that started the thread that was created. It may not point to an existing or valid thread or message.

Type

Optional[int]

slowmode_delay

The number of seconds a member must wait between creating threads in this forum. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode.

Type

int

nsfw

If the forum is marked as “not safe for work” or “age restricted”.

Type

bool

default_auto_archive_duration

The default auto archive duration in minutes for threads created in this forum.

Type

int

default_thread_slowmode_delay

The default slowmode delay in seconds for threads created in this forum.

New in version 2.1.

Type

int

default_reaction_emoji

The default reaction emoji for threads created in this forum to show in the add reaction button.

New in version 2.1.

Type

Optional[PartialEmoji]

default_layout

The default layout for posts in this forum channel. Defaults to ForumLayoutType.not_set.

New in version 2.2.

Type

ForumLayoutType

default_sort_order

The default sort order for posts in this forum channel.

New in version 2.3.

Type

Optional[ForumOrderType]

property type

The channel’s Discord type.

Type

ChannelType

property members

Returns all members that can see this channel.

New in version 2.5.

Type

List[Member]

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

  • Implicit permissions

  • Member timeout

  • User installed app

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Changed in version 2.0: The object passed in can now be a role object.

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

Changed in version 2.4: User installed apps are now taken into account. The permissions returned for a user installed app mirrors the permissions Discord returns in app_permissions, though it is recommended to use that attribute instead.

Parameters

obj (Union[Member, Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

Returns

The resolved permissions for the member or role.

Return type

Permissions

get_thread(thread_id, /)

Returns a thread with the given ID.

Note

This does not always retrieve archived threads, as they are not retained in the internal cache. Use Guild.fetch_channel() instead.

New in version 2.2.

Parameters

thread_id (int) – The ID to search for.

Returns

The returned thread or None if not found.

Return type

Optional[Thread]

property threads

Returns all the threads that you can see.

Type

List[Thread]

property flags

The flags associated with this thread.

New in version 2.1.

Type

ChannelFlags

property available_tags

Returns all the available tags for this forum.

New in version 2.1.

Type

Sequence[ForumTag]

get_tag(tag_id, /)

Returns the tag with the given ID.

New in version 2.1.

Parameters

tag_id (int) – The ID to search for.

Returns

The tag with the given ID, or None if not found.

Return type

Optional[ForumTag]

is_nsfw()

bool: Checks if the forum is NSFW.

is_media()

bool: Checks if the channel is a media channel.

New in version 2.4.

property category

The category this channel belongs to.

If there is no category then this is None.

Type

Optional[CategoryChannel]

property changed_roles

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type

List[Role]

property created_at

Returns the channel’s creation time in UTC.

Type

datetime.datetime

property jump_url

Returns a URL that allows the client to jump to the channel.

New in version 2.0.

Type

str

property mention

The string that allows you to mention the channel.

Type

str

property overwrites

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Changed in version 2.0: Overwrites can now be type-aware Object in case of cache lookup failure.

Returns

The channel’s permission overwrites.

Return type

Dict[Union[Role, Member, Object], PermissionOverwrite]

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

Parameters

obj (Union[Role, User, Object]) – The role or user denoting whose overwrite to get.

Returns

The permission overwrites for this object.

Return type

PermissionOverwrite

property permissions_synced

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

New in version 1.3.

Type

bool

Thread

class discord.Thread

Represents a Discord thread.

x == y

Checks if two threads are equal.

x != y

Checks if two threads are not equal.

hash(x)

Returns the thread’s hash.

str(x)

Returns the thread’s name.

New in version 2.0.

name

The thread name.

Type

str

guild

The guild the thread belongs to.

Type

Guild

id

The thread ID. This is the same as the thread starter message ID.

Type

int

parent_id

The parent TextChannel or ForumChannel ID this thread belongs to.

Type

int

owner_id

The user’s ID that created this thread.

Type

int

last_message_id

The last message ID of the message sent to this thread. It may not point to an existing or valid message.

Type

Optional[int]

slowmode_delay

The number of seconds a member must wait between sending messages in this thread. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode.

Type

int

message_count

An approximate number of messages in this thread.

Type

int

member_count

An approximate number of members in this thread. This caps at 50.

Type

int

me

A thread member representing yourself, if you’ve joined the thread. This could not be available.

Type

Optional[ThreadMember]

archived

Whether the thread is archived.

Type

bool

locked

Whether the thread is locked.

Type

bool

invitable

Whether non-moderators can add other non-moderators to this thread. This is always True for public threads.

Type

bool

archiver_id

The user’s ID that archived this thread.

Note

Due to an API change, the archiver_id will always be None and can only be obtained via the audit log.

Type

Optional[int]

auto_archive_duration

The duration in minutes until the thread is automatically hidden from the channel list. Usually a value of 60, 1440, 4320 and 10080.

Type

int

archive_timestamp

An aware timestamp of when the thread’s archived status was last updated in UTC.

Type

datetime.datetime

property type

The channel’s Discord type.

Type

ChannelType

property parent

The parent channel this thread belongs to.

Type

Optional[Union[ForumChannel, TextChannel]]

property flags

The flags associated with this thread.

Type

ChannelFlags

property owner

The member this thread belongs to.

Type

Optional[Member]

property mention

The string that allows you to mention the thread.

Type

str

property jump_url

Returns a URL that allows the client to jump to the thread.

New in version 2.0.

Type

str

property members

A list of thread members in this thread.

This requires Intents.members to be properly filled. Most of the time however, this data is not provided by the gateway and a call to fetch_members() is needed.

Type

List[ThreadMember]

property applied_tags

A list of tags applied to this thread.

New in version 2.1.

Type

List[ForumTag]

property starter_message

Returns the thread starter message from the cache.

The message might not be cached, valid, or point to an existing message.

Note that the thread starter message ID is the same ID as the thread.

Returns

The thread starter message or None if not found.

Return type

Optional[Message]

property last_message

Returns the last message from this thread from the cache.

The message might not be valid or point to an existing message.

Reliable Fetching

For a slightly more reliable method of fetching the last message, consider using either history() or fetch_message() with the last_message_id attribute.

Returns

The last message in this channel or None if not found.

Return type

Optional[Message]

property category

The category channel the parent channel belongs to, if applicable.

Raises

ClientException – The parent channel was not cached and returned None.

Returns

The parent channel’s category.

Return type

Optional[CategoryChannel]

property category_id

The category channel ID the parent channel belongs to, if applicable.

Raises

ClientException – The parent channel was not cached and returned None.

Returns

The parent channel’s category ID.

Return type

Optional[int]

property created_at

An aware timestamp of when the thread was created in UTC.

Note

This timestamp only exists for threads created after 9 January 2022, otherwise returns None.

is_private()

bool: Whether the thread is a private thread.

A private thread is only viewable by those that have been explicitly invited or have manage_threads.

is_news()

bool: Whether the thread is a news thread.

A news thread is a thread that has a parent that is a news channel, i.e. TextChannel.is_news() is True.

is_nsfw()

bool: Whether the thread is NSFW or not.

An NSFW thread is a thread that has a parent that is an NSFW channel, i.e. TextChannel.is_nsfw() is True.

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

Since threads do not have their own permissions, they mostly inherit them from the parent channel with some implicit permissions changed.

Parameters

obj (Union[Member, Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

Raises

ClientException – The parent channel was not cached and returned None

Returns

The resolved permissions for the member or role.

Return type

Permissions

ThreadMember

class discord.ThreadMember

Represents a Discord thread member.

x == y

Checks if two thread members are equal.

x != y

Checks if two thread members are not equal.

hash(x)

Returns the thread member’s hash.

str(x)

Returns the thread member’s name.

New in version 2.0.

id

The thread member’s ID.

Type

int

thread_id

The thread’s ID.

Type

int

joined_at

The time the member joined the thread in UTC.

Type

datetime.datetime

muted

The mute configuration for the guild. Only reliably available for yourself.

Type

MuteConfig

property flags

The thread member’s flags.

Only reliably available for yourself.

Type

ThreadMemberFlags

property member

The member this ThreadMember represents. If the member is not cached then this will be None.

Type

Optional[Member]

property thread

The thread this member belongs to.

Type

Thread

VoiceChannel

class discord.VoiceChannel

Represents a Discord guild voice channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns the channel’s name.

id

The channel ID.

Type

int

guild

The guild the channel belongs to.

Type

Guild

name

The channel name.

Type

str

nsfw

If the channel is marked as “not safe for work” or “age restricted”.

New in version 2.0.

Type

bool

category_id

The category channel ID this channel belongs to, if applicable.

Type

Optional[int]

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

Type

int

bitrate

The channel’s preferred audio bitrate in bits per second.

Type

int

rtc_region

The region for the voice channel’s voice communication. A value of None indicates automatic voice region detection.

New in version 1.7.

Changed in version 2.0: The type of this attribute has changed to str.

Type

Optional[str]

user_limit

The channel’s limit for number of members that can be in a voice channel.

Type

int

video_quality_mode

The camera video quality for the voice channel’s participants.

New in version 2.0.

Type

VideoQualityMode

last_message_id

The last message ID of the message sent to this channel. It may not point to an existing or valid message.

New in version 2.0.

Type

Optional[int]

slowmode_delay

The number of seconds a member must wait between sending messages in this channel. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode.

New in version 2.2.

Type

int

status

The status of the voice channel. None if no status is set. This is not available for the fetch methods such as Guild.fetch_channel() or Client.fetch_channel().

Type

Optional[str]

voice_background

The background for this voice channel.

Deprecated since version 3.0.

Type

Optional[ChannelVoiceBackground]

hd_streaming_until

When the HD streaming entitlement expires.

New in version 3.0.

Type

Optional[datetime]

hd_streaming_buyer_id

The user’s ID who purchased HD streaming for this voice channel.

New in version 3.0.

Type

Optional[int]

property type

The channel’s Discord type.

Type

ChannelType

property category

The category this channel belongs to.

If there is no category then this is None.

Type

Optional[CategoryChannel]

property changed_roles

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type

List[Role]

await connect(*, timeout=30.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, _channel=None, self_deaf=False, self_mute=False, self_video=False)

This function is a coroutine.

Connects to voice and creates a VoiceClient to establish your connection to the voice server.

This requires voice_states.

Parameters
  • timeout (float) – The timeout in seconds to wait the connection to complete.

  • reconnect (bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.

  • cls (Type[VoiceProtocol]) – A type that subclasses VoiceProtocol to connect with. Defaults to VoiceClient.

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

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

  • self_video (bool) – Indicates if the client should show camera.

Raises
Returns

A voice client that is fully connected to the voice server.

Return type

VoiceProtocol

property created_at

Returns the channel’s creation time in UTC.

Type

datetime.datetime

get_partial_message(message_id, /)

Creates a PartialMessage from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

New in version 2.0.

Parameters

message_id (int) – The message ID to create a partial message for.

Returns

The partial message.

Return type

PartialMessage

is_nsfw()

bool: Checks if the channel is NSFW.

New in version 2.0.

property jump_url

Returns a URL that allows the client to jump to the channel.

New in version 2.0.

Type

str

property last_message

Retrieves the last message from this channel in cache.

The message might not be valid or point to an existing message.

New in version 2.0.

Reliable Fetching

For a slightly more reliable method of fetching the last message, consider using either history() or fetch_message() with the last_message_id attribute.

Returns

The last message in this channel or None if not found.

Return type

Optional[Message]

property members

Returns all members that are currently inside this voice channel.

Type

List[Member]

property mention

The string that allows you to mention the channel.

Type

str

property overwrites

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Changed in version 2.0: Overwrites can now be type-aware Object in case of cache lookup failure.

Returns

The channel’s permission overwrites.

Return type

Dict[Union[Role, Member, Object], PermissionOverwrite]

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

Parameters

obj (Union[Role, User, Object]) – The role or user denoting whose overwrite to get.

Returns

The permission overwrites for this object.

Return type

PermissionOverwrite

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

  • Implicit permissions

  • Member timeout

  • User installed app

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Changed in version 2.0: The object passed in can now be a role object.

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

Changed in version 2.4: User installed apps are now taken into account. The permissions returned for a user installed app mirrors the permissions Discord returns in app_permissions, though it is recommended to use that attribute instead.

Parameters

obj (Union[Member, Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

Returns

The resolved permissions for the member or role.

Return type

Permissions

property permissions_synced

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

New in version 1.3.

Type

bool

property scheduled_events

Returns all scheduled events for this channel.

New in version 2.0.

Type

List[ScheduledEvent]

property voice_states

Returns a mapping of member IDs who have voice states in this channel.

New in version 1.3.

Note

This function is intentionally low level to replace members when the member cache is unavailable.

Returns

The mapping of member ID to a voice state.

Return type

Mapping[int, VoiceState]

Methods
class discord.VoiceChannelEffect

Represents a Discord voice channel effect.

New in version 2.5.

channel

The channel in which the effect is sent.

Type

Union[DMChannel, GroupChannel, VoiceChannel]

user

The user who sent the effect. None if not found in cache.

Type

Optional[Union[Member, User]]

animation

The animation the effect has. Returns None if the effect has no animation.

Type

Optional[VoiceChannelEffectAnimation]

emoji

The emoji of the effect.

Type

Optional[PartialEmoji]

sound

The sound of the effect. Returns None if it’s an emoji effect.

Type

Optional[VoiceChannelSoundEffect]

is_sound()

bool: Whether the effect is a sound or not.

Attributes
class discord.VoiceChannelBackground

Represents a background for voice channel.

New in version 3.0.

type

The background type.

Type

VoiceCallBackgroundType

resource_id

The resource ID. Currently unknown.

Only provided when type is gradient.

Type

Optional[int]

Parameters
  • type (VoiceCallBackgroundType) – The background type.

  • resource_id (Optional[int]) –

    The resource ID. Currently unknown.

    Must be provided when type is gradient.

class discord.VoiceChannelEffectAnimation

A namedtuple which represents a voice channel effect animation.

New in version 2.5.

id

The ID of the animation.

Type

int

type

The type of the animation.

Type

VoiceChannelEffectAnimationType

Attributes
Methods
class discord.VoiceChannelSoundEffect

Represents a Discord voice channel sound effect.

New in version 2.5.

x == y

Checks if two sound effects are equal.

x != y

Checks if two sound effects are not equal.

hash(x)

Returns the sound effect’s hash.

id

The ID of the sound.

Type

int

volume

The volume of the sound as floating point percentage (e.g. 1.0 for 100%).

Type

float

property created_at

Returns the snowflake’s creation time in UTC. Returns None if it’s a default sound.

Type

Optional[datetime.datetime]

is_default()

bool: Whether it’s a default sound or not.

await read()

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

Raises
Returns

The content of the asset.

Return type

bytes

await save(fp, *, seek_begin=True)

This function is a coroutine.

Saves this asset into a file-like object.

Parameters
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is successfully done.

Raises
Returns

The number of bytes written.

Return type

int

await to_file(*, filename=..., description=None, spoiler=False)

This function is a coroutine.

Converts the asset into a File suitable for sending via abc.Messageable.send().

New in version 2.0.

Parameters
  • filename (Optional[str]) – The filename of the file. If not provided, then the filename from the asset’s URL is used.

  • description (Optional[str]) – The description for the file.

  • spoiler (bool) – Whether the file is a spoiler.

Raises
Returns

The asset as a file suitable for sending.

Return type

File

property url

Returns the URL of the sound.

Type

str

StageChannel

class discord.StageChannel

Represents a Discord guild stage channel.

New in version 1.7.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns the channel’s name.

id

The channel ID.

Type

int

guild

The guild the channel belongs to.

Type

Guild

name

The channel name.

Type

str

nsfw

If the channel is marked as “not safe for work” or “age restricted”.

New in version 2.0.

Type

bool

category_id

The category channel ID this channel belongs to, if applicable.

Type

Optional[int]

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

Type

int

bitrate

The channel’s preferred audio bitrate in bits per second.

Type

int

rtc_region

The region for the stage channel’s voice communication. A value of None indicates automatic voice region detection.

Type

Optional[str]

user_limit

The channel’s limit for number of members that can be in a stage channel.

Type

int

video_quality_mode

The camera video quality for the stage channel’s participants.

New in version 2.0.

Type

VideoQualityMode

last_message_id

The last message ID of the message sent to this channel. It may not point to an existing or valid message.

New in version 2.2.

Type

Optional[int]

slowmode_delay

The number of seconds a member must wait between sending messages in this channel. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode.

New in version 2.2.

Type

int

topic

The channel’s topic. None if it isn’t set.

Type

Optional[str]

hd_streaming_until

When the HD streaming entitlement expires.

New in version 3.0.

Type

Optional[datetime]

hd_streaming_buyer_id

The user’s ID who purchased HD streaming for this stage channel.

New in version 3.0.

Type

Optional[int]

property requesting_to_speak

A list of members who are requesting to speak in the stage channel.

Type

List[Member]

property speakers

A list of members who have been permitted to speak in the stage channel.

New in version 2.0.

Type

List[Member]

property listeners

A list of members who are listening in the stage channel.

New in version 2.0.

Type

List[Member]

property moderators

A list of members who are moderating the stage channel.

New in version 2.0.

Type

List[Member]

property type

The channel’s Discord type.

Type

ChannelType

property instance

The running stage instance of the stage channel.

New in version 2.0.

Type

Optional[StageInstance]

property category

The category this channel belongs to.

If there is no category then this is None.

Type

Optional[CategoryChannel]

property changed_roles

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type

List[Role]

await connect(*, timeout=30.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, _channel=None, self_deaf=False, self_mute=False, self_video=False)

This function is a coroutine.

Connects to voice and creates a VoiceClient to establish your connection to the voice server.

This requires voice_states.

Parameters
  • timeout (float) – The timeout in seconds to wait the connection to complete.

  • reconnect (bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.

  • cls (Type[VoiceProtocol]) – A type that subclasses VoiceProtocol to connect with. Defaults to VoiceClient.

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

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

  • self_video (bool) – Indicates if the client should show camera.

Raises
Returns

A voice client that is fully connected to the voice server.

Return type

VoiceProtocol

property created_at

Returns the channel’s creation time in UTC.

Type

datetime.datetime

get_partial_message(message_id, /)

Creates a PartialMessage from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

New in version 2.0.

Parameters

message_id (int) – The message ID to create a partial message for.

Returns

The partial message.

Return type

PartialMessage

is_nsfw()

bool: Checks if the channel is NSFW.

New in version 2.0.

property jump_url

Returns a URL that allows the client to jump to the channel.

New in version 2.0.

Type

str

property last_message

Retrieves the last message from this channel in cache.

The message might not be valid or point to an existing message.

New in version 2.0.

Reliable Fetching

For a slightly more reliable method of fetching the last message, consider using either history() or fetch_message() with the last_message_id attribute.

Returns

The last message in this channel or None if not found.

Return type

Optional[Message]

property members

Returns all members that are currently inside this voice channel.

Type

List[Member]

property mention

The string that allows you to mention the channel.

Type

str

property overwrites

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Changed in version 2.0: Overwrites can now be type-aware Object in case of cache lookup failure.

Returns

The channel’s permission overwrites.

Return type

Dict[Union[Role, Member, Object], PermissionOverwrite]

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

Parameters

obj (Union[Role, User, Object]) – The role or user denoting whose overwrite to get.

Returns

The permission overwrites for this object.

Return type

PermissionOverwrite

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

  • Implicit permissions

  • Member timeout

  • User installed app

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Changed in version 2.0: The object passed in can now be a role object.

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

Changed in version 2.4: User installed apps are now taken into account. The permissions returned for a user installed app mirrors the permissions Discord returns in app_permissions, though it is recommended to use that attribute instead.

Parameters

obj (Union[Member, Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

Returns

The resolved permissions for the member or role.

Return type

Permissions

property permissions_synced

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

New in version 1.3.

Type

bool

property scheduled_events

Returns all scheduled events for this channel.

New in version 2.0.

Type

List[ScheduledEvent]

property voice_states

Returns a mapping of member IDs who have voice states in this channel.

New in version 1.3.

Note

This function is intentionally low level to replace members when the member cache is unavailable.

Returns

The mapping of member ID to a voice state.

Return type

Mapping[int, VoiceState]

StageInstance

class discord.StageInstance

Represents a stage instance of a stage channel in a guild.

New in version 2.0.

x == y

Checks if two stage instances are equal.

x != y

Checks if two stage instances are not equal.

hash(x)

Returns the stage instance’s hash.

id

The stage instance’s ID.

Type

int

guild

The guild that the stage instance is running in.

Type

Guild

channel_id

The ID of the channel that the stage instance is running in.

Type

int

topic

The topic of the stage instance.

Type

str

privacy_level

The privacy level of the stage instance.

Type

PrivacyLevel

discoverable_disabled

Whether discoverability for the stage instance is disabled.

Type

bool

scheduled_event_id

The ID of scheduled event that belongs to the stage instance if any.

New in version 2.0.

Type

Optional[int]

channel

The channel that stage instance is running in.

Type

Optional[StageChannel]

scheduled_event

The scheduled event that belongs to the stage instance.

Type

Optional[ScheduledEvent]

CategoryChannel

class discord.CategoryChannel

Represents a Discord channel category.

These are useful to group channels to logical compartments.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the category’s hash.

str(x)

Returns the category’s name.

name

The category name.

Type

str

guild

The guild the category belongs to.

Type

Guild

id

The category channel ID.

Type

int

position

The position in the category list. This is a number that starts at 0. e.g. the top category is position 0.

Type

int

nsfw

If the channel is marked as “not safe for work”.

Note

To check if the channel or the guild of that channel are marked as NSFW, consider is_nsfw() instead.

Type

bool

property type

The channel’s Discord type.

Type

ChannelType

is_nsfw()

bool: Checks if the category is NSFW.

property channels

Returns the channels that are under this category.

These are sorted by the official Discord UI, which places voice channels below the text channels.

Type

List[abc.GuildChannel]

property text_channels

Returns the text channels that are under this category.

Type

List[TextChannel]

property voice_channels

Returns the voice channels that are under this category.

Type

List[VoiceChannel]

property stage_channels

Returns the stage channels that are under this category.

New in version 1.7.

Type

List[StageChannel]

property forums

Returns the forum channels that are under this category.

New in version 2.4.

Type

List[ForumChannel]

property category

The category this channel belongs to.

If there is no category then this is None.

Type

Optional[CategoryChannel]

property changed_roles

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type

List[Role]

property created_at

Returns the channel’s creation time in UTC.

Type

datetime.datetime

property jump_url

Returns a URL that allows the client to jump to the channel.

New in version 2.0.

Type

str

property mention

The string that allows you to mention the channel.

Type

str

property overwrites

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Changed in version 2.0: Overwrites can now be type-aware Object in case of cache lookup failure.

Returns

The channel’s permission overwrites.

Return type

Dict[Union[Role, Member, Object], PermissionOverwrite]

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

Parameters

obj (Union[Role, User, Object]) – The role or user denoting whose overwrite to get.

Returns

The permission overwrites for this object.

Return type

PermissionOverwrite

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

  • Implicit permissions

  • Member timeout

  • User installed app

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Changed in version 2.0: The object passed in can now be a role object.

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

Changed in version 2.4: User installed apps are now taken into account. The permissions returned for a user installed app mirrors the permissions Discord returns in app_permissions, though it is recommended to use that attribute instead.

Parameters

obj (Union[Member, Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

Returns

The resolved permissions for the member or role.

Return type

Permissions

property permissions_synced

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

New in version 1.3.

Type

bool

DMChannel

class discord.DMChannel

Represents a Discord direct message channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns a string representation of the channel.

id

The direct message channel ID.

Type

int

recipient

The user you are participating with in the direct message channel.

Type

User

me

The user presenting yourself.

Type

ClientUser

last_message_id

The last message ID of the message sent to this channel. It may not point to an existing or valid message.

Type

Optional[int]

last_pin_timestamp

When the last pinned message was pinned. None if there are no pinned messages.

Type

Optional[datetime.datetime]

safety_warnings

The safety warnings for this direct message channel.

New in version 3.0.

Type

List[SafetyWarning]

property call

The channel’s currently active call.

New in version 3.0.

Type

Optional[PrivateCall]

property flags

The flags associated with this DM channel.

Type

ChannelFlags

property type

The channel’s Discord type.

Type

ChannelType

property guild

The guild this DM channel belongs to. Always None.

This is mainly provided for compatibility purposes in duck typing.

New in version 2.0.

Type

Optional[Guild]

property jump_url

Returns a URL that allows the client to jump to the channel.

New in version 2.0.

Type

str

property created_at

Returns the direct message channel’s creation time in UTC.

Type

datetime.datetime

property recipient_flags

The channel recipient’s flags.

New in version 3.0.

Type

RecipientFlags

property requested_at

Returns the message request’s creation time in UTC, if applicable.

New in version 3.0.

Type

Optional[datetime.datetime]

is_message_request()

bool: Indicates if the direct message is/was a message request.

New in version 3.0.

is_accepted()

bool: Indicates if the message request is accepted. For regular direct messages, this is always True.

New in version 3.0.

is_spam()

bool: Indicates if the direct message is a spam message request.

New in version 3.0.

permissions_for(obj=None, /)

Handles permission resolution for a User.

This function is there for compatibility with other channel types.

Actual direct messages do not really have the concept of permissions.

This returns all the Text related permissions set to True except:

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

Changed in version 2.1: Thread related permissions are now set to False.

Parameters

obj (User) – The user to check permissions for. This parameter is ignored but kept for compatibility with other permissions_for methods.

Returns

The resolved permissions.

Return type

Permissions

get_partial_message(message_id, /)

Creates a PartialMessage from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

New in version 1.6.

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

Parameters

message_id (int) – The message ID to create a partial message for.

Returns

The partial message.

Return type

PartialMessage

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, ring=True)

This function is a coroutine.

Connects to voice and creates a VoiceClient to establish your connection to the voice server.

Parameters
  • timeout (float) – The timeout in seconds to wait for the voice endpoint.

  • reconnect (bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.

  • cls (Type[VoiceProtocol]) – A type that subclasses VoiceProtocol to connect with. Defaults to VoiceClient.

  • ring (bool) – Whether to ring the other member(s) to join the call, if starting a new call. Defaults to True.

Raises
Returns

A voice client that is fully connected to the voice server.

Return type

VoiceProtocol

await send(content=None, *, file=None, files=None, delete_after=None, allowed_mentions=None, metadata=...)

This function is a coroutine.

Sends a message to the destination with the content given.

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

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

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

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

  • file (File) – The file to upload.

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

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

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    New in version 1.4.

  • metadata (Optional[Dict[str, str]]) – The message’s metadata. Can be only up to 25 entries, and 1024 characters per key and value.

Raises
  • HTTPException – Sending the message failed.

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

  • NotFound – You sent a message with the same nonce as one that has been explicitly deleted shortly earlier.

  • ValueError – The files list is not of the appropriate size.

  • TypeError – You specified both file and files.

Returns

The message that was sent.

Return type

Message

GroupChannel

class discord.GroupChannel

Represents a Discord group channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns a string representation of the channel

id

The group channel ID.

Type

int

me

The user presenting yourself.

Type

ClientUser

name

The group channel’s name if provided.

Type

Optional[str]

last_message_id

The last message ID of the message sent to this channel. It may not point to an existing or valid message.

Type

Optional[int]

last_pin_timestamp

When the last pinned message was pinned. None if there are no pinned messages.

Type

Optional[datetime.datetime]

recipients

The users you are participating with in the group channel.

Type

List[User]

owner_id

The owner ID that owns the group channel.

Type

int

managed

Whether the group channel is managed by an application.

This restricts the operations that can be performed on the channel, and means owner will usually be None.

Type

bool

application_id

The ID of the managing application, if any.

Type

Optional[int]

nicks

A mapping of users to their respective nicknames in the group channel.

New in version 3.0.

Type

Dict[User, str]

origin_channel_id

The ID of the DM this group channel originated from, if any.

This can only be accurately received in on_private_channel_create() due to a Discord limitation.

New in version 3.0.

Type

Optional[int]

blocked_user_warning_dismissed

Whether the user has acknowledged the presence of blocked users in the group channel.

This can only be accurately received in on_private_channel_create(), on_private_channel_update(), and on_private_channel_delete() due to a Discord limitation.

New in version 3.0.

Type

bool

property call

The channel’s currently active call.

Type

Optional[PrivateCall]

property type

The channel’s Discord type.

Type

ChannelType

property guild

The guild this group channel belongs to. Always None.

This is mainly provided for compatibility purposes in duck typing.

New in version 2.0.

Type

Optional[Guild]

property icon

Returns the channel’s icon asset if available.

Type

Optional[Asset]

property origin_channel

The DM this group channel originated from, if any.

This can only be accurately received in on_private_channel_create() due to a Discord limitation.

Type

Optional[DMChannel]

property created_at

Returns the channel’s creation time in UTC.

Type

datetime.datetime

property jump_url

Returns a URL that allows the client to jump to the channel.

New in version 2.0.

Type

str

permissions_for(obj, /)

Handles permission resolution for a User.

This function is there for compatibility with other channel types.

Actual direct messages do not really have the concept of permissions.

This returns all the Text related permissions set to True except:

This also checks the kick_members permission if the user is the owner.

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

Changed in version 2.1: Thread related permissions are now set to False.

Parameters

obj (Snowflake) – The user to check permissions for.

Returns

The resolved permissions for the user.

Return type

Permissions

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, ring=True)

This function is a coroutine.

Connects to voice and creates a VoiceClient to establish your connection to the voice server.

Parameters
  • timeout (float) – The timeout in seconds to wait for the voice endpoint.

  • reconnect (bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.

  • cls (Type[VoiceProtocol]) – A type that subclasses VoiceProtocol to connect with. Defaults to VoiceClient.

  • ring (bool) – Whether to ring the other member(s) to join the call, if starting a new call. Defaults to True.

Raises
Returns

A voice client that is fully connected to the voice server.

Return type

VoiceProtocol

await fetch_linked_accounts_for(users=None)

This function is a coroutine.

Retrieves linked accounts for specified users.

New in version 3.0.

Parameters

users (Optional[List[User]]) – The users to retrieve linked accounts for.

Raises
  • Forbidden – You do not have proper permissions to retrieve linked accounts.

  • HTTPException – Retrieving linked accounts failed.

Returns

The mapping of user IDs to their linked accounts.

Return type

Dict[int, List[LinkedAccount]]

Attributes
class discord.LinkedAccount

Represents a linked account.

New in version 3.0.

id

The ID of the linked account.

Type

str

name

The name of the account.

Type

str

EphemeralDMChannel

class discord.EphemeralDMChannel

Represents a Discord ephemeral direct message channel.

New in version 3.0.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns a string representation of the channel.

id

The direct message channel ID.

Type

int

me

The user presenting yourself.

Type

ClientUser

recipients

The users participating in the ephemral direct message channel.

Type

Tuple[User, …]

recipient

The user you are participating with in the direct message channel.

Type

User

last_message_id

The last message ID of the message sent to this channel. It may not point to an existing or valid message.

Type

Optional[int]

last_pin_timestamp

When the last pinned message was pinned. None if there are no pinned messages.

Type

Optional[datetime.datetime]

property type

The channel’s Discord type.

Type

ChannelType

property guild

The guild this Ephemeral DM channel belongs to. Always None.

This is mainly provided for compatibility purposes in duck typing.

New in version 2.0.

Type

Optional[Guild]

property jump_url

Returns a URL that allows the client to jump to the channel.

New in version 2.0.

Type

str

property created_at

Returns the direct message channel’s creation time in UTC.

Type

datetime.datetime

property requested_at

Returns the message request’s creation time in UTC, if applicable.

Type

Optional[datetime.datetime]

is_message_request()

bool: Indicates if the direct message is/was a message request.

is_accepted()

bool: Indicates if the message request is accepted. For regular direct messages, this is always True.

is_spam()

bool: Indicates if the direct message is a spam message request.

permissions_for(obj=None, /)

Handles permission resolution for a User.

This function is there for compatibility with other channel types.

Actual direct messages do not really have the concept of permissions.

This returns all the Text related permissions set to True except:

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

Changed in version 2.1: Thread related permissions are now set to False.

Parameters

obj (User) – The user to check permissions for. This parameter is ignored but kept for compatibility with other permissions_for methods.

Returns

The resolved permissions.

Return type

Permissions

get_partial_message(message_id, /)

Creates a PartialMessage from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

New in version 1.6.

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

Parameters

message_id (int) – The message ID to create a partial message for.

Returns

The partial message.

Return type

PartialMessage

await connect(*, timeout=30.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, _channel=None, self_deaf=False, self_mute=False, self_video=False)

This function is a coroutine.

Connects to voice and creates a VoiceClient to establish your connection to the voice server.

This requires voice_states.

Parameters
  • timeout (float) – The timeout in seconds to wait the connection to complete.

  • reconnect (bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.

  • cls (Type[VoiceProtocol]) – A type that subclasses VoiceProtocol to connect with. Defaults to VoiceClient.

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

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

  • self_video (bool) – Indicates if the client should show camera.

Raises
Returns

A voice client that is fully connected to the voice server.

Return type

VoiceProtocol

await send(content=None, *, file=None, files=None, delete_after=None, allowed_mentions=None, metadata=...)

This function is a coroutine.

Sends a message to the destination with the content given.

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

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

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

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

  • file (File) – The file to upload.

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

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

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    New in version 1.4.

  • metadata (Optional[Dict[str, str]]) – The message’s metadata. Can be only up to 25 entries, and 1024 characters per key and value.

Raises
  • HTTPException – Sending the message failed.

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

  • NotFound – You sent a message with the same nonce as one that has been explicitly deleted shortly earlier.

  • ValueError – The files list is not of the appropriate size.

  • TypeError – You specified both file and files.

Returns

The message that was sent.

Return type

Message

PartialInviteGuild

class discord.PartialInviteGuild

Represents a “partial” invite guild.

This model will be given when the user is not part of the guild the Invite resolves to.

x == y

Checks if two partial guilds are the same.

x != y

Checks if two partial guilds are not the same.

hash(x)

Return the partial guild’s hash.

str(x)

Returns the partial guild’s name.

name

The partial guild’s name.

Type

str

id

The partial guild’s ID.

Type

int

verification_level

The partial guild’s verification level.

Type

VerificationLevel

features

A list of features the guild has. See Guild.features for more information.

Type

List[str]

description

The partial guild’s description.

Type

Optional[str]

nsfw_level

The partial guild’s NSFW level.

New in version 2.0.

Type

NSFWLevel

vanity_url_code

The partial guild’s vanity URL code, if available.

New in version 2.0.

Type

Optional[str]

premium_subscription_count

The number of “boosts” the partial guild currently has.

New in version 2.0.

Type

int

property created_at

Returns the guild’s creation time in UTC.

Type

datetime.datetime

property vanity_url

The Discord vanity invite URL for this partial guild, if available.

New in version 2.0.

Type

Optional[str]

property icon

Returns the guild’s icon asset, if available.

Type

Optional[Asset]

property banner

Returns the guild’s banner asset, if available.

Type

Optional[Asset]

property splash

Returns the guild’s invite splash asset, if available.

Type

Optional[Asset]

PartialInviteChannel

class discord.PartialInviteChannel

Represents a “partial” invite channel.

This model will be given when the user is not part of the guild the Invite resolves to.

x == y

Checks if two partial channels are the same.

x != y

Checks if two partial channels are not the same.

hash(x)

Return the partial channel’s hash.

str(x)

Returns the partial channel’s name.

name

The partial channel’s name.

Type

str

id

The partial channel’s ID.

Type

int

type

The partial channel’s type.

Type

ChannelType

property mention

The string that allows you to mention the channel.

Type

str

property created_at

Returns the channel’s creation time in UTC.

Type

datetime.datetime

Invite

class discord.Invite

Represents a Discord Guild or abc.GuildChannel invite.

Depending on the way this object was created, some of the attributes can have a value of None.

x == y

Checks if two invites are equal.

x != y

Checks if two invites are not equal.

hash(x)

Returns the invite hash.

str(x)

Returns the invite URL.

The following table illustrates what methods will obtain the attributes:

Attribute

Method

max_age

abc.GuildChannel.invites(), Guild.invites()

max_uses

abc.GuildChannel.invites(), Guild.invites()

created_at

abc.GuildChannel.invites(), Guild.invites()

temporary

abc.GuildChannel.invites(), Guild.invites()

uses

abc.GuildChannel.invites(), Guild.invites()

approximate_member_count

Client.fetch_invite() with with_counts enabled

approximate_presence_count

Client.fetch_invite() with with_counts enabled

expires_at

Client.fetch_invite() with with_expiration enabled

If it’s not in the table above then it is available by all methods.

type

The type of the invite.

Type

InviteType

max_age

How long before the invite expires in seconds. A value of 0 indicates that it doesn’t expire.

Type

Optional[int]

code

The URL fragment used for the invite.

Type

str

guild

The guild the invite is for. Can be None if it’s from a group direct message.

Type

Optional[Union[Guild, Object, PartialInviteGuild]]

profile

The profile for the guild this invite is for.

New in version 3.0.

Type

Optional[GuildProfile]

revoked

Indicates if the invite has been revoked.

Type

Optional[bool]

created_at

An aware UTC datetime object denoting the time the invite was created.

Type

Optional[datetime.datetime]

temporary

Indicates that the invite grants temporary membership. If True, members who joined via this invite will be kicked upon disconnect.

Type

Optional[bool]

uses

How many times the invite has been used.

Type

Optional[int]

max_uses

How many times the invite can be used. A value of 0 indicates that it has unlimited uses.

Type

Optional[int]

inviter

The user who created the invite.

Type

Optional[User]

approximate_member_count

The approximate number of members in the guild.

Type

Optional[int]

approximate_presence_count

The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded.

Type

Optional[int]

expires_at

The expiration date of the invite. If the value is None when received through Client.fetch_invite() with with_expiration enabled, the invite will never expire.

New in version 2.0.

Type

Optional[datetime.datetime]

channel

The channel the invite is for.

Type

Optional[Union[abc.GuildChannel, Object, PartialInviteChannel]]

target_type

The type of target for the voice channel invite.

New in version 2.0.

Type

InviteTarget

target_user

The user whose stream to display for this invite, if any.

New in version 2.0.

Type

Optional[User]

target_application

The embedded application the invite targets, if any.

New in version 2.0.

Type

Optional[PartialAppInfo]

scheduled_event

The scheduled event associated with this invite, if any.

New in version 2.0.

Type

Optional[ScheduledEvent]

scheduled_event_id

The ID of the scheduled event associated with this invite, if any.

New in version 2.0.

Type

Optional[int]

property id

Returns the proper code portion of the invite.

Type

str

property url

A property that retrieves the invite URL.

Type

str

set_scheduled_event(scheduled_event, /)

Sets the scheduled event for this invite.

New in version 2.0.

Parameters

scheduled_event (Snowflake) – The ID of the scheduled event.

Returns

The invite with the new scheduled event.

Return type

Invite

Template

class discord.Template

Represents a Discord template.

New in version 1.4.

code

The template code.

Type

str

uses

How many times the template has been used.

Type

int

name

The name of the template.

Type

str

description

The description of the template.

Type

str

creator

The creator of the template.

Type

User

created_at

An aware datetime in UTC representing when the template was created.

Type

datetime

updated_at

An aware datetime in UTC representing when the template was last updated. This is referred to as “last synced” in the official Discord client.

Type

datetime

source_guild

The guild snapshot that represents the data that this template currently holds.

Type

Guild

is_dirty

Whether the template has unsynced changes.

New in version 2.0.

Type

Optional[bool]

property url

The template url.

New in version 2.0.

Type

str

WelcomeScreen

class discord.WelcomeScreen

Represents a Guild welcome screen.

New in version 2.0.

description

The description shown on the welcome screen.

Type

str

welcome_channels

The channels shown on the welcome screen.

Type

List[WelcomeChannel]

property enabled

Whether the welcome screen is displayed.

This is equivalent to checking if WELCOME_SCREEN_ENABLED is present in Guild.features.

Type

bool

WelcomeChannel

class discord.WelcomeChannel

Represents a WelcomeScreen welcome channel.

New in version 2.0.

channel

The guild channel that is being referenced.

Type

abc.Snowflake

description

The description shown of the channel.

Type

str

emoji

The emoji used beside the channel description.

Type

Optional[PartialEmoji, Emoji, str]

WidgetChannel

class discord.WidgetChannel

Represents a “partial” widget channel.

x == y

Checks if two partial channels are the same.

x != y

Checks if two partial channels are not the same.

hash(x)

Return the partial channel’s hash.

str(x)

Returns the partial channel’s name.

id

The channel’s ID.

Type

int

name

The channel’s name.

Type

str

position

The channel’s position.

Type

int

property mention

The string that allows you to mention the channel.

Type

str

property created_at

Returns the channel’s creation time in UTC.

Type

datetime.datetime

WidgetMember

class discord.WidgetMember

Represents a “partial” member of the widget’s guild.

x == y

Checks if two widget members are the same.

x != y

Checks if two widget members are not the same.

hash(x)

Return the widget member’s hash.

str(x)

Returns the widget member’s handle (e.g. name or name#discriminator).

id

The member’s ID.

Type

int

name

The member’s username.

Type

str

discriminator

The member’s discriminator. This is a legacy concept that is no longer used.

Type

str

global_name

The member’s global nickname, taking precedence over the username in display.

New in version 2.3.

Type

Optional[str]

bot

Whether the member is a bot.

Type

bool

status

The member’s status.

Type

Status

nick

The member’s guild-specific nickname. Takes precedence over the global name.

Type

Optional[str]

avatar

The member’s avatar hash.

Type

Optional[str]

activity

The member’s activity.

Type

Optional[Union[BaseActivity, Spotify]]

deafened

Whether the member is currently deafened.

Type

Optional[bool]

muted

Whether the member is currently muted.

Type

Optional[bool]

suppress

Whether the member is currently being suppressed.

Type

Optional[bool]

connected_channel

Which channel the member is connected to.

Type

Optional[WidgetChannel]

property display_name

Returns the member’s display name.

Type

str

property accent_color

Returns the user’s accent color, if applicable.

A user’s accent color is only shown if they do not have a banner. This will only be available if the user explicitly sets a color.

There is an alias for this named accent_colour.

New in version 2.0.

Note

This information is only available via discord.Client.fetch_user().

Type

Optional[discord.Color]

property accent_colour

Returns the user’s accent colour, if applicable.

A user’s accent colour is only shown if they do not have a banner. This will only be available if the user explicitly sets a colour.

This is an alias of accent_color.

New in version 2.0.

Note

This information is only available via discord.Client.fetch_user().

Type

Optional[discord.Color]

property avatar_decoration

Returns an Asset for the avatar decoration the user has.

If the user has not set an avatar decoration, None is returned.

New in version 2.4.

Type

Optional[discord.Asset]

property avatar_decoration_sku_id

Returns the SKU ID of the avatar decoration the user has.

If the user has not set an avatar decoration, None is returned.

New in version 2.4.

Type

Optional[int]

property banner

Returns the user’s banner asset, if available.

New in version 2.0.

Note

This information is only available via discord.Client.fetch_user().

Type

Optional[discord.Asset]

property color

A property that returns a color denoting the rendered color for the user. This always returns Color.default().

There is an alias for this named colour.

Type

discord.Color

property colour

A property that returns a colour denoting the rendered colour for the user. This always returns Colour.default().

This is an alias of color.

Type

discord.Colour

property created_at

Returns the user’s creation time in UTC.

This is when the user’s Discord account was created.

Type

datetime.datetime

property default_avatar

Returns the default avatar for a given user.

Type

discord.Asset

property display_avatar

Returns the user’s display avatar.

For regular users this is just their default avatar or uploaded avatar.

New in version 2.0.

Type

discord.Asset

property game_relationship

Returns the GameRelationship with this user if applicable, None otherwise.

Type

Optional[GameRelationship]

is_blocked()

bool: Checks if the user is blocked.

is_friend()

bool: Checks if the user is your friend.

is_game_friend()

bool: Checks if the user is your friend in-game.

is_ignored()

bool: Checks if the user is ignored.

property mention

Returns a string that allows you to mention the given user.

Type

str

mentioned_in(message)

Checks if the user is mentioned in the specified message.

Parameters

message (discord.Message) – The message to check if you’re mentioned in.

Returns

Indicates if the user is mentioned in the message.

Return type

bool

property primary_guild

Returns the user’s primary guild.

Type

discord.PrimaryGuild

property public_flags

The publicly available flags the user has.

Type

discord.PublicUserFlags

property relationship

Returns the Relationship with this user if applicable, None otherwise.

Type

Optional[Relationship]

property voice

Returns the user’s current voice state.

Type

Optional[discord.VoiceState]

Widget

class discord.Widget

Represents a Guild widget.

x == y

Checks if two widgets are the same.

x != y

Checks if two widgets are not the same.

str(x)

Returns the widget’s JSON URL.

id

The guild’s ID.

Type

int

name

The guild’s name.

Type

str

channels

The accessible voice channels in the guild.

Type

List[WidgetChannel]

members

The online members in the guild. Offline members do not appear in the widget.

Note

Due to a Discord limitation, if this data is available the users will be “anonymized” with linear IDs and discriminator information being incorrect. Likewise, the number of members retrieved is capped.

Type

List[WidgetMember]

presence_count

The approximate number of online members in the guild. Offline members are not included in this count.

New in version 2.0.

Type

int

property created_at

Returns the member’s creation time in UTC.

Type

datetime.datetime

property json_url

The JSON URL of the widget.

Type

str

property invite_url

The invite URL for the guild, if available.

Type

Optional[str]

await fetch_invite(*, with_counts=True)

This function is a coroutine.

Retrieves an Invite from the widget’s invite URL. This is the same as Client.fetch_invite(); the invite code is abstracted away.

Parameters

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

Returns

The invite from the widget’s invite URL, if available.

Return type

Optional[Invite]

StickerPack

class discord.StickerPack

Represents a sticker pack.

New in version 2.0.

str(x)

Returns the name of the sticker pack.

x == y

Checks if the sticker pack is equal to another sticker pack.

x != y

Checks if the sticker pack is not equal to another sticker pack.

name

The name of the sticker pack.

Type

str

description

The description of the sticker pack.

Type

str

id

The ID of the sticker pack.

Type

int

stickers

The stickers of this sticker pack.

Type

List[StandardSticker]

sku_id

The SKU ID of the sticker pack.

Type

int

cover_sticker_id

The ID of the sticker used for the cover of the sticker pack.

Type

Optional[int]

cover_sticker

The sticker used for the cover of the sticker pack.

Type

Optional[StandardSticker]

property banner

The banner asset of the sticker pack.

Type

Asset

StickerItem

Attributes
class discord.StickerItem

Represents a sticker item.

New in version 2.0.

str(x)

Returns the name of the sticker item.

x == y

Checks if the sticker item is equal to another sticker item.

x != y

Checks if the sticker item is not equal to another sticker item.

name

The sticker’s name.

Type

str

id

The ID of the sticker.

Type

int

format

The format for the sticker’s image.

Type

StickerFormatType

url

The URL for the sticker’s image.

Type

str

Sticker

class discord.Sticker

Represents a sticker.

New in version 1.6.

str(x)

Returns the name of the sticker.

x == y

Checks if the sticker is equal to another sticker.

x != y

Checks if the sticker is not equal to another sticker.

name

The sticker’s name.

Type

str

id

The ID of the sticker.

Type

int

description

The description of the sticker.

Type

str

format

The format for the sticker’s image.

Type

StickerFormatType

url

The URL for the sticker’s image.

Type

str

property created_at

Returns the sticker’s creation time in UTC.

Type

datetime.datetime

StandardSticker

class discord.StandardSticker

Represents a sticker that is found in a standard sticker pack.

New in version 2.0.

str(x)

Returns the name of the sticker.

x == y

Checks if the sticker is equal to another sticker.

x != y

Checks if the sticker is not equal to another sticker.

name

The sticker’s name.

Type

str

id

The ID of the sticker.

Type

int

description

The description of the sticker.

Type

str

pack_id

The ID of the sticker’s pack.

Type

int

format

The format for the sticker’s image.

Type

StickerFormatType

tags

A list of tags for the sticker.

Type

List[str]

sort_value

The sticker’s sort order within its pack.

Type

int

GuildSticker

class discord.GuildSticker

Represents a sticker that belongs to a guild.

New in version 2.0.

str(x)

Returns the name of the sticker.

x == y

Checks if the sticker is equal to another sticker.

x != y

Checks if the sticker is not equal to another sticker.

name

The sticker’s name.

Type

str

id

The ID of the sticker.

Type

int

description

The description of the sticker.

Type

str

format

The format for the sticker’s image.

Type

StickerFormatType

available

Whether this sticker is available for use.

Type

bool

guild_id

The ID of the guild that this sticker is from.

Type

int

user

The user that created this sticker. This can only be retrieved using Guild.fetch_sticker() and having manage_emojis_and_stickers.

Type

Optional[User]

emoji

The name of a unicode emoji that represents this sticker.

Type

str

guild

The guild that this sticker is from. Could be None if the bot is not in the guild.

New in version 2.0.

Type

Optional[Guild]

BaseSoundboardSound

Attributes
class discord.BaseSoundboardSound

Represents a generic Discord soundboard sound.

New in version 2.5.

x == y

Checks if two sounds are equal.

x != y

Checks if two sounds are not equal.

hash(x)

Returns the sound’s hash.

id

The ID of the sound.

Type

int

volume

The volume of the sound as floating point percentage (e.g. 1.0 for 100%).

Type

float

property url

Returns the URL of the sound.

Type

str

SoundboardDefaultSound

Attributes
class discord.SoundboardDefaultSound

Represents a Discord soundboard default sound.

New in version 2.5.

x == y

Checks if two sounds are equal.

x != y

Checks if two sounds are not equal.

hash(x)

Returns the sound’s hash.

id

The ID of the sound.

Type

int

volume

The volume of the sound as floating point percentage (e.g. 1.0 for 100%).

Type

float

name

The name of the sound.

Type

str

emoji

The emoji of the sound.

Type

PartialEmoji

SoundboardSound

class discord.SoundboardSound

Represents a Discord soundboard sound.

New in version 2.5.

x == y

Checks if two sounds are equal.

x != y

Checks if two sounds are not equal.

hash(x)

Returns the sound’s hash.

id

The ID of the sound.

Type

int

guild

The guild in which the sound is uploaded.

Type

Guild

volume

The volume of the sound as floating point percentage (e.g. 1.0 for 100%).

Type

float

user_id

The ID of the user who created this sound.

Type

int

user

The user who uploaded the sound.

Type

Optional[User]

name

The name of the sound.

Type

str

emoji

The emoji of the sound. None if no emoji is set.

Type

Optional[PartialEmoji]

available

Whether this sound is available for use.

Type

bool

property created_at

Returns the snowflake’s creation time in UTC.

Type

datetime.datetime

SKU

class discord.SKU

Represents a premium offering as a stock-keeping unit (SKU).

New in version 2.4.

id

The SKU’s ID.

Type

int

type

The type of the SKU.

Type

SKUType

application_id

The ID of the application that the SKU belongs to.

Type

int

name

The consumer-facing name of the premium offering.

Type

str

slug

A system-generated URL slug based on the SKU name.

Type

str

property flags

Returns the flags of the SKU.

Type

SKUFlags

property created_at

Returns the sku’s creation time in UTC.

Type

datetime.datetime

await fetch_subscription(subscription_id, /)

This function is a coroutine.

Retrieves a Subscription with the specified ID.

New in version 2.5.

Parameters

subscription_id (int) – The subscription’s ID to fetch from.

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

  • HTTPException – Fetching the subscription failed.

Returns

The subscription you requested.

Return type

Subscription

async for ... in subscriptions(*, limit=50, before=None, after=None)

Retrieves an asynchronous iterator of the Subscription that SKU has.

New in version 2.5.

Examples

Usage

async for subscription in sku.subscriptions(limit=100):
    print(subscription.user_id, subscription.current_period_end)

Flattening into a list

subscriptions = [subscription async for subscription in sku.subscriptions(limit=100)]
# subscriptions is now a list of Subscription...

All parameters are optional.

Parameters
  • limit (Optional[int]) – The number of subscriptions to retrieve. If None, it retrieves every subscription for this SKU. Note, however, that this would make it a slow operation. Defaults to 100.

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

  • after (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve subscriptions after this date or entitlement. 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 – Fetching the subscriptions failed.

  • TypeError – Both after and before were provided, as Discord does not support this type of pagination.

Yields

Subscription – The subscription with the SKU.

Entitlement

class discord.Entitlement

Represents a Discord entitlement.

New in version 3.0.

x == y

Checks if two entitlements are equal.

x != y

Checks if two entitlements are not equal.

hash(x)

Returns the entitlement’s hash.

id

The entitlement’s ID.

Type

int

type

The type of the entitlement.

Type

EntitlementType

sku_id

The ID of the SKU that the entitlement belongs to.

Type

int

application_id

The ID of the application that the entitlement belongs to.

Type

int

user_id

The ID of the user that is granted access to the entitlement.

Type

int

guild_id

The guild’s ID who is granted access to the SKU.

Type

Optional[int]

parent_id

The parent entitlement’s ID.

Type

Optional[int]

deleted

Whether the entitlement has been deleted.

Type

bool

consumed

For consumable items, whether the entitlement has been consumed.

Type

bool

branch_ids

The IDs of the granted application branches.

Type

List[int]

starts_at

A UTC start date after which the entitlement is valid.

Type

Optional[datetime]

ends_at

A UTC date after which entitlement is no longer valid.

Type

Optional[datetime]

promotion_id

The ID of the promotion this entitlement is from.

Type

Optional[int]

subscription_id

The ID of the subscription this entitlement is from.

Type

Optional[int]

gift_batch_id

The ID of the batch the gift attached to this entitlement from.

Type

Optional[int]

gifter_id

The user’s ID who gifted this entitlement.

Type

Optional[int]

gift_style

The style of the gift attached to this entitlement.

Type

Optional[GiftStyle]

fulfillment_status

The tenant fulfillment status of the entitlement.

Type

Optional[EntitlementFulfillmentStatus]

fulfilled_at

When the entitlement was fulfilled.

Type

Optional[datetime]

source_type

The type of the source this entitlement is from.

Type

Optional[EntitlementSourceType]

tenant_metadata

The tenant metadata for the entitlement.

Type

Optional[TenantMetadata]

sku

The granted SKU.

Type

Optional[SKU]

property gift_flags

The gift’s flags.

Type

GiftFlags

property user

The user that is granted access to the entitlement.

Type

Optional[User]

property guild

The guild that is granted access to the entitlement.

Type

Optional[Guild]

property created_at

Returns the entitlement’s creation time in UTC.

Type

datetime.datetime

is_expired()

bool: Returns True if the entitlement is expired. Will be always False for test entitlements.

await consume()

This function is a coroutine.

Marks a one-time purchase entitlement as consumed.

Raises
await delete()

This function is a coroutine.

Deletes the entitlement.

Raises

Subscription

class discord.Subscription

Represents a Discord subscription.

New in version 2.5.

id

The subscription’s ID.

Type

int

user_id

The ID of the user that is subscribed.

Type

int

sku_ids

The IDs of the SKUs that the user subscribed to.

Type

List[int]

entitlement_ids

The IDs of the entitlements granted for this subscription.

Type

List[int]

renewal_sku_ids

The IDs of the SKUs that the user is going to be subscribed to when renewing.

Type

List[int]

current_period_start

When the current billing period started.

Type

datetime.datetime

current_period_end

When the current billing period ends.

Type

datetime.datetime

status

The status of the subscription.

Type

SubscriptionStatus

canceled_at

When the subscription was canceled. This is only available for subscriptions with a status of SubscriptionStatus.inactive.

Type

Optional[datetime.datetime]

country

The ISO3166-1 alpha-2 country code of the payment source used to purchase the subscription.

Only present if Client.scopes contains payment_sources.country_code OAuth2 scope.

Type

Optional[str]

property created_at

Returns the subscription’s creation time in UTC.

Type

datetime.datetime

property user

The user that is subscribed.

Type

Optional[User]

RawMessageDeleteEvent

class discord.RawMessageDeleteEvent

Represents the event payload for a on_raw_message_delete() event.

channel_id

The channel ID where the deletion took place.

Type

int

guild_id

The guild ID where the deletion took place, if applicable.

Type

Optional[int]

message_id

The message ID that got deleted.

Type

int

cached_message

The cached message, if found in the internal message cache.

Type

Optional[Message]

RawBulkMessageDeleteEvent

class discord.RawBulkMessageDeleteEvent

Represents the event payload for a on_raw_bulk_message_delete() event.

message_ids

A set of the message IDs that were deleted.

Type

Set[int]

channel_id

The channel ID where the message got deleted.

Type

int

guild_id

The guild ID where the message got deleted, if applicable.

Type

Optional[int]

cached_messages

The cached messages, if found in the internal message cache.

Type

List[Message]

RawMessageUpdateEvent

class discord.RawMessageUpdateEvent

Represents the payload for a on_raw_message_edit() event.

message_id

The message ID that got updated.

Type

int

channel_id

The channel ID where the update took place.

New in version 1.3.

Type

int

guild_id

The guild ID where the message got updated, if applicable.

New in version 1.7.

Type

Optional[int]

data

The raw data given by the Gateway

Type

dict

cached_message

The cached message, if found in the internal message cache. Represents the message before it is modified by the data in RawMessageUpdateEvent.data.

Type

Optional[Message]

message

The updated message.

New in version 2.5.

Type

Message

RawReactionActionEvent

class discord.RawReactionActionEvent

Represents the payload for a on_raw_reaction_add() or on_raw_reaction_remove() event.

message_id

The message ID that got or lost a reaction.

Type

int

user_id

The user ID who added the reaction or whose reaction was removed.

Type

int

channel_id

The channel ID where the reaction got added or removed.

Type

int

guild_id

The guild ID where the reaction got added or removed, if applicable.

Type

Optional[int]

emoji

The custom or unicode emoji being used.

Type

PartialEmoji

member

The member who added the reaction. Only available if event_type is REACTION_ADD and the reaction is inside a guild.

New in version 1.3.

Type

Optional[Member]

message_author_id

The author ID of the message being reacted to. Only available if event_type is REACTION_ADD.

New in version 2.4.

Type

Optional[int]

event_type

The event type that triggered this action. Can be REACTION_ADD for reaction addition or REACTION_REMOVE for reaction removal.

New in version 1.3.

Type

str

burst

Whether the reaction was a burst reaction, also known as a “super reaction”.

New in version 2.4.

Type

bool

burst_colors

A list of colors used for burst reaction animation. Only available if burst is True and if event_type is REACTION_ADD.

New in version 2.0.

Changed in version 3.0: Renamed from burst_colours.

Type

List[Color]

type

The type of the reaction.

New in version 2.4.

Type

ReactionType

property burst_colours

An alias of burst_colors.

New in version 3.0.

RawReactionClearEvent

class discord.RawReactionClearEvent

Represents the payload for a on_raw_reaction_clear() event.

message_id

The message ID that got its reactions cleared.

Type

int

channel_id

The channel ID where the reactions got cleared.

Type

int

guild_id

The guild ID where the reactions got cleared.

Type

Optional[int]

RawReactionClearEmojiEvent

class discord.RawReactionClearEmojiEvent

Represents the payload for a on_raw_reaction_clear_emoji() event.

New in version 1.3.

message_id

The message ID that got its reactions cleared.

Type

int

channel_id

The channel ID where the reactions got cleared.

Type

int

guild_id

The guild ID where the reactions got cleared.

Type

Optional[int]

emoji

The custom or unicode emoji being removed.

Type

PartialEmoji

RawIntegrationDeleteEvent

class discord.RawIntegrationDeleteEvent

Represents the payload for a on_raw_integration_delete() event.

New in version 2.0.

application_id

The ID of the bot/OAuth2 application for this deleted integration.

Type

Optional[int]

integration_id

The ID of the integration that got deleted.

Type

int

guild_id

The guild ID where the integration got deleted.

Type

int

guild

The guild where the integration got deleted.

Type

Optional[Guild]

RawThreadUpdateEvent

Attributes
class discord.RawThreadUpdateEvent

Represents the payload for a on_raw_thread_update() event.

New in version 2.0.

guild_id

The ID of the guild the thread is in.

Type

int

data

The raw data given by the Gateway.

Type

dict

thread

The updated thread.

Type

Optional[discord.Thread]

old

The thread before being updated, if thread could be found in the internal cache.

Type

Optional[discord.Thread]

RawThreadMembersUpdate

class discord.RawThreadMembersUpdate

Represents the payload for a on_raw_thread_member_remove() event.

New in version 2.0.

thread_id

The ID of the thread that was updated.

Type

int

guild_id

The ID of the guild the thread is in.

Type

int

member_count

The approximate number of members in the thread. This caps at 50.

Type

int

data

The raw data given by the Gateway.

Type

dict

RawThreadDeleteEvent

class discord.RawThreadDeleteEvent

Represents the payload for a on_raw_thread_delete() event.

New in version 2.0.

thread_id

The ID of the thread that was deleted.

Type

int

thread_type

The channel type of the deleted thread.

Type

discord.ChannelType

guild_id

The ID of the guild the thread was deleted in.

Type

int

parent_id

The ID of the channel the thread belonged to.

Type

int

thread

The thread, if it could be found in the internal cache.

Type

Optional[discord.Thread]

RawTypingEvent

class discord.RawTypingEvent

Represents the payload for a on_raw_typing() event.

New in version 2.0.

channel_id

The ID of the channel the user started typing in.

Type

int

user_id

The ID of the user that started typing.

Type

int

user

The user that started typing, if they could be found in the internal cache.

Type

Optional[Union[discord.User, discord.Member]]

timestamp

When the typing started as an aware datetime in UTC.

Type

datetime.datetime

guild_id

The ID of the guild the user started typing in, if applicable.

Type

Optional[int]

RawMemberRemoveEvent

Attributes
class discord.RawMemberRemoveEvent

Represents the payload for a on_raw_member_remove() event.

New in version 2.0.

user

The user that left the guild.

Type

Union[discord.User, discord.Member]

guild_id

The ID of the guild the user left.

Type

int

RawAppCommandPermissionsUpdateEvent

class discord.RawAppCommandPermissionsUpdateEvent

Represents the payload for a on_raw_app_command_permissions_update() event.

New in version 2.0.

target_id

The ID of the command or application whose permissions were updated. When this is the application ID instead of a command ID, the permissions apply to all commands that do not contain explicit overwrites.

Type

int

application_id

The ID of the application that the command belongs to.

Type

int

guild

The guild where the permissions were updated.

Type

Guild

permissions

List of new permissions for the app command.

Type

List[AppCommandPermissions]

RawPollVoteActionEvent

class discord.RawPollVoteActionEvent

Represents the payload for a on_raw_poll_vote_add() or on_raw_poll_vote_remove() event.

New in version 2.4.

user_id

The ID of the user that added or removed a vote.

Type

int

channel_id

The channel ID where the poll vote action took place.

Type

int

message_id

The message ID that contains the poll the user added or removed their vote on.

Type

int

guild_id

The guild ID where the vote got added or removed, if applicable..

Type

Optional[int]

answer_id

The poll answer’s ID the user voted on.

Type

int

Presence

class discord.Presence

Represents the payload for a on_raw_presence_update() event.

New in version 2.5.

Changed in version 3.0: Renamed from RawPresenceUpdateEvent.

user_id

The ID of the user that triggered the presence update.

Type

int

user

The user that triggered the presence update, if available.

New in version 3.0.

Type

Optional[User]

guild_id

The guild ID for the users presence update. Could be None.

Type

Optional[int]

guild

The guild associated with the presence update and user. Could be None.

Type

Optional[Guild]

client_status

The ClientStatus model which holds information about the status of the user on various clients.

Type

ClientStatus

activities

The activities the user is currently doing. Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.

Type

Tuple[Union[BaseActivity, Spotify]]

hidden_activities

The hidden activities the user is currently doing. Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.

New in version 3.0.

Type

Tuple[Union[BaseActivity, Spotify]]

pair

The (old, new) pair representing old and new presence.

New in version 3.0.

Type

Optional[Union[Tuple[Member, Member], Tuple[Relationship, Relationship], Tuple[GameRelationship, GameRelationship]]

PartialWebhookGuild

Attributes
class discord.PartialWebhookGuild

Represents a partial guild for webhooks.

These are typically given for channel follower webhooks.

New in version 2.0.

id

The partial guild’s ID.

Type

int

name

The partial guild’s name.

Type

str

property icon

Returns the guild’s icon asset, if available.

Type

Optional[Asset]

PartialWebhookChannel

Attributes
class discord.PartialWebhookChannel

Represents a partial channel for webhooks.

These are typically given for channel follower webhooks.

New in version 2.0.

id

The partial channel’s ID.

Type

int

name

The partial channel’s name.

Type

str

property mention

The string that allows you to mention the channel that the webhook is following.

Type

str

PollAnswer

class discord.PollAnswer

Represents a poll’s answer.

str(x)

Returns this answer’s text, if any.

New in version 2.4.

id

The ID of this answer.

Type

int

media

The display data for this answer.

Type

PollMedia

self_voted

Whether the current user has voted to this answer or not.

Type

bool

property text

Returns this answer’s displayed text.

Type

str

property emoji

Returns this answer’s displayed emoji, if any.

Type

Optional[Union[Emoji, PartialEmoji]]

property vote_count

Returns an approximate count of votes for this answer.

If the poll is finished, the count is exact.

Type

int

property poll

Returns the parent poll of this answer.

Type

Poll

property victor

Whether the answer is the one that had the most votes when the poll ended.

New in version 2.5.

Note

If the poll has not ended, this will always return False.

Type

bool

MessageSnapshot

class discord.MessageSnapshot(data, state)

Represents a message snapshot attached to a forwarded message.

New in version 2.5.

type

The type of the forwarded message.

Type

MessageType

content

The actual contents of the forwarded message.

Type

str

embeds

A list of embeds the forwarded message has.

Type

List[Embed]

attachments

A list of attachments given to the forwarded message.

Type

List[Attachment]

created_at

The forwarded message’s time of creation.

Type

datetime.datetime

flags

Extra features of the the message snapshot.

Type

MessageFlags

stickers

A list of sticker items given to the message.

Type

List[StickerItem]

components

A list of components in the message.

Type

List[Union[ActionRow, Button, SelectMenu]]

raw_mentions

A property that returns an array of user IDs matched with the syntax of <@user_id> in the message content.

This allows you to receive the user IDs of mentioned users even in a private message context.

Type

List[int]

raw_channel_mentions

A property that returns an array of channel IDs matched with the syntax of <#channel_id> in the message content.

Type

List[int]

raw_role_mentions

A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content.

Type

List[int]

cached_message

Returns the cached message this snapshot points to, if any.

Type

Optional[Message]

property edited_at

An aware UTC datetime object containing the edited time of the forwarded message.

Type

Optional[datetime.datetime]

ClientStatus

class discord.ClientStatus

Represents the Client Status Object from Discord, which holds information about the status of the user on various clients/platforms, with additional helpers.

New in version 2.5.

property status

The user’s overall status. If the value is unknown, then it will be a str instead.

Type

Status

property raw_status

The user’s overall status as a string value.

Type

str

property mobile_status

The user’s status on a mobile device, if applicable.

Type

Status

property desktop_status

The user’s status on the desktop client, if applicable.

Type

Status

property web_status

The user’s status on the web client, if applicable.

Type

Status

property embedded_status

The user’s status on the embedded (PlayStation, Xbox, in-game) client, if applicable.

Type

Status

is_on_mobile()

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

PrimaryGuild

class discord.PrimaryGuild

Represents the primary guild identity of a User.

New in version 2.6.

id

The ID of the user’s primary guild, if any.

Type

Optional[int]

tag

The primary guild’s tag.

Type

Optional[str]

identity_enabled

Whether the user has their primary guild publicly displayed. If None, the user has a public guild but has not reaffirmed the guild identity after a change

Warning

Users can have their primary guild publicly displayed while still having an id of None. Be careful when checking this attribute!

Type

Optional[bool]

property badge

Returns the primary guild’s asset

Type

Optional[Asset]

property created_at

Returns the primary guild’s creation time in UTC.

Type

Optional[datetime.datetime]

ApplicationExecutable

class discord.ApplicationExecutable

Represents an application executable.

os

The operating system the executable is for.

Type

OperatingSystem

name

The name of the executable file.

Type

str

is_launcher

Indicates whether the executable is a launcher.

Type

bool

arguments

The arguments for an executable.

Type

str

DetectableApplication

class discord.DetectableApplication

Represents an application that can be detected by desktop client.

id

The application’s ID.

Type

int

name

The application’s name.

Type

str

aliases

A list of other names the application’s game is associated with.

Type

List[str]

executables

A list of unique executables of the application’s game.

Type

List[ApplicationExecutable]

themes

The themes of the application’s game.

Type

List[str]

hook

Indicates whether the Discord client is allowed to hook into the application’s game directly.

Type

bool

overlay

Whether the application’s game supports the Discord overlay.

Type

bool

overlay_warn

Whether the Discord overlay is known to be problematic with this application’s game.

Type

bool

overlay_compatibility_hook

Indicates whether to use the compatibility hook for the overlay.

Type

bool

property overlay_methods

The methods of overlaying that the application’s game supports.

Type

OverlayMethodFlags

Data Classes

Some classes are just there to be data containers, this lists them.

Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes.

Nearly all classes here have __slots__ defined which means that it is impossible to have dynamic attributes to the data classes.

The only exception to this rule is Object, which is made with dynamic attributes in mind.

Object

Attributes
class discord.Object(id, *, type=...)

Represents a generic Discord object.

The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.

There are also some cases where some websocket events are received in strange order and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.

x == y

Checks if two objects are equal.

x != y

Checks if two objects are not equal.

hash(x)

Returns the object’s hash.

id

The ID of the object.

Type

int

type

The discord.py model type of the object, if not specified, defaults to this class.

Note

In instances where there are multiple applicable types, use a shared base class. for example, both Member and User are subclasses of abc.User.

New in version 2.0.

Type

Type[abc.Snowflake]

property created_at

Returns the snowflake’s creation time in UTC.

Type

datetime.datetime

Embed

class discord.Embed(*, color=None, colour=None, title=None, type='rich', url=None, description=None, timestamp=None)

Represents a Discord embed.

len(x)

Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b)

Returns whether the embed has any data set.

New in version 2.0.

x == y

Checks if two embeds are equal.

New in version 2.0.

For ease of use, all parameters that expect a str are implicitly casted to str for you.

Changed in version 2.0: Embed.Empty has been removed in favour of None.

id

The ID of the embed. This attribute won’t be empty if received from RPC.

New in version 3.0.

Type

str

title

The title of the embed. This can be set during initialization. Can only be up to 256 characters.

Type

Optional[str]

type

The type of embed. Usually “rich”. This can be set during initialization. Possible strings for embed types can be found on discord’s api docs

Type

str

description

The description of the embed. This can be set during initialization. Can only be up to 4096 characters.

Type

Optional[str]

url

The URL of the embed. This can be set during initialization.

Type

Optional[str]

timestamp

The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.

Type

Optional[datetime.datetime]

color

The color code of the embed. Aliased to colour as well. This can be set during initialization.

Note

If the embed was received over RPC, css_color should be used instead.

Type

Optional[Union[Color, int]]

css_color

The CSS color of the embed. Aliased to css_colour as well.

New in version 3.0.

Type

Optional[str]

reference_id

The message’s ID this embed was generated from.

New in version 3.0.

Type

Optional[int]

content_scan_version

The version of the explicit content scan filter this embed was scanned with.

New in version 3.0.

Type

Optional[int]

classmethod from_dict(data)

Converts a dict to a Embed provided it is in the format that Discord expects it to be in.

You can find out about this format in the Discord Userdoccers.

Parameters

data (dict) – The dictionary to convert into an embed.

copy()

Returns a shallow copy of the embed.

property flags

The flags of this embed.

New in version 2.5.

Type

EmbedFlags

property footer

Returns an EmbedProxy denoting the footer contents.

See set_footer() for possible values you can access.

If the attribute has no value then None is returned.

Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Parameters

Clears embed’s footer information.

This function returns the class instance to allow for fluent-style chaining.

New in version 2.0.

property image

Returns an EmbedProxy denoting the image contents.

Possible attributes you can access are:

  • url for the image URL.

  • proxy_url for the proxied image URL.

  • width for the image width.

  • height for the image height.

  • flags for the image’s attachment flags.

If the attribute has no value then None is returned.

set_image(*, url)

Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Parameters

url (Optional[str]) – The source URL for the image. Only HTTP(S) is supported. If None is passed, any existing image is removed. Inline attachment URLs are also supported, see How do I use a local image file for an embed image?.

property thumbnail

Returns an EmbedProxy denoting the thumbnail contents.

Possible attributes you can access are:

  • url for the thumbnail URL.

  • proxy_url for the proxied thumbnail URL.

  • width for the thumbnail width.

  • height for the thumbnail height.

  • flags for the thumbnail’s attachment flags.

If the attribute has no value then None is returned.

set_thumbnail(*, url)

Sets the thumbnail for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Parameters

url (Optional[str]) – The source URL for the thumbnail. Only HTTP(S) is supported. If None is passed, any existing thumbnail is removed. Inline attachment URLs are also supported, see How do I use a local image file for an embed image?.

property video

Returns an EmbedProxy denoting the video contents.

Possible attributes include:

  • url for the video URL.

  • proxy_url for the proxied video URL.

  • height for the video height.

  • width for the video width.

  • flags for the video’s attachment flags.

If the attribute has no value then None is returned.

property provider

Returns an EmbedProxy denoting the provider contents.

The only attributes that might be accessed are name and url.

If the attribute has no value then None is returned.

property author

Returns an EmbedProxy denoting the author contents.

See set_author() for possible values you can access.

If the attribute has no value then None is returned.

set_author(*, name, url=None, icon_url=None)

Sets the author for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Parameters
remove_author()

Clears embed’s author information.

This function returns the class instance to allow for fluent-style chaining.

New in version 1.4.

property fields

Returns a list of EmbedProxy denoting the field contents.

See add_field() for possible values you can access.

If the attribute has no value then None is returned.

Type

List[EmbedProxy]

add_field(*, name, value, inline=True)

Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.

Parameters
  • name (str) – The name of the field. Can only be up to 256 characters.

  • value (str) – The value of the field. Can only be up to 1024 characters.

  • inline (bool) – Whether the field should be displayed inline.

insert_field_at(index, *, name, value, inline=True)

Inserts a field before a specified index to the embed.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.

New in version 1.2.

Parameters
  • index (int) – The index of where to insert the field.

  • name (str) – The name of the field. Can only be up to 256 characters.

  • value (str) – The value of the field. Can only be up to 1024 characters.

  • inline (bool) – Whether the field should be displayed inline.

clear_fields()

Removes all fields from this embed.

This function returns the class instance to allow for fluent-style chaining.

Changed in version 2.0: This function now returns the class instance.

remove_field(index)

Removes a field at a specified index.

If the index is invalid or out of bounds then the error is silently swallowed.

This function returns the class instance to allow for fluent-style chaining.

Note

When deleting a field by index, the index of the other fields shift to fill the gap just like a regular list.

Changed in version 2.0: This function now returns the class instance.

Parameters

index (int) – The index of the field to remove.

set_field_at(index, *, name, value, inline=True)

Modifies a field to the embed object.

The index must point to a valid pre-existing field. Can only be up to 25 fields.

This function returns the class instance to allow for fluent-style chaining.

Parameters
  • index (int) – The index of the field to modify.

  • name (str) – The name of the field. Can only be up to 256 characters.

  • value (str) – The value of the field. Can only be up to 1024 characters.

  • inline (bool) – Whether the field should be displayed inline.

Raises

IndexError – An invalid index was provided.

to_dict()

Converts this embed object into a dict.

AllowedMentions

class discord.AllowedMentions(*, everyone=True, users=True, roles=True, replied_user=True)

A class that represents what mentions are allowed in a message.

This class can be set during Client initialisation to apply to every message sent. It can also be applied on a per message basis via abc.Messageable.send() for more fine-grained control.

everyone

Whether to allow everyone and here mentions. Defaults to True.

Type

bool

users

Controls the users being mentioned. If True (the default) then users are mentioned based on the message content. If False then users are not mentioned at all. If a list of abc.Snowflake is given then only the users provided will be mentioned, provided those users are in the message content.

Type

Union[bool, Sequence[abc.Snowflake]]

roles

Controls the roles being mentioned. If True (the default) then roles are mentioned based on the message content. If False then roles are not mentioned at all. If a list of abc.Snowflake is given then only the roles provided will be mentioned, provided those roles are in the message content.

Type

Union[bool, Sequence[abc.Snowflake]]

replied_user

Whether to mention the author of the message being replied to. Defaults to True.

New in version 1.6.

Type

bool

classmethod all()

A factory method that returns a AllowedMentions with all fields explicitly set to True

New in version 1.5.

classmethod none()

A factory method that returns a AllowedMentions with all fields set to False

New in version 1.5.

MessageReference

class discord.MessageReference(*, message_id, channel_id, guild_id=None, fail_if_not_exists=True, type=<MessageReferenceType.default: 0>)

Represents a reference to a Message.

New in version 1.5.

Changed in version 1.6: This class can now be constructed by users.

type

The type of message reference.

New in version 2.5.

Type

MessageReferenceType

message_id

The ID of the message referenced. This can be None when this message reference was retrieved from a system message of one of the following types:

Type

Optional[int]

channel_id

The channel ID of the message referenced.

Type

int

guild_id

The guild ID of the message referenced.

Type

Optional[int]

fail_if_not_exists

Whether the referenced message should raise HTTPException if the message no longer exists or Discord could not fetch the message.

New in version 1.7.

Type

bool

resolved

The message that this reference resolved to. If this is None then the original message was not fetched either due to the Discord API not attempting to resolve it or it not being available at the time of creation. If the message was resolved at a prior point but has since been deleted then this will be of type DeletedReferencedMessage.

New in version 1.6.

Type

Optional[Union[Message, DeletedReferencedMessage]]

classmethod from_message(message, *, fail_if_not_exists=True, type=<MessageReferenceType.default: 0>)

Creates a MessageReference from an existing Message.

New in version 1.6.

Parameters
  • message (Message) – The message to be converted into a reference.

  • fail_if_not_exists (bool) –

    Whether the referenced message should raise HTTPException if the message no longer exists or Discord could not fetch the message.

    New in version 1.7.

  • type (MessageReferenceType) –

    The type of message reference this is.

    New in version 2.5.

Returns

A reference to the message.

Return type

MessageReference

property cached_message

The cached message, if found in the internal message cache.

Type

Optional[Message]

property jump_url

Returns a URL that allows the client to jump to the referenced message.

New in version 1.7.

Type

str

PartialMessage

Methods
class discord.PartialMessage(*, channel, id)

Represents a partial message to aid with working messages when only a message and channel ID are present.

There are two ways to construct this class. The first one is through the constructor itself, and the second is via the following:

Note that this class is trimmed down and has no rich attributes.

New in version 1.6.

x == y

Checks if two partial messages are equal.

x != y

Checks if two partial messages are not equal.

hash(x)

Returns the partial message’s hash.

channel

The channel associated with this partial message.

Type

Union[PartialMessageable, TextChannel, StageChannel, VoiceChannel, Thread, DMChannel]

id

The message ID.

Type

int

guild

The guild that the partial message belongs to, if applicable.

Type

Optional[Guild]

property created_at

The partial message’s creation time in UTC.

Type

datetime.datetime

property jump_url

Returns a URL that allows the client to jump to this message.

Type

str

property thread

The public thread created from this message, if it exists.

Note

This does not retrieve archived threads, as they are not retained in the internal cache. Use fetch_thread() instead.

New in version 2.4.

Type

Optional[Thread]

await delete(*, delay=None)

This function is a coroutine.

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you must have manage_messages.

Changed in version 1.1: Added the new delay keyword-only parameter.

Parameters

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

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

  • NotFound – The message was deleted already

  • HTTPException – Deleting the message failed.

await edit(*, content=..., attachments=..., delete_after=None, allowed_mentions=...)

This function is a coroutine.

Edits the message.

The content must be able to be transformed into a string via str(content).

Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.

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

Parameters
  • content (Optional[str]) – The new content to replace the message with. Could be None to remove the content.

  • attachments (List[Union[Attachment, File]]) –

    A list of attachments to keep in the message as well as new files to upload. If [] is passed then all attachments are removed.

    Note

    New files will always appear after current attachments.

    New in version 2.0.

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

  • allowed_mentions (Optional[AllowedMentions]) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    New in version 1.4.

Raises
  • HTTPException – Editing the message failed.

  • Forbidden – Tried to suppress a message without permissions or edited a message’s content or embed that isn’t yours.

  • NotFound – This message does not exist.

Returns

The newly edited message.

Return type

Message

to_reference(*, fail_if_not_exists=True, type=<MessageReferenceType.default: 0>)

Creates a MessageReference from the current message.

New in version 1.6.

Parameters
  • fail_if_not_exists (bool) –

    Whether the referenced message should raise HTTPException if the message no longer exists or Discord could not fetch the message.

    New in version 1.7.

  • type (MessageReferenceType) –

    The type of message reference.

    New in version 2.5.

Returns

The reference to this message.

Return type

MessageReference

MessageApplication

class discord.MessageApplication(*, data, state)

Represents a message’s application data from a Message.

New in version 2.0.

id

The application ID.

Type

int

description

The application description.

Type

str

name

The application’s name.

Type

str

property icon

The application’s icon, if any.

Type

Optional[Asset]

property cover

The application’s cover image, if any.

Type

Optional[Asset]

RoleSubscriptionInfo

class discord.RoleSubscriptionInfo(data)

Represents a message’s role subscription information.

This is currently only attached to messages of type MessageType.role_subscription_purchase.

New in version 2.0.

role_subscription_listing_id

The ID of the SKU and listing that the user is subscribed to.

Type

int

tier_name

The name of the tier that the user is subscribed to.

Type

str

total_months_subscribed

The cumulative number of months that the user has been subscribed for.

Type

int

is_renewal

Whether this notification is for a renewal rather than a new purchase.

Type

bool

PurchaseNotification

class discord.PurchaseNotification

Represents a message’s purchase notification data.

This is currently only attached to messages of type MessageType.purchase_notification.

New in version 2.5.

guild_product_purchase

The guild product purchase that prompted the message.

Type

Optional[GuildProductPurchase]

GuildProductPurchase

class discord.GuildProductPurchase

Represents a message’s guild product that the user has purchased.

New in version 2.5.

listing_id

The ID of the listing that the user has purchased.

Type

int

product_name

The name of the product that the user has purchased.

Type

str

AutoModRuleAction

class discord.AutoModRuleAction(*, type=None, channel_id=None, duration=None, custom_message=None)

Represents an auto moderation’s rule action.

Note

Only one of channel_id, duration, or custom_message can be used.

New in version 2.0.

type

The type of action to take. Defaults to block_message.

Type

AutoModRuleActionType

channel_id

The ID of the channel or thread to send the alert message to, if any. Passing this sets type to send_alert_message.

Type

Optional[int]

duration

The duration of the timeout to apply, if any. Has a maximum of 28 days. Passing this sets type to timeout.

Type

Optional[datetime.timedelta]

custom_message

A custom message which will be shown to a user when their message is blocked. Passing this sets type to block_message.

New in version 2.2.

Type

Optional[str]

AutoModTrigger

class discord.AutoModTrigger(*, type=None, keyword_filter=None, presets=None, allow_list=None, mention_limit=None, regex_patterns=None, mention_raid_protection=None)

Represents a trigger for an auto moderation rule.

The following table illustrates relevant attributes for each AutoModRuleTriggerType:

New in version 2.0.

type

The type of trigger.

Type

AutoModRuleTriggerType

keyword_filter

The list of strings that will trigger the filter. Maximum of 1000. Keywords can only be up to 60 characters in length.

This could be combined with regex_patterns.

Type

List[str]

regex_patterns

The regex pattern that will trigger the filter. The syntax is based off of Rust’s regex syntax. Maximum of 10. Regex strings can only be up to 260 characters in length.

This could be combined with keyword_filter and/or allow_list

New in version 2.1.

Type

List[str]

presets

The presets used with the preset keyword filter.

Type

AutoModPresets

allow_list

The list of words that are exempt from the commonly flagged words. Maximum of 100. Keywords can only be up to 60 characters in length.

Type

List[str]

mention_limit

The total number of user and role mentions a message can contain. Has a maximum of 50.

Type

int

mention_raid_protection

Whether mention raid protection is enabled or not.

New in version 2.4.

Type

bool

File

class discord.File(fp, filename=None, *, spoiler=..., description=None)

A parameter object used for abc.Messageable.send() for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple abc.Messageable.send()s.

fp

A file-like object opened in binary mode and read mode or a filename representing a file in the hard drive to open.

Note

If the file-like object passed is opened via open then the modes ‘rb’ should be used.

To pass binary data, consider usage of io.BytesIO.

Type

Union[os.PathLike, io.BufferedIOBase]

spoiler

Whether the attachment is a spoiler. If left unspecified, the filename is used to determine if the file is a spoiler.

Type

bool

description

The file description to display, currently only supported for images.

New in version 2.0.

Type

Optional[str]

property filename

The filename to display when uploading to Discord. If this is not given then it defaults to fp.name or if fp is a string then the filename will default to the string given.

Type

str

Color

class discord.Color(value)

Represents a Discord role color. This class is similar to a (red, green, blue) tuple.

There is an alias for this called Colour.

x == y

Checks if two colors are equal.

x != y

Checks if two colors are not equal.

hash(x)

Return the color’s hash.

str(x)

Returns the hex format for the color.

int(x)

Returns the raw color value.

Note

The color values in the classmethods are mostly provided as-is and can change between versions should the Discord client’s representation of that color also change.

value

The raw integer color value.

Type

int

property r

Returns the red component of the color.

Type

int

property g

Returns the green component of the color.

Type

int

property b

Returns the blue component of the color.

Type

int

to_rgb()

Tuple[int, int, int]: Returns an (r, g, b) tuple representing the color.

classmethod from_rgb(r, g, b)

Constructs a Color from an RGB tuple.

classmethod from_hsv(h, s, v)

Constructs a Color from an HSV tuple.

classmethod from_str(value)

Constructs a Color from a string.

The following formats are accepted:

  • 0x<hex>

  • #<hex>

  • 0x#<hex>

  • rgb(<number>, <number>, <number>)

Like CSS, <number> can be either 0-255 or 0-100% and <hex> can be either a 6 digit hex number or a 3 digit hex shortcut (e.g. #FFF).

New in version 2.0.

Raises

ValueError – The string could not be converted into a color.

classmethod default()

A factory method that returns a Color with a value of 0.

classmethod random(*, seed=None)

A factory method that returns a Color with a random hue.

Note

The random algorithm works by choosing a color with a random hue but with maxed out saturation and value.

New in version 1.6.

Parameters

seed (Optional[Union[int, str, float, bytes, bytearray]]) –

The seed to initialize the RNG with. If None is passed the default RNG is used.

New in version 1.7.

classmethod teal()

A factory method that returns a Color with a value of 0x1ABC9C.

classmethod dark_teal()

A factory method that returns a Color with a value of 0x11806A.

classmethod brand_green()

A factory method that returns a Color with a value of 0x57F287.

New in version 2.0.

classmethod green()

A factory method that returns a Color with a value of 0x2ECC71.

classmethod dark_green()

A factory method that returns a Color with a value of 0x1F8B4C.

classmethod blue()

A factory method that returns a Color with a value of 0x3498DB.

classmethod dark_blue()

A factory method that returns a Color with a value of 0x206694.

classmethod purple()

A factory method that returns a Color with a value of 0x9B59B6.

classmethod dark_purple()

A factory method that returns a Color with a value of 0x71368A.

classmethod magenta()

A factory method that returns a Color with a value of 0xE91E63.

classmethod dark_magenta()

A factory method that returns a Color with a value of 0xAD1457.

classmethod gold()

A factory method that returns a Color with a value of 0xF1C40F.

classmethod dark_gold()

A factory method that returns a Color with a value of 0xC27C0E.

classmethod orange()

A factory method that returns a Color with a value of 0xE67E22.

classmethod dark_orange()

A factory method that returns a Color with a value of 0xA84300.

classmethod brand_red()

A factory method that returns a Color with a value of 0xED4245.

New in version 2.0.

classmethod red()

A factory method that returns a Color with a value of 0xE74C3C.

classmethod dark_red()

A factory method that returns a Color with a value of 0x992D22.

classmethod lighter_grey()

A factory method that returns a Color with a value of 0x95A5A6.

classmethod lighter_gray()

A factory method that returns a Color with a value of 0x95A5A6.

classmethod dark_grey()

A factory method that returns a Color with a value of 0x607d8b.

classmethod dark_gray()

A factory method that returns a Color with a value of 0x607d8b.

classmethod light_grey()

A factory method that returns a Color with a value of 0x979C9F.

classmethod light_gray()

A factory method that returns a Color with a value of 0x979C9F.

classmethod darker_grey()

A factory method that returns a Color with a value of 0x546E7A.

classmethod darker_gray()

A factory method that returns a Color with a value of 0x546E7A.

classmethod og_blurple()

A factory method that returns a Color with a value of 0x7289DA.

classmethod blurple()

A factory method that returns a Color with a value of 0x5865F2.

classmethod greyple()

A factory method that returns a Color with a value of 0x99AAB5.

classmethod dark_theme()

A factory method that returns a Color with a value of 0x313338.

This will appear transparent on Discord’s dark theme.

New in version 1.5.

Changed in version 2.2: Updated color from previous 0x36393F to reflect discord theme changes.

classmethod fuchsia()

A factory method that returns a Color with a value of 0xEB459E.

New in version 2.0.

classmethod yellow()

A factory method that returns a Color with a value of 0xFEE75C.

New in version 2.0.

classmethod dark_embed()

A factory method that returns a Color with a value of 0x2B2D31.

New in version 2.2.

classmethod light_embed()

A factory method that returns a Color with a value of 0xEEEFF1.

New in version 2.2.

classmethod pink()

A factory method that returns a Color with a value of 0xEB459F.

New in version 2.3.

BaseActivity

Attributes
class discord.BaseActivity(**kwargs)

The base activity that all user-settable activities inherit from. An user-settable activity is one that can be used in Client.change_presence().

The following types currently count as user-settable:

Note that although these types are considered user-settable by the library, Discord typically ignores certain combinations of activity depending on what is currently set. This behavior may change in the future so there are no guarantees on whether Discord will actually let you set these types.

New in version 1.3.

id

The activity’s ID. Only unique per user.

New in version 3.0.

Type

str

property created_at

When the user started doing this activity in UTC.

New in version 1.3.

Type

Optional[datetime]

Activity

class discord.Activity(**kwargs)

Represents an activity in Discord.

This could be an activity such as streaming, playing, listening or watching.

For memory optimization purposes, some activities are offered in slimmed down versions:

name

The name of the activity.

Type

Optional[str]

type

The type of activity currently being done.

Type

ActivityType

url

A stream URL that the activity could be doing.

Type

Optional[str]

session_id

The ID of the Gateway session the activity is attached to.

Type

Optional[str]

platform

The user’s current platform.

New in version 2.4.

Changed in version 3.0: The type was changed from str to ActivityPlatform.

Type

Optional[ActivityPlatform]

start_timestamp

Corresponds to when the user started doing the activity in milliseconds since Unix epoch.

Type

Optional[int]

end_timestamp

Corresponds to when the user will finish doing the activity in milliseconds since Unix epoch.

Type

Optional[int]:

application_id

The application ID of the game.

Type

Optional[int]

parent_application_id

The game’s parent application ID.

New in version 3.0.

Type

Optional[int]

status_display_type

The field that is displayed in the user’s status text (in member/DM list).

New in version 3.0.

Type

Optional[StatusDisplayType]

details

The detail of the user’s current activity.

Type

Optional[str]

details_url

The URL that is opened when clicking on the details text. Can be only up to 256 characters.

New in version 3.0.

Type

Optional[str]

state

The user’s current state. For example, “In Game”.

Type

Optional[str]

state_url

The URL that is opened when clicking on the state text. Can be only up to 256 characters.

New in version 3.0.

Type

Optional[str]

sync_id

The ID of the synced activity (for example, a Spotify song ID).

Type

Optional[str]

button_labels

A list of strings representing the labels of custom buttons shown in a rich presence.

New in version 2.0.

Changed in version 3.0: Renamed from buttons.

Type

List[str]

emoji

The emoji that belongs to this activity.

Type

Optional[PartialEmoji]

party

The party of the activity.

Changed in version 3.0: The type was changed from dict.

Type

Optional[ActivityParty]

assets

The images and their hover text of an activity.

Changed in version 3.0: The type was changed from dict.

Type

Optional[ActivityAssets]

metadata

A dictionary representing the activity metadata.

It contains the following optional keys:

  • button_urls: A list representing URLs correpresenting to the custom buttons shown in Rich Presence.

  • artist_ids: A list representing the Spotify IDs of artists.

  • album_id: A string representing the ID of album of the song being played.

  • context_uri: A string representing the Spotify URI of the current player context.

  • type: A string representing the type of Spotify being played, generally track or episode.

See more details on Discord Userdoccers.

Danger

Contents inside this attribute are NOT sanitized and can have technically anything. Treat data carefully.

Type

Dict[str, Any]

property start

When the user started doing this activity in UTC, if applicable.

Type

Optional[datetime]

property end

When the user will stop doing this activity in UTC, if applicable.

Type

Optional[datetime]

property large_image_url

Returns an URL pointing to the large image asset of this activity, if applicable.

Type

Optional[str]

property large_url

The URL that is opened when clicking on the large image, if applicable.

Type

Optional[str]

property small_image_url

Returns an URL pointing to the small image asset of this activity, if applicable.

Type

Optional[str]

property large_image_text

Returns the large image asset hover text of this activity, if applicable.

Type

Optional[str]

property small_image_text

Returns the small image asset hover text of this activity, if applicable.

Type

Optional[str]

property small_url

The URL that is opened when clicking on the small image, if applicable.

Type

Optional[str]

Game

class discord.Game(details=None, **extra)

A slimmed down version of Activity that represents a Discord game.

This is typically displayed via Playing on the official Discord client.

The parameters are mostly same as attributes, with additional ones detailed below.

x == y

Checks if two games are equal.

x != y

Checks if two games are not equal.

hash(x)

Returns the game’s hash.

str(x)

Returns the game’s name.

Parameters

supported_platforms (Optional[ActivityPlatforms]) – The platforms the game is supported on.

name

The game’s name.

Type

str

session_id

The ID of the Gateway session the activity is attached to.

Type

Optional[str]

start_timestamp

Corresponds to when the user started doing the activity in milliseconds since Unix epoch.

Type

Optional[int]

end_timestamp

Corresponds to when the user will finish doing the activity in milliseconds since Unix epoch.

Type

Optional[int]:

platform

Where the user is playing from (ie. PS5, Xbox).

New in version 2.4.

Changed in version 3.0: The type was changed from str to ActivityPlatform.

Type

Optional[ActivityPlatform]

application_id

The game’s application ID.

Type

Optional[int]

parent_application_id

The game’s parent application ID.

Type

Optional[int]

status_display_type

The field that is displayed in the user’s status text (in member/DM list).

Type

Optional[StatusDisplayType]

details

The game’s details.

Type

Optional[str]

details_url

The URL that is opened when clicking on the details text. Can be only up to 256 characters.

Type

Optional[str]

state

The game’s state.

Type

Optional[str]

state_url

The URL that is opened when clicking on the state text. Can be only up to 256 characters.

Type

Optional[str]

button_labels

A list of strings representing the labels of custom buttons shown in a rich presence.

New in version 2.0.

Changed in version 3.0: The attribute was renamed from buttons to button_labels.

Type

List[str]

party

The party of the activity.

Type

Optional[ActivityParty]

assets

The images and their hover text of an activity.

Type

Optional[ActivityAssets]

secrets

The secrets for joining/spectating a game.

Type

Optional[ActivitySecrets]

metadata

A dictionary representing the activity metadata.

It contains the following optional keys:

  • button_urls: A list representing URLs correpresenting to the custom buttons shown in Rich Presence.

  • artist_ids: A list representing the Spotify IDs of artists.

  • album_id: A string representing the ID of album of the song being played.

  • context_uri: A string representing the Spotify URI of the current player context.

  • type: A string representing the type of Spotify being played, generally track or episode.

See more details on Discord Userdoccers.

Danger

Contents inside this attribute are NOT sanitized and can have technically anything. Treat data carefully.”

Type

Dict[str, Any]

property supported_platforms

The platforms the game is supported on.

Type

Optional[ActivityPlatforms]

property flags

The activity’s flags.

Type

ActivityFlags

property type

Returns the game’s type. This is for compatibility with Activity.

It always returns ActivityType.playing.

Type

ActivityType

property start

When the user started playing this game in UTC, if applicable.

Type

Optional[datetime]

property end

When the user will stop playing this game in UTC, if applicable.

Type

Optional[datetime]

add_button(label, *, url)

Adds a button.

Parameters
  • label (str) – The label of the button.

  • url (str) – The URL of the button.

Returns

The current instance, for chaining.

Return type

Game

Streaming

class discord.Streaming(*, name, url, **extra)

A slimmed down version of Activity that represents a Discord streaming status.

This is typically displayed via Streaming on the official Discord client.

x == y

Checks if two streams are equal.

x != y

Checks if two streams are not equal.

hash(x)

Returns the stream’s hash.

str(x)

Returns the stream’s name.

platform

Where the user is streaming from (ie. YouTube, Twitch).

New in version 1.3.

Type

Optional[str]

name

The stream’s name.

Type

Optional[str]

details

An alias for name.

Type

Optional[str]

game

The game being streamed.

New in version 1.3.

Type

Optional[str]

url

The stream’s URL.

Type

str

assets

The stream’s assets.

Type

ActivityAssets

property type

Returns the game’s type. This is for compatibility with Activity.

It always returns ActivityType.streaming.

Type

ActivityType

property twitch_name

If provided, the Twitch name of the user streaming.

This corresponds to the large_image key of the Streaming.assets dictionary if it starts with twitch:. Typically set by the Discord client.

Type

Optional[str]

CustomActivity

class discord.CustomActivity(name, *, emoji=None, state=None, expires_at=None, **kwargs)

Represents a custom activity from Discord.

x == y

Checks if two activities are equal.

x != y

Checks if two activities are not equal.

hash(x)

Returns the activity’s hash.

str(x)

Returns the custom status text.

New in version 1.3.

name

The custom activity’s name.

Type

Optional[str]

emoji

The emoji to pass to the activity, if any.

Type

Optional[PartialEmoji]

expires_at

When the custom activity will expire. This is only available from UserSettings.custom_activity.

New in version 3.0.

Type

Optional[datetime]

label

The custom activity’s label.

New in version 3.0.

Type

Optional[CustomStatusLabelType]

property type

Returns the activity’s type. This is for compatibility with Activity.

It always returns custom.

Type

ActivityType

Permissions

class discord.Permissions(permissions=0, **kwargs)

Wraps up the Discord permission value.

The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.

Changed in version 1.3: You can now use keyword arguments to initialize Permissions similar to update().

x == y

Checks if two permissions are equal.

x != y

Checks if two permissions are not equal.

x <= y

Checks if a permission is a subset of another permission.

x >= y

Checks if a permission is a superset of another permission.

x < y

Checks if a permission is a strict subset of another permission.

x > y

Checks if a permission is a strict superset of another permission.

x | y, x |= y

Returns a Permissions instance with all enabled flags from both x and y.

New in version 2.0.

x & y, x &= y

Returns a Permissions instance with only flags enabled on both x and y.

New in version 2.0.

x ^ y, x ^= y

Returns a Permissions instance with only flags enabled on only one of x or y, not on both.

New in version 2.0.

~x

Returns a Permissions instance with all flags inverted from x.

New in version 2.0.

hash(x)

Return the permission’s hash.

iter(x)

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

bool(b)

Returns whether the permissions object has any permissions set to True.

New in version 2.0.

value

The raw value. This value is a bit array field of a 53-bit integer representing the currently available permissions. You should query permissions via the properties rather than using this raw value.

Type

int

is_subset(other)

Returns True if self has the same or fewer permissions as other.

is_superset(other)

Returns True if self has the same or more permissions as other.

is_strict_subset(other)

Returns True if the permissions on other are a strict subset of those on self.

is_strict_superset(other)

Returns True if the permissions on other are a strict superset of those on self.

classmethod none()

A factory method that creates a Permissions with all permissions set to False.

classmethod all()

A factory method that creates a Permissions with all permissions set to True.

classmethod all_channel()

A Permissions with all channel-specific permissions set to True and the guild-specific ones set to False. The guild-specific permissions are currently:

Changed in version 1.7: Added stream, priority_speaker and use_application_commands permissions.

Changed in version 2.3: Added use_soundboard, create_expressions permissions.

Changed in version 2.4: Added send_polls, send_voice_messages, attr:use_external_sounds, use_embedded_activities, and use_external_apps permissions.

classmethod general()

A factory method that creates a Permissions with all “General” permissions from the official Discord UI set to True.

Changed in version 1.7: Permission read_messages is now included in the general permissions, but permissions administrator, create_instant_invite, kick_members, ban_members, change_nickname and manage_nicknames are no longer part of the general permissions.

Changed in version 2.3: Added create_expressions permission.

Changed in version 2.4: Added view_creator_monetization_analytics permission.

classmethod membership()

A factory method that creates a Permissions with all “Membership” permissions from the official Discord UI set to True.

New in version 1.7.

classmethod text()

A factory method that creates a Permissions with all “Text” permissions from the official Discord UI set to True.

Changed in version 1.7: Permission read_messages is no longer part of the text permissions. Added use_application_commands permission.

Changed in version 2.3: Added send_voice_messages permission.

Changed in version 2.4: Added send_polls and use_external_apps permissions.

classmethod voice()

A factory method that creates a Permissions with all “Voice” permissions from the official Discord UI set to True.

classmethod stage()

A factory method that creates a Permissions with all “Stage Channel” permissions from the official Discord UI set to True.

New in version 1.7.

classmethod stage_moderator()

A factory method that creates a Permissions with all permissions for stage moderators set to True. These permissions are currently:

New in version 1.7.

Changed in version 2.0: Added manage_channels permission and removed request_to_speak permission.

classmethod elevated()

A factory method that creates a Permissions with all permissions that require 2FA set to True. These permissions are currently:

New in version 2.0.

classmethod events()

A factory method that creates a Permissions with all “Events” permissions from the official Discord UI set to True.

New in version 2.4.

classmethod advanced()

A factory method that creates a Permissions with all “Advanced” permissions from the official Discord UI set to True.

New in version 1.7.

update(**kwargs)

Bulk updates this permission object.

Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored.

Parameters

**kwargs – A list of key/value pairs to bulk update permissions with.

create_instant_invite

Returns True if the user can create instant invites.

Type

bool

kick_members

Returns True if the user can kick users from the guild.

Type

bool

ban_members

Returns True if a user can ban users from the guild.

Type

bool

administrator

Returns True if a user is an administrator. This role overrides all other permissions.

This also bypasses all channel-specific overrides.

Type

bool

manage_channels

Returns True if a user can edit, delete, or create channels in the guild.

This also corresponds to the “Manage Channel” channel-specific override.

Type

bool

manage_guild

Returns True if a user can edit guild properties.

Type

bool

add_reactions

Returns True if a user can add reactions to messages.

Type

bool

view_audit_log

Returns True if a user can view the guild’s audit log.

Type

bool

priority_speaker

Returns True if a user can be more easily heard while talking.

Type

bool

stream

Returns True if a user can stream in a voice channel.

Type

bool

read_messages

Returns True if a user can read messages from all or specific text channels.

Type

bool

view_channel

An alias for read_messages.

New in version 1.3.

Type

bool

send_messages

Returns True if a user can send messages from all or specific text channels.

Type

bool

send_tts_messages

Returns True if a user can send TTS messages from all or specific text channels.

Type

bool

manage_messages

Returns True if a user can delete or pin messages in a text channel.

Note

Note that there are currently no ways to edit other people’s messages.

Type

bool

Returns True if a user’s messages will automatically be embedded by Discord.

Type

bool

attach_files

Returns True if a user can send files in their messages.

Type

bool

read_message_history

Returns True if a user can read a text channel’s previous messages.

Type

bool

mention_everyone

Returns True if a user’s @everyone or @here will mention everyone in the text channel.

Type

bool

external_emojis

Returns True if a user can use emojis from other guilds.

Type

bool

use_external_emojis

An alias for external_emojis.

New in version 1.3.

Type

bool

view_guild_insights

Returns True if a user can view the guild’s insights.

New in version 1.3.

Type

bool

connect

Returns True if a user can connect to a voice channel.

Type

bool

speak

Returns True if a user can speak in a voice channel.

Type

bool

mute_members

Returns True if a user can mute other users.

Type

bool

deafen_members

Returns True if a user can deafen other users.

Type

bool

move_members

Returns True if a user can move users between other voice channels.

Type

bool

use_voice_activation

Returns True if a user can use voice activation in voice channels.

Type

bool

change_nickname

Returns True if a user can change their nickname in the guild.

Type

bool

manage_nicknames

Returns True if a user can change other user’s nickname in the guild.

Type

bool

manage_roles

Returns True if a user can create or edit roles less than their role’s position.

This also corresponds to the “Manage Permissions” channel-specific override.

Type

bool

manage_permissions

An alias for manage_roles.

New in version 1.3.

Type

bool

manage_webhooks

Returns True if a user can create, edit, or delete webhooks.

Type

bool

manage_expressions

Returns True if a user can edit or delete emojis, stickers, and soundboard sounds.

New in version 2.3.

Type

bool

manage_emojis

An alias for manage_expressions.

Type

bool

manage_emojis_and_stickers

An alias for manage_expressions.

New in version 2.0.

Type

bool

use_application_commands

Returns True if a user can use slash commands.

New in version 1.7.

Type

bool

request_to_speak

Returns True if a user can request to speak in a stage channel.

New in version 1.7.

Type

bool

manage_events

Returns True if a user can manage guild events.

New in version 2.0.

Type

bool

manage_threads

Returns True if a user can manage threads.

New in version 2.0.

Type

bool

create_public_threads

Returns True if a user can create public threads.

New in version 2.0.

Type

bool

create_private_threads

Returns True if a user can create private threads.

New in version 2.0.

Type

bool

external_stickers

Returns True if a user can use stickers from other guilds.

New in version 2.0.

Type

bool

use_external_stickers

An alias for external_stickers.

New in version 2.0.

Type

bool

send_messages_in_threads

Returns True if a user can send messages in threads.

New in version 2.0.

Type

bool

use_embedded_activities

Returns True if a user can launch an embedded application in a Voice channel.

New in version 2.0.

Type

bool

moderate_members

Returns True if a user can time out other members.

New in version 2.0.

Type

bool

view_creator_monetization_analytics

Returns True if a user can view role subscription insights.

New in version 2.4.

Type

bool

use_soundboard

Returns True if a user can use the soundboard.

New in version 2.3.

Type

bool

create_expressions

Returns True if a user can create emojis, stickers, and soundboard sounds.

New in version 2.3.

Type

bool

create_events

Returns True if a user can create guild events.

New in version 2.4.

Type

bool

use_external_sounds

Returns True if a user can use sounds from other guilds.

New in version 2.3.

Type

bool

send_voice_messages

Returns True if a user can send voice messages.

New in version 2.3.

Type

bool

send_polls

Returns True if a user can send poll messages.

New in version 2.4.

Type

bool

create_polls

An alias for send_polls.

New in version 2.4.

Type

bool

use_external_apps

Returns True if a user can use external apps.

New in version 2.4.

Type

bool

PermissionOverwrite

class discord.PermissionOverwrite(**kwargs)

A type that is used to represent a channel specific permission.

Unlike a regular Permissions, the default value of a permission is equivalent to None and not False. Setting a value to False is explicitly denying that permission, while setting a value to True is explicitly allowing that permission.

The values supported by this are the same as Permissions with the added possibility of it being set to None.

x == y

Checks if two overwrites are equal.

x != y

Checks if two overwrites are not equal.

iter(x)

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

Parameters

**kwargs – Set the value of permissions by their name.

pair()

Tuple[Permissions, Permissions]: Returns the (allow, deny) pair from this overwrite.

classmethod from_pair(allow, deny)

Creates an overwrite from an allow/deny pair of Permissions.

is_empty()

Checks if the permission overwrite is currently empty.

An empty permission overwrite is one that has no overwrites set to True or False.

Returns

Indicates if the overwrite is empty.

Return type

bool

update(**kwargs)

Bulk updates this permission overwrite object.

Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored.

Parameters

**kwargs – A list of key/value pairs to bulk update with.

ForumTag

Attributes
class discord.ForumTag(*, name, emoji=None, moderated=False)

Represents a forum tag that can be applied to a thread within a ForumChannel.

New in version 2.1.

x == y

Checks if two forum tags are equal.

x != y

Checks if two forum tags are not equal.

hash(x)

Returns the forum tag’s hash.

str(x)

Returns the forum tag’s name.

id

The ID of the tag. If this was manually created then the ID will be 0.

Type

int

name

The name of the tag. Can only be up to 20 characters.

Type

str

moderated

Whether this tag can only be added or removed by a moderator with the manage_threads permission.

Type

bool

emoji

The emoji that is used to represent this tag. Note that if the emoji is a custom emoji, it will not have name information.

Type

Optional[PartialEmoji]

Flags

class discord.AppCommandContext(**kwargs)

Wraps up the Discord BaseCommand execution context.

New in version 2.4.

x == y

Checks if two AppCommandContext flags are equal.

x != y

Checks if two AppCommandContext flags are not equal.

x | y, x |= y

Returns an AppCommandContext instance with all enabled flags from both x and y.

x & y, x &= y

Returns an AppCommandContext instance with only flags enabled on both x and y.

x ^ y, x ^= y

Returns an AppCommandContext instance with only flags enabled on only one of x or y, not on both.

~x

Returns an AppCommandContext instance with all flags inverted from x.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

value

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

Type

int

guild

Whether the context allows usage in a guild.

Type

bool

dm_channel

Whether the context allows usage in a DM channel.

Type

bool

private_channel

Whether the context allows usage in a DM or a GDM channel.

Type

bool

class discord.ActivityFlags(**kwargs)

Wraps up the Discord activity flags.

New in version 3.0.

x == y

Checks if two ActivityFlags flags are equal.

x != y

Checks if two ActivityFlags flags are not equal.

x | y, x |= y

Returns an ActivityFlags instance with all enabled flags from both x and y.

x & y, x &= y

Returns an ActivityFlags instance with only flags enabled on both x and y.

x ^ y, x ^= y

Returns an ActivityFlags instance with only flags enabled on only one of x or y, not on both.

~x

Returns an ActivityFlags instance with all flags inverted from x.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

value

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

Type

int

instance

Returns True if the activity is an instanced game session (a match that will end).

Type

bool

join

Returns True if the activity can be joined by other users.

Type

bool

spectate

Returns True if the activity can be spectated by other users (deprecated).

Type

bool

sync

Returns True if the activity can be synced.

Type

bool

play

Returns True if the activity can be played.

Type

bool

party_privacy_friends

Returns True if the activity’s party can be joined by friends.

Type

bool

party_privacy_voice_channel

Returns True if the activity’s party can be joined by users in the same voice channel.

Type

bool

embedded

Returns True if the activity is embedded within the Discord client.

Type

bool

class discord.ActivityPlatforms(**kwargs)

Represents a list of platforms supported by Discord activity.

New in version 3.0.

x == y

Checks if two ActivityPlatforms flags are equal.

x != y

Checks if two ActivityPlatforms flags are not equal.

x | y, x |= y

Returns an ActivityPlatforms instance with all enabled flags from both x and y.

x & y, x &= y

Returns an ActivityPlatforms instance with only flags enabled on both x and y.

x ^ y, x ^= y

Returns an ActivityPlatforms instance with only flags enabled on only one of x or y, not on both.

~x

Returns an ActivityPlatforms instance with all flags inverted from x.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

value

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

Type

int

desktop

Returns True if activity is supported on desktop platforms.

Type

bool

xbox

Returns True if activity is supported on Xbox.

Type

bool

samsung

Returns True if activity is supported on Samsung devices.

Type

bool

ios

Returns True if activity is supported on iOS.

Type

bool

android

Returns True if activity is supported on Android.

Type

bool

embedded

Returns True if activity is supported on embedded platforms.

Type

bool

ps4

Returns True if activity is supported on PS4.

Type

bool

ps5

Returns True if activity is supported on PS5.

Type

bool

Attributes
class discord.AppInstallationType(**kwargs)

Represents the installation location of an application command.

New in version 2.4.

x == y

Checks if two AppInstallationType flags are equal.

x != y

Checks if two AppInstallationType flags are not equal.

x | y, x |= y

Returns an AppInstallationType instance with all enabled flags from both x and y.

x & y, x &= y

Returns an AppInstallationType instance with only flags enabled on both x and y.

x ^ y, x ^= y

Returns an AppInstallationType instance with only flags enabled on only one of x or y, not on both.

~x

Returns an AppInstallationType instance with all flags inverted from x.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

value

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

Type

int

guild

Whether the integration is a guild install.

Type

bool

user

Whether the integration is a user install.

Type

bool

class discord.ApplicationFlags(**kwargs)

Wraps up the Discord Application flags.

x == y

Checks if two ApplicationFlags are equal.

x != y

Checks if two ApplicationFlags are not equal.

x | y, x |= y

Returns an ApplicationFlags instance with all enabled flags from both x and y.

New in version 2.0.

x & y, x &= y

Returns an ApplicationFlags instance with only flags enabled on both x and y.

New in version 2.0.

x ^ y, x ^= y

Returns an ApplicationFlags instance with only flags enabled on only one of x or y, not on both.

New in version 2.0.

~x

Returns an ApplicationFlags instance with all flags inverted from x.

New in version 2.0.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

New in version 2.0.

value

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

Type

int

embedded_released

Returns True if the embedded application is released to the public.

Type

bool

managed_emoji

Returns True if the application can create managed emojis.

Type

bool

embedded_iap

Returns True if the embedded application can use in-app purchases.

Type

bool

group_dm_create

Returns True if the application can create group DMs without limit.

Type

bool

auto_mod_badge

Returns True if the application uses at least 100 automod rules across all guilds. This shows up as a badge in the official client.

New in version 2.3.

Type

bool

game_profile_disabled

Returns True if the application has it’s game profile page disabled.

Type

bool

public_oauth2_client

Returns True if the application’s OAuth2 credentials are public.

Type

bool

contextless_activity

Returns True if the embedded application’s activity can be launched without a context.

Type

bool

social_layer_integration_limited

Returns True if the application has limited access to the social layer API.

Type

bool

gateway_presence

Returns True if the application is verified and is allowed to receive presence information over the gateway.

Type

bool

gateway_presence_limited

Returns True if the application is allowed to receive limited presence information over the gateway.

Type

bool

gateway_guild_members

Returns True if the application is verified and is allowed to receive guild members information over the gateway.

Type

bool

gateway_guild_members_limited

Returns True if the application is allowed to receive limited guild members information over the gateway.

Type

bool

verification_pending_guild_limit

Returns True if the application is currently pending verification and has hit the guild limit.

Type

bool

embedded

Returns True if the application is embedded within the Discord client.

Type

bool

gateway_message_content

Returns True if the application is verified and is allowed to read message content in guilds.

Type

bool

gateway_message_content_limited

Returns True if the application is unverified and is allowed to read message content in guilds.

Type

bool

embedded_first_party

Returns True if the embedded application is created by Discord.

Type

bool

application_command_migrated

Unknown.

Type

bool

app_commands_badge

Returns True if the application has registered a global application command. This shows up as a badge in the official client.

Type

bool

active

Returns True if the application has had at least one global application command used in the last 30 days.

New in version 2.1.

Type

bool

active_grace_period

Returns True if the application has not had any global application commands used in the last 30 days and has lost the active flag.

Type

bool

iframe_modal

Returns True if the application can use IFrames within modals.

Type

bool

social_layer_integration

Returns True if the application can use the social layer API.

Type

bool

promoted

Returns True if the application is promoted by Discord in the application directory.

Type

bool

partner

Returns True if the application is partnered with Discord.

Type

bool

class discord.AttachmentFlags(**kwargs)

Wraps up the Discord Attachment flags.

New in version 2.4.

x == y

Checks if two AttachmentFlags are equal.

x != y

Checks if two AttachmentFlags are not equal.

x | y, x |= y

Returns a AttachmentFlags instance with all enabled flags from both x and y.

x & y, x &= y

Returns a AttachmentFlags instance with only flags enabled on both x and y.

x ^ y, x ^= y

Returns a AttachmentFlags instance with only flags enabled on only one of x or y, not on both.

~x

Returns a AttachmentFlags instance with all flags inverted from x.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

value

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

Type

int

clip

Returns True if the attachment is a clip.

Type

bool

thumbnail

Returns True if the attachment is a thumbnail.

Type

bool

remix

Returns True if the attachment has been edited using the remix feature.

Type

bool

spoiler

Returns True if the attachment was marked as a spoiler.

New in version 2.5.

Type

bool

contains_explicit_media

Returns True if the attachment was flagged as sensitive content.

New in version 2.5.

Type

bool

animated

Returns True if the attachment is an animated image.

New in version 2.5.

Type

bool

class discord.AutoModPresets(**kwargs)

Wraps up the Discord AutoModRule presets.

New in version 2.0.

x == y

Checks if two AutoMod preset flags are equal.

x != y

Checks if two AutoMod preset flags are not equal.

x | y, x |= y

Returns an AutoModPresets instance with all enabled flags from both x and y.

New in version 2.0.

x & y, x &= y

Returns an AutoModPresets instance with only flags enabled on both x and y.

New in version 2.0.

x ^ y, x ^= y

Returns an AutoModPresets instance with only flags enabled on only one of x or y, not on both.

New in version 2.0.

~x

Returns an AutoModPresets instance with all flags inverted from x.

New in version 2.0.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

value

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

Type

int

profanity

Whether to use the preset profanity filter.

Type

bool

sexual_content

Whether to use the preset sexual content filter.

Type

bool

slurs

Whether to use the preset slurs filter.

Type

bool

class discord.ChannelFlags(**kwargs)

Wraps up the Discord GuildChannel or Thread flags.

x == y

Checks if two channel flags are equal.

x != y

Checks if two channel flags are not equal.

x | y, x |= y

Returns a ChannelFlags instance with all enabled flags from both x and y.

New in version 2.0.

x & y, x &= y

Returns a ChannelFlags instance with only flags enabled on both x and y.

New in version 2.0.

x ^ y, x ^= y

Returns a ChannelFlags instance with only flags enabled on only one of x or y, not on both.

New in version 2.0.

~x

Returns a ChannelFlags instance with all flags inverted from x.

New in version 2.0.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

New in version 2.0.

value

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

Type

int

guild_feed_removed

Returns True if the channel is hidden from the guild’s feed.

Type

bool

pinned

Returns True if the thread is pinned to the forum channel.

Type

bool

active_channels_removed

Returns True if the channel has been removed from the guild’s active channels.

Type

bool

require_tag

Returns True if a tag is required to be specified when creating a thread in a ForumChannel.

New in version 2.1.

Type

bool

spam

Returns True if the channel is marked as spammy.

Type

bool

guild_resource_channel

Returns True if the channel is used as a read-only resource for onboarding and is not shown in the channel list.

Type

bool

clyde_ai

Returns True if the channel is created by Clyde AI, which has full access to all message content.

Type

bool

scheduled_for_deletion

Returns True if the channel is scheduled for deletion and is not shown in the UI.

Type

bool

summaries_disabled

Returns True if the channel has summaries disabled.

Type

bool

role_subscription_template_preview_channel

Returns True if role subscription tier for this guild channel has not been published yet.

Type

bool

broadcasting

Returns True if the group is used for broadcasting a live stream.

Type

bool

hide_media_download_options

Returns True if the client hides embedded media download options in a ForumChannel. Only available in media channels.

New in version 2.4.

Type

bool

join_request_interview_channel

Returns True if the group is used for guild join request interviews.

Type

bool

obfuscated

Returns True if the user does not have permissions to view the channel.

Type

bool

is_moderator_report_channel

Returns True if the channel is a Mod Queue channel.

Type

bool

class discord.EmbedFlags(**kwargs)

Wraps up the Discord Embed flags.

New in version 2.5.

x == y

Checks if two EmbedFlags are equal.

x != y

Checks if two EmbedFlags are not equal.

x | y, x |= y

Returns an EmbedFlags instance with all enabled flags from both x and y.

x ^ y, x ^= y

Returns an EmbedFlags instance with only flags enabled on only one of x or y, not on both.

~x

Returns an EmbedFlags instance with all flags inverted from x.

hash(x)

Returns the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

value

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

Type

int

contains_explicit_media

Returns True if the embed was flagged as sensitive content.

Type

bool

content_inventory_entry

Returns True if the embed is a reply to an activity card, and is no longer displayed.

Type

bool

class discord.GiftFlags(**kwargs)

Wraps up the Discord Gift flags.

New in version 3.0.

x == y

Checks if two GiftFlags are equal.

x != y

Checks if two GiftFlags are not equal.

x | y, x |= y

Returns an GiftFlags instance with all enabled flags from both x and y.

x ^ y, x ^= y

Returns an GiftFlags instance with only flags enabled on only one of x or y, not on both.

~x

Returns an GiftFlags instance with all flags inverted from x.

hash(x)

Returns the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

value

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

Type

int

payment_source_required

Returns True if the gift requires a payment source to be redeemed.

Type

bool

existing_subscription_disallowed

Returns True if the gift cannot be redeemed by users with existing premium subscription.

Type

bool

not_self_redeemable

Returns True if the gift cannot be redeemed by the gifter.

Type

bool

promotion

Returns True if the gift is from a promotion.

Type

bool

class discord.Intents(value=0, **kwargs)

Wraps up a Discord Gateway intent flags.

Similar to Permissions, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

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

This is used to disable certain Gateway features that are unnecessary to run your client. To make use of this, it is passed to the intents keyword argument of Client.

New in version 1.5.

x == y

Checks if two flags are equal.

x != y

Checks if two flags are not equal.

x | y, x |= y

Returns an Intents instance with all enabled flags from both x and y.

New in version 2.0.

x & y, x &= y

Returns an Intents instance with only flags enabled on both x and y.

New in version 2.0.

x ^ y, x ^= y

Returns an Intents instance with only flags enabled on only one of x or y, not on both.

New in version 2.0.

~x

Returns an Intents instance with all flags inverted from x.

New in version 2.0.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any intent is enabled.

New in version 2.0.

value

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

Type

int

classmethod all()

A factory method that creates a Intents with everything available enabled.

classmethod none()

A factory method that creates a Intents instance with everything disabled.

classmethod default()

A factory method that creates a Intents instance with everything enabled except members, presences, and message_content.

classmethod sdk()

A factory method that creates a Intents instance with intents the official SDK enables.

The following intents are enabled by the SDK:

guilds

Whether guild related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

It is highly advisable to leave this intent enabled for your client to function.

Type

bool

members

Whether guild member related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

For more information go to the member intent documentation.

Note

Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification.

Type

bool

moderation

Whether guild moderation related events are enabled.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Warning

This intent is not usable by user accounts.

Type

bool

bans

An alias of moderation.

Changed in version 2.2: Changed to an alias.

Warning

This intent is not usable by user accounts.

Type

bool

emojis

Alias of expressions.

Changed in version 2.0: Changed to an alias.

Warning

This intent is not usable by user accounts.

Type

bool

emojis_and_stickers

Alias of expressions.

New in version 2.0.

Changed in version 2.5: Changed to an alias.

Warning

This intent is not usable by user accounts.

Type

bool

expressions

Whether guild emoji, sticker, and soundboard sound related events are enabled.

New in version 2.5.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Warning

This intent is not usable by user accounts.

Type

bool

integrations

Whether guild integration related events are enabled.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Warning

This intent is not usable by user accounts.

Type

bool

webhooks

Whether guild webhook related events are enabled.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Warning

This intent is not usable by user accounts.

Type

bool

invites

Whether guild invite related events are enabled.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Warning

This intent is not usable by user accounts.

Type

bool

voice_states

Whether guild voice state related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Note

This intent is required to connect to voice.

Type

bool

presences

Whether guild/user presence related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

For more information go to the presence intent documentation.

Type

bool

guild_presences

Whether guild presence related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

For more information go to the presence intent documentation.

Note

Currently, for bots this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification.

Type

bool

user_presences

Whether user presence related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

For more information go to the presence intent documentation.

Type

bool

messages

Whether guild and direct message related events are enabled.

This is a shortcut to set or get both guild_messages and dm_messages.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Note that due to an implicit relationship this also corresponds to the following events:

Warning

guild_messages intent is not usable by user accounts.

Type

bool

guild_messages

Whether guild message related events are enabled.

See also dm_messages for DMs or messages for both.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Note that due to an implicit relationship this also corresponds to the following events:

Warning

This intent is not usable by user accounts.

Type

bool

dm_messages

Whether direct message related events are enabled.

See also guild_messages for guilds or messages for both.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Note that due to an implicit relationship this also corresponds to the following events:

Type

bool

reactions

Whether guild and direct message reaction related events are enabled.

This is a shortcut to set or get both guild_reactions and dm_reactions.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Warning

This intent is not usable by user accounts.

Type

bool

guild_reactions

Whether guild message reaction related events are enabled.

See also dm_reactions for DMs or reactions for both.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Warning

This intent is not usable by user accounts.

Type

bool

dm_reactions

Whether direct message reaction related events are enabled.

See also guild_reactions for guilds or reactions for both.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Warning

This intent is not usable by user accounts.

Type

bool

typing

Whether guild and direct message typing related events are enabled.

This is a shortcut to set or get both guild_typing and dm_typing.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Warning

This intent is not usable by user accounts.

Type

bool

guild_typing

Whether guild and direct message typing related events are enabled.

See also dm_typing for DMs or typing for both.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Warning

This intent is not usable by user accounts.

Type

bool

dm_typing

Whether guild and direct message typing related events are enabled.

See also guild_typing for guilds or typing for both.

This corresponds to the following events:

This does not correspond to any attributes or classes in the library in terms of cache.

Warning

This intent is not usable by user accounts.

Type

bool

message_content

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

  • The message was sent by the client

  • The message was sent in direct messages

  • The message mentions the client

This applies to the following events:

For more information go to the message content intent documentation.

Note

Currently, for bots this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification.

New in version 2.0.

Warning

This intent is not usable by user accounts.

Type

bool

guild_scheduled_events

Whether guild scheduled event related events are enabled.

This corresponds to the following events:

New in version 2.0.

Warning

This intent is not usable by user accounts.

Type

bool

private_channels

Whether private channel related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

It is highly advisable to leave this intent enabled for your client to function.

Type

bool

calls

Whether call related events are enabled.

This corresponds to the following events:

Type

bool

auto_moderation

Whether auto moderation related events are enabled.

This is a shortcut to set or get both auto_moderation_configuration and auto_moderation_execution.

This corresponds to the following events:

New in version 2.0.

Warning

This intent is not usable by user accounts.

Type

bool

auto_moderation_configuration

Whether auto moderation configuration related events are enabled.

This corresponds to the following events:

New in version 2.0.

Warning

This intent is not usable by user accounts.

Type

bool

auto_moderation_execution

Whether auto moderation execution related events are enabled.

This corresponds to the following events: - on_automod_action()

New in version 2.0.

Warning

This intent is not usable by user accounts.

Type

bool

relationships

Whether relationship related events are enabled.

This corresponds to the following events:

This also corresponds to the following attributes and classes in terms of cache:

Type

bool

polls

Whether guild and direct messages poll related events are enabled.

This is a shortcut to set or get both guild_polls and dm_polls.

This corresponds to the following events:

New in version 2.4.

Warning

guild_polls and dm_polls intents are not usable by user accounts.

Type

bool

guild_polls

Whether guild poll related events are enabled.

See also dm_polls and polls.

This corresponds to the following events:

New in version 2.4.

Warning

This intent is not usable by user accounts.

Type

bool

dm_polls

Whether direct messages poll related events are enabled.

See also guild_polls and polls.

This corresponds to the following events:

New in version 2.4.

Warning

This intent is not usable by user accounts.

Type

bool

lobbies

Whether lobby related events are enabled.

This corresponds to the following events:

  • on_lobby_create()

  • on_lobby_update()

  • on_lobby_member_join()

  • on_lobby_member_update()

  • on_lobby_member_remove()

  • on_lobby_message()

  • on_lobby_message_update()

  • on_lobby_message_delete()

  • on_lobby_voice_state_update()

This also corresponds to the following attributes and classes in terms of cache:

Type

bool

lobby_delete

Whether lobby delete event is enabled.

This corresponds to the following events:

  • on_lobby_remove()

Type

bool

guild_names_only

Whether to include only Guild.name and Guild.id.

This affects the following events:

This also corresponds to the following attributes and classes in terms of cache:

It is highly advisable to leave this intent enabled for your client to properly function.

Type

bool

Attributes
class discord.LobbyMemberFlags(**kwargs)

Wraps up the Discord Lobby Member flags.

New in version 3.0.

x == y

Checks if two LobbyMemberFlags are equal.

x != y

Checks if two LobbyMemberFlags are not equal.

x | y, x |= y

Returns a LobbyMemberFlags instance with all enabled flags from both x and y.

x & y, x &= y

Returns a LobbyMemberFlags instance with only flags enabled on both x and y.

x ^ y, x ^= y

Returns a LobbyMemberFlags instance with only flags enabled on only one of x or y, not on both.

~x

Returns a LobbyMemberFlags instance with all flags inverted from x.

hash(x)

Returns the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

value

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

Type

int

Returns True if the member can link lobby to a channel..

Type

bool

Attributes
class discord.MediaScanFlags(**kwargs)

Wraps up the media scan flags.

New in version 3.0.

x == y

Checks if two MediaScanFlags are equal.

x != y

Checks if two MediaScanFlags are not equal.

x | y, x |= y

Returns a MediaScanFlags instance with all enabled flags from both x and y.

x & y, x &= y

Returns a MediaScanFlags instance with only flags enabled on both x and y.

x ^ y, x ^= y

Returns a MediaScanFlags instance with only flags enabled on only one of x or y, not on both.

~x

Returns a MediaScanFlags instance with all flags inverted from x.

hash(x)

Returns the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

value

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

Type

int

explicit

Returns True if the media contains explicit content.

Type

bool

gore

Returns True if the media has gore..

Type

bool

class discord.MemberCacheFlags(**kwargs)

Controls the library’s cache policy when it comes to members.

This allows for finer grained control over what members are cached. Note that the bot’s own member is always cached. This class is passed to the member_cache_flags parameter in Client.

Due to a quirk in how Discord works, in order to ensure proper cleanup of cache resources it is recommended to have Intents.members enabled. Otherwise the library cannot know when a member leaves a guild and is thus unable to cleanup after itself.

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

The default value is all flags enabled.

New in version 1.5.

x == y

Checks if two flags are equal.

x != y

Checks if two flags are not equal.

x | y, x |= y

Returns a MemberCacheFlags instance with all enabled flags from both x and y.

New in version 2.0.

x & y, x &= y

Returns a MemberCacheFlags instance with only flags enabled on both x and y.

New in version 2.0.

x ^ y, x ^= y

Returns a MemberCacheFlags instance with only flags enabled on only one of x or y, not on both.

New in version 2.0.

~x

Returns a MemberCacheFlags instance with all flags inverted from x.

New in version 2.0.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

New in version 2.0.

value

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

Type

int

classmethod all()

A factory method that creates a MemberCacheFlags with everything enabled.

classmethod none()

A factory method that creates a MemberCacheFlags with everything disabled.

voice

Whether to cache members that are in voice.

This requires Intents.voice_states.

Members that leave voice are no longer cached.

Type

bool

joined

Whether to cache members that joined the guild or are chunked as part of the initial log in flow.

This requires Intents.members.

Members that leave the guild are no longer cached.

Type

bool

classmethod from_intents(intents)

A factory method that creates a MemberCacheFlags based on the currently selected Intents.

Parameters

intents (Intents) – The intents to select from.

Returns

The resulting member cache flags.

Return type

MemberCacheFlags

class discord.MemberFlags(**kwargs)

Wraps up the Discord Guild Member flags.

New in version 2.2.

x == y

Checks if two MemberFlags are equal.

x != y

Checks if two MemberFlags are not equal.

x | y, x |= y

Returns a MemberFlags instance with all enabled flags from both x and y.

x & y, x &= y

Returns a MemberFlags instance with only flags enabled on both x and y.

x ^ y, x ^= y

Returns a MemberFlags instance with only flags enabled on only one of x or y, not on both.

~x

Returns a MemberFlags instance with all flags inverted from x.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

value

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

Type

int

did_rejoin

Returns True if the member left and rejoined the guild.

Type

bool

completed_onboarding

Returns True if the member has completed onboarding.

Type

bool

bypasses_verification

Returns True if the member can bypass the guild verification requirements.

Type

bool

started_onboarding

Returns True if the member has started onboarding.

Type

bool

guest

Returns True if the member is a guest and can only access the voice channel they were invited to.

New in version 2.5.

Type

bool

started_home_actions

Returns True if the member has started Server Guide new member actions.

New in version 2.5.

Type

bool

completed_home_actions

Returns True if the member has completed Server Guide new member actions.

New in version 2.5.

Type

bool

automod_quarantined_username

Returns True if the member’s username, nickname, or global name has been blocked by AutoMod.

New in version 2.5.

Type

bool

dm_settings_upsell_acknowledged

Returns True if the member has dismissed the DM settings upsell.

New in version 2.5.

Type

bool

automod_quarantined_clan_tag

Returns True if the member’s clan tag has been blocked by AutoMod.

Type

bool

class discord.MessageFlags(**kwargs)

Wraps up a Discord Message flag value.

See SystemChannelFlags.

x == y

Checks if two flags are equal.

x != y

Checks if two flags are not equal.

x | y, x |= y

Returns a MessageFlags instance with all enabled flags from both x and y.

New in version 2.0.

x & y, x &= y

Returns a MessageFlags instance with only flags enabled on both x and y.

New in version 2.0.

x ^ y, x ^= y

Returns a MessageFlags instance with only flags enabled on only one of x or y, not on both.

New in version 2.0.

~x

Returns a MessageFlags instance with all flags inverted from x.

New in version 2.0.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

New in version 2.0.

New in version 1.3.

value

The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.

Type

int

crossposted

Returns True if the message is the original crossposted message.

Type

bool

is_crossposted

Returns True if the message was crossposted from another channel.

Type

bool

suppress_embeds

Returns True if the message’s embeds have been suppressed.

Type

bool

source_message_deleted

Returns True if the source message for this crosspost has been deleted.

Type

bool

urgent

Returns True if the source message is an urgent message.

An urgent message is one sent by Discord Trust and Safety.

Type

bool

has_thread

Returns True if the source message is associated with a thread.

New in version 2.0.

Type

bool

ephemeral

Returns True if the source message is ephemeral.

New in version 2.0.

Type

bool

loading

Returns True if the message is an interaction response and the bot is “thinking”.

New in version 2.0.

Type

bool

failed_to_mention_some_roles_in_thread

Returns True if the message failed to mention some roles in a thread and add their members to the thread.

New in version 2.0.

Type

bool

guild_feed_hidden

Returns True if the message is hidden from the guild’s feed.

Type

bool

Returns True if the message contains a link that impersonates Discord.

Type

bool

suppress_notifications

Returns True if the message will not trigger push and desktop notifications.

New in version 2.2.

Type

bool

silent

Alias for suppress_notifications.

New in version 2.2.

Type

bool

voice

Returns True if the message is a voice message.

New in version 2.3.

Type

bool

forwarded

Returns True if the message is a forwarded message.

New in version 2.5.

Type

bool

has_components_v2

Whether the message contains v2 components.

Type

bool

sent_by_social_layer_integration

Whether the message is trigged by the social layer integration.

Type

bool

discord.OverlayMethodFlags
class discord.OverlayMethodFlags(**kwargs)

Wraps up the Discord Overlay method flags.

x == y

Checks if two OverlayMethodFlags are equal.

x != y

Checks if two OverlayMethodFlags are not equal.

x | y, x |= y

Returns a OverlayMethodFlags instance with all enabled flags from both x and y.

x & y, x &= y

Returns a OverlayMethodFlags instance with only flags enabled on both x and y.

x ^ y, x ^= y

Returns a OverlayMethodFlags instance with only flags enabled on only one of x or y, not on both.

~x

Returns a OverlayMethodFlags instance with all flags inverted from x.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

New in version 3.0.

value

The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.

Type

int

out_of_process

Returns True if the overlay can be rendered out of process.

Type

bool

class discord.PublicUserFlags(**kwargs)

Wraps up the Discord User Public flags.

x == y

Checks if two PublicUserFlags are equal.

x != y

Checks if two PublicUserFlags are not equal.

x | y, x |= y

Returns a PublicUserFlags instance with all enabled flags from both x and y.

New in version 2.0.

x & y, x &= y

Returns a PublicUserFlags instance with only flags enabled on both x and y.

New in version 2.0.

x ^ y, x ^= y

Returns a PublicUserFlags instance with only flags enabled on only one of x or y, not on both.

New in version 2.0.

~x

Returns a PublicUserFlags instance with all flags inverted from x.

New in version 2.0.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

New in version 2.0.

New in version 1.4.

value

The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.

Type

int

staff

Returns True if the user is a Discord Employee.

Type

bool

partner

Returns True if the user is a Discord Partner.

Type

bool

hypesquad

Returns True if the user is a HypeSquad Events member.

Type

bool

bug_hunter

Returns True if the user is a Discord Bug Hunter.

Type

bool

mfa_sms

Returns True if the user has SMS recovery for Multi Factor Authentication enabled..

Type

bool

premium_promo_dismissed

Returns True if the user has dismissed the Discord Nitro promotion.

Type

bool

hypesquad_bravery

Returns True if the user is a HypeSquad Bravery member.

Type

bool

hypesquad_brilliance

Returns True if the user is a HypeSquad Brilliance member.

Type

bool

hypesquad_balance

Returns True if the user is a HypeSquad Balance member.

Type

bool

early_supporter

Returns True if the user is an Early Supporter.

Type

bool

team_user

Returns True if the user is a Team User.

Type

bool

system

Returns True if the user is a system user (i.e. represents Discord officially).

Type

bool

has_unread_urgent_messages

Returns True if the user has an unread system message.

Type

bool

bug_hunter_level_2

Returns True if the user is a Bug Hunter Level 2

Type

bool

verified_bot

Returns True if the user is a Verified Bot.

Type

bool

verified_bot_developer

Returns True if the user is an Early Verified Bot Developer.

Type

bool

early_verified_bot_developer

An alias for verified_bot_developer.

New in version 1.5.

Type

bool

discord_certified_moderator

Returns True if the user is a Discord Certified Moderator.

New in version 2.0.

Type

bool

bot_http_interactions

Returns True if the user is a bot that only uses HTTP interactions and is shown in the online member list.

New in version 2.0.

Type

bool

spammer

Returns True if the user is flagged as a spammer by Discord.

New in version 2.0.

Type

bool

active_developer

Returns True if the user is an active developer.

New in version 2.1.

Type

bool

provisional_account

Returns True if the user is a provisional account.

New in version 3.0.

Type

bool

quarantined

Returns True if the user is quarautined.

New in version 3.0.

Type

bool

collaborator

Returns True if the user is a collaborator and considered staff.

New in version 3.0.

Type

bool

restricted_collaborator

Returns True if the user is a restricted collaborator and considered staff.

New in version 3.0.

Type

bool

all()

List[UserFlags]: Returns all public flags the user has.

class discord.RecipientFlags(**kwargs)

Wraps up the Discord DM channel recipient flags.

x == y

Checks if two RecipientFlags are equal.

x != y

Checks if two RecipientFlags are not equal.

x | y, x |= y

Returns a RecipientFlags instance with all enabled flags from both x and y.

x & y, x &= y

Returns a RecipientFlags instance with only flags enabled on both x and y.

x ^ y, x ^= y

Returns a RecipientFlags instance with only flags enabled on only one of x or y, not on both.

~x

Returns a RecipientFlags instance with all flags inverted from x.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

value

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

Type

int

dismissed_in_game_message_nux

Returns True if the user dismissed in_game_message_nux message.

Type

bool

dismissed_current_chat_wallpaper

Returns True if the user dismissed current chat wallpaper.

Type

bool

Attributes
class discord.RoleFlags(**kwargs)

Wraps up the Discord Role flags.

New in version 2.4.

x == y

Checks if two RoleFlags are equal.

x != y

Checks if two RoleFlags are not equal.

x | y, x |= y

Returns a RoleFlags instance with all enabled flags from both x and y.

x & y, x &= y

Returns a RoleFlags instance with only flags enabled on both x and y.

x ^ y, x ^= y

Returns a RoleFlags instance with only flags enabled on only one of x or y, not on both.

~x

Returns a RoleFlags instance with all flags inverted from x.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

value

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

Type

int

in_prompt

Returns True if the role can be selected by members in an onboarding prompt.

Type

bool

class discord.SKUFlags(**kwargs)

Wraps up the Discord SKU flags.

New in version 2.4.

x == y

Checks if two SKUFlags are equal.

x != y

Checks if two SKUFlags are not equal.

x | y, x |= y

Returns a SKUFlags instance with all enabled flags from both x and y.

x & y, x &= y

Returns a SKUFlags instance with only flags enabled on both x and y.

x ^ y, x ^= y

Returns a SKUFlags instance with only flags enabled on only one of x or y, not on both.

~x

Returns a SKUFlags instance with all flags inverted from x.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

value

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

Type

int

premium_purchase

Returns True if the SKU is a premium purchase.

Type

bool

has_free_premium_content

Returns True if the SKU has free premium content.

Type

bool

available

Returns True if the SKU is available for purchase.

Type

bool

premium_and_distribution

Returns True if the SKU is a premium and distribution product.

Type

bool

sticker_pack

Returns True if the SKU is a premium sticker pack.

Type

bool

guild_role_subscription

Returns True if the SKU is a guild role subscription. These are subscriptions made to guilds for premium perks.

Type

bool

premium_subscription

Returns True if the SKU is a Discord premium subscription or related first-party product. These are subscriptions like Nitro and Server Boosts. These are the only giftable subscriptions.

Type

bool

application_guild_subscription

Returns True if the SKU is a application subscription.

These are subscriptions made to applications for premium perks bound to a guild.

Type

bool

application_user_subscription

Returns True if the SKU is a application subscription.

These are subscriptions made to applications for premium perks bound to an user.

Type

bool

creator_monetization

Returns True if the SKU is a creator monetization product (e.g. guild role subscription, guild product).

Type

bool

guild_product

Returns True if the SKU is a guild product.

These are one-time purchases made by guilds for premium perks.

Type

bool

class discord.SystemChannelFlags(**kwargs)

Wraps up a Discord system channel flag value.

Similar to Permissions, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit the system flags easily.

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

x == y

Checks if two flags are equal.

x != y

Checks if two flags are not equal.

x | y, x |= y

Returns a SystemChannelFlags instance with all enabled flags from both x and y.

New in version 2.0.

x & y, x &= y

Returns a SystemChannelFlags instance with only flags enabled on both x and y.

New in version 2.0.

x ^ y, x ^= y

Returns a SystemChannelFlags instance with only flags enabled on only one of x or y, not on both.

New in version 2.0.

~x

Returns a SystemChannelFlags instance with all flags inverted from x.

New in version 2.0.

hash(x)

Return the flag’s hash.

iter(x)

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

bool(b)

Returns whether any flag is set to True.

New in version 2.0.

value

The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.

Type

int

join_notifications

Returns True if the system channel is used for member join notifications.

Type

bool

premium_subscriptions

Returns True if the system channel is used for “Nitro boosting” notifications.

Type

bool

guild_reminder_notifications

Returns True if the system channel is used for server setup helpful tips notifications.

New in version 2.0.

Type

bool

join_notification_replies

Returns True if sticker reply button (“Wave to say hi!”) is shown for member join notifications.

New in version 2.0.

Type

bool

role_subscription_purchase_notifications

Returns True if role subscription purchase and renewal notifications are enabled.

New in version 2.2.

Type

bool

role_subscription_purchase_notification_replies

Returns True if the role subscription notifications have a sticker reply button.

New in version 2.2.

Type

bool

Poll

class discord.Poll(question, duration, *, multiple=False, layout_type=<PollLayoutType.default: 1>)

Represents a message’s Poll.

New in version 2.4.

Parameters
  • question (Union[PollMedia, str]) – The poll’s displayed question. The text can be up to 300 characters.

  • duration (datetime.timedelta) – The duration of the poll. Duration must be in hours.

  • multiple (bool) – Whether users are allowed to select more than one answer. Defaults to False.

  • layout_type (PollLayoutType) – The layout type of the poll. Defaults to PollLayoutType.default.

duration

The duration of the poll.

Type

datetime.timedelta

multiple

Whether users are allowed to select more than one answer.

Type

bool

layout_type

The layout type of the poll.

Type

PollLayoutType

property question

Returns this poll’s question string.

Type

str

property answers

Returns a read-only copy of the answers.

Type

List[PollAnswer]

property victor_answer_id

The victor answer ID.

New in version 2.5.

Note

This will always be None for polls that have not yet finished.

Type

Optional[int]

property victor_answer

The victor answer.

New in version 2.5.

Note

This will always be None for polls that have not yet finished.

Type

Optional[PollAnswer]

property expires_at

A datetime object representing the poll expiry.

Note

This will always be None for stateless polls.

Type

Optional[datetime.datetime]

property created_at

Returns the poll’s creation time.

Note

This will always be None for stateless polls.

Type

Optional[datetime.datetime]

property message

The message this poll is from.

Type

Optional[Message]

property total_votes

Returns the sum of all the answer votes.

If the poll has not yet finished, this is an approximate vote count.

Changed in version 2.5: This now returns an exact vote count when updated from its poll results message.

Type

int

is_finalised()

bool: Returns whether the poll has finalised.

This always returns False for stateless polls.

is_finalized()

bool: Returns whether the poll has finalised.

This always returns False for stateless polls.

copy()

Returns a stateless copy of this poll.

This is meant to be used when you want to edit a stateful poll.

Returns

The copy of the poll.

Return type

Poll

add_answer(*, text, emoji=None)

Appends a new answer to this poll.

Parameters
  • text (str) – The text label for this poll answer. Can be up to 55 characters.

  • emoji (Union[PartialEmoji, Emoji, str]) – The emoji to display along the text.

Raises

ClientException – Cannot append answers to a poll that is active.

Returns

This poll with the new answer appended. This allows fluent-style chaining.

Return type

Poll

get_answer(id)

Returns the answer with the provided ID or None if not found.

Parameters

id (int) – The ID of the answer to get.

Returns

The answer.

Return type

Optional[PollAnswer]

PollMedia

Attributes
class discord.PollMedia(text, emoji=None)

Represents the poll media for a poll item.

New in version 2.4.

text

The displayed text.

Type

str

emoji

The attached emoji for this media. This is only valid for poll answers.

Type

Optional[Union[PartialEmoji, Emoji]]

Option

class discord.Option(name, *, type, name_localizations=None, description, description_localizations=None, required=True, choices=None, channel_types=None, min_value=None, max_value=None, min_length=None, max_length=None, autocomplete=False)

Represents an application command option.

New in version 3.0.

type

The type of option.

Type

AppCommandOptionType

name

The name of the option.

Type

str

name_localized

The localized name of the option.

Type

Optional[str]

name_localizations

The localized names of the option. Used for display purposes.

Type

Dict[Locale, str]

description

The description of the option.

Type

str

description_localized

The localized description of the option.

Type

Optional[str]

description_localizations

The localized descriptions of the option. Used for display purposes.

Type

Dict[Locale, str]

required

Whether the option is required.

Type

bool

choices

A list of choices for the command to choose from for this option.

Type

List[Choice]

parent

The parent application command that has this option.

Type

Union[SlashCommand, SlashCommandGroup]

channel_types

The channel types that are allowed for this option.

Type

List[ChannelType]

min_value

The minimum supported value for this option.

Type

Optional[Union[int, float]]

max_value

The maximum supported value for this option.

Type

Optional[Union[int, float]]

min_length

The minimum allowed length for this option.

Type

Optional[int]

max_length

The maximum allowed length for this option.

Type

Optional[int]

autocomplete

Whether the option has autocomplete.

Type

bool

SlashCommandGroup

class discord.SlashCommandGroup(name, *, type=<AppCommandOptionType.subcommand_group: 2>, description='', options=None, name_localizations=None, description_localizations=None)

Represents an application command subcommand.

New in version 3.0.

type

The type of subcommand.

Type

AppCommandOptionType

name

The name of the subcommand.

Type

str

description

The description of the subcommand.

Type

str

name_localizations

The localised names of the subcommand. Used for display purposes.

Type

Dict[Locale, str]

description_localizations

The localised descriptions of the subcommand. Used for display purposes.

Type

Dict[Locale, str]

options

A list of options.

Type

List[Union[Option, SlashCommandGroup]]

property qualified_name

Returns the fully qualified command name.

The qualified name includes the parent name as well. For example, in a command like /foo bar the qualified name is foo bar.

Type

str

property mention

Returns a string that allows you to mention the given SlashCommandGroup.

Type

str

property parent

The parent application command.

Type

Union[SlashCommand, SlashCommandGroup]

Exceptions

The following exceptions are thrown by the library.

exception discord.DiscordException

Base exception class for discord.py

Ideally speaking, this could be caught to handle any exceptions raised from this library.

exception discord.ClientException

Exception that’s raised when an operation in the Client fails.

These are usually for exceptions that happened due to user input.

exception discord.LoginFailure

Exception that’s raised when the Client.login() function fails to log you in from improper credentials or some other misc. failure.

exception discord.HTTPException(response, message)

Exception that’s raised when an HTTP request operation fails.

response

The response of the failed HTTP request. This is an instance of aiohttp.ClientResponse. In some cases this could also be a requests.Response.

Type

aiohttp.ClientResponse

text

The text of the error. Could be an empty string.

Type

str

status

The status code of the HTTP request.

Type

int

code

The Discord specific error code for the failure.

Type

int

error_code

The OAuth2-specific error codes. Could be an empty string.

Type

str

exception discord.RateLimited(retry_after)

Exception that’s raised for when status code 429 occurs and the timeout is greater than the configured maximum using the max_ratelimit_timeout parameter in Client.

This is not raised during global ratelimits.

Since sometimes requests are halted pre-emptively before they’re even made, this does not subclass HTTPException.

New in version 2.0.

retry_after

The amount of seconds that the client should wait before retrying the request.

Type

float

exception discord.Forbidden(response, message)

Exception that’s raised for when status code 403 occurs.

Subclass of HTTPException

exception discord.NotFound(response, message)

Exception that’s raised for when status code 404 occurs.

Subclass of HTTPException

exception discord.DiscordServerError(response, message)

Exception that’s raised for when a 500 range status code occurs.

Subclass of HTTPException.

New in version 1.5.

exception discord.InvalidData

Exception that’s raised when the library encounters unknown or invalid data from Discord.

exception discord.GatewayNotFound

An exception that is raised when the gateway for Discord could not be found

exception discord.ConnectionClosed(socket, *, code=None)

Exception that’s raised when the gateway connection is closed for reasons that could not be handled internally.

code

The close code of the websocket.

Type

int

reason

The reason provided for the closure.

Type

str

exception discord.MissingApplicationID(message=None)

An exception raised when the client does not have an application ID set.

An application ID is required for syncing application commands and various other application tasks such as SKUs or application emojis.

This inherits from AppCommandError and ClientException.

New in version 2.0.

Changed in version 2.5: This is now exported to the discord namespace and now inherits from ClientException.

exception discord.opus.OpusError(code)

An exception that is thrown for libopus related errors.

code

The error code returned.

Type

int

exception discord.opus.OpusNotLoaded

An exception that is thrown for when libopus is not loaded.

Exception Hierarchy