OAuth2 API Reference

The following section outlines the OAuth2 API of discord4py

OAuth2 Client

class discord.oauth2.OAuth2Client

Bases: object

A class for interacting with the Discord OAuth2 API.

Parameters:
  • client_id (int) – The client ID of your application.

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

  • access_token_store (AccessTokenStore) – The access token store to use to store and update and load the access_tokens. Must be a subclass of AccessTokenStore

  • auto_refresh (bool) – Whether to automatically refresh access tokens when AccessTokenExpired is raised.

  • log_level (Optional[int]) – The log level to use for the internal logger.

  • loop (Optional[asyncio.AbstractEventLoop]) – The event loop to use for the internal HTTP client. Only required if you are using a custom event loop.

client_id

The client ID of your application.

Type:

int

access_token_store

The access token store to use to store and update and load the access_tokens. Must be a subclass of AccessTokenStore

Type:

AccessTokenStore

auto_refresh

Whether to automatically refresh access tokens when AccessTokenExpired is raised.

Type:

bool

loop

The event loop that the client is running on.

Type:

asyncio.AbstractEventLoop

setup_logging(*, log_handler=MISSING, log_formatter=MISSING, log_level=MISSING, root_logger=False)

Sets up the :mod:`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.

Note

This will only return the logger when called the first time on this instance. Subsequent calls will return None.

So if you want to get the logger, you should call this method yourself before starting the client.

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

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

  • 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 the value of log_level in the init or logging.INFO.

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

Returns:

The logger that was set up. This is the library logger if root_logger

Return type:

Optional[logging.Logger]

await start()

This function is a coroutine.

Starts the client. This will start the internal HTTP client and call the on_startup event.

Important

This must be called before any other requests are made.

await authorize(code, redirect_uri)

This function is a coroutine.

Retrieves a users access token by doing a post-request with the authorization code to https://discord.com/api/oauth2/token

Parameters:
  • code (str) – The access code from https://discord.com/oauth2/authorize

  • redirect_uri (str) – The redirect_uri associated with this authorization, usually from your authorization URL

Raises:
Returns:

The access token for the user

Return type:

AccessToken

await refresh_access_token(access_token, /)

This function is a coroutine.

Refreshes an access token using its refresh_token and returns the updated instance.

Parameters:

access_token (AccessToken) – The access_token to refresh

Raises:

InvalidRefreshToken – The refresh token is invalid or has expired

Returns:

The refreshed token

Return type:

AccessToken

await revoke_access_token(access_token, /)

This function is a coroutine.

Revokes an access token. It will no longer be usable.

Parameters:

access_token (AccessToken) – The access token to revoke

Raises:

HTTPException – Revoking the access token failed

await fetch_access_token_info(access_token, /, *, raw=False)

This function is a coroutine.

Fetches info about the current authorization.

Parameters:
  • access_token (AccessToken) – The access token to fetch info for

  • raw (bool) – Whether to return the raw data or not

Raises:

AccessTokenExpired – The access token is expired (this might be handled automatically when auto_refresh is True)

Returns:

  • AccessTokenInfo – The info about the current authorization

  • dict – The raw data if raw is True

await fetch_user(access_token, /, *, raw=False)

This function is a coroutine.

Fetches the user associated with the access token. Requires the IDENTIFY scope.

Parameters:
  • access_token (AccessToken) – The access token to fetch the user for

  • raw (bool) – Whether to return the raw data, defaults to False

Returns:

  • User – The user associated with the access token

  • dict – The raw data if raw is True

await fetch_guilds(access_token, /, *, raw=False)

This function is a coroutine.

Fetches the guilds the current user is a member of. Requires the GUILDS scope.

Parameters:
  • access_token (AccessToken) – The access token to fetch the guilds for

  • raw (bool) – Whether to return the raw data, defaults to False

Returns:

  • List[PartialGuild] – The guilds the current user is a member of

  • List[dict] – The raw data if raw is True

await fetch_guild_member(access_token, guild_id, *, raw=False)

This function is a coroutine.

Fetches the guild member of the current user in the guild. Requires the READ_GUILD_MEMBERS scope.

Parameters:
  • access_token (AccessToken) – The access token to fetch the guild member for

  • guild_id (SupportsStr) – The ID of the guild to fetch the guild member for

  • raw (bool) – Whether to return the raw data, defaults to False

Raises:

AccessTokenExpired – The access token is expired (this might be handled automatically when auto_refresh is True)

Returns:

  • GuildMember – The guild member of the current user in the guild

  • dict – The raw data if raw is True

await add_guild_member(access_token, /, *, bot_token, guild_id, user_id, nick=MISSING, roles=MISSING, mute=MISSING, deaf=MISSING, raw=False)

Adds a user to a guild using their access token.

Note

This requires the access_token to be authorized with the JOIN_GUILDS scope. Furthermore, the bot must be a member of the guild with the create_instant_invite permissions.

Warning

You should always ask for the user’s consent before adding them to a guild.

The nick, roles, mute and deaf parameters are optional and requires different permission for the bot.

Parameter

Required Permissions

nick

manage_nicknames

roles

manage_roles

mute

mute_members

deaf

deafen_members

Parameters:
  • access_token (AccessToken) – The access token for the user to add to the guild.

  • bot_token (SupportsStr) – The bot token for the bot. This is required for authorization.

  • guild_id (SupportsStr) – The ID of the guild to add the user to.

  • user_id (SupportsStr) – The ID of the user to add to the guild. If you don’t store the user ID already you can get it using fetch_user().

  • nick (str) – The nickname to give the user. Defaults to None.

  • roles (List[SupportsStr]) –

    A list of role IDs for roles to give the member on join. Defaults to None.

    Important

    For guilds with membership screening enabled, assigning a role using the roles parameter will add the user to the guild as a full member (pending will be False).

    A member with a role will bypass membership screening, onboarding and the guild’s verification level, and get immediate access to chat. Therefore, instead of assigning a role when the member joins, it is recommended to grant roles only after the user completes screening.

  • mute (bool) – Whether to mute the user on join. Defaults to False.

  • deaf (bool) – Whether to deafen the user on join. Defaults to False.

  • raw (bool) – Whether to return the raw data. Defaults to False.

Raises:
  • AccessTokenExpired – The access token is expired (this might be handled automatically when auto_refresh is True)

  • Forbidden – The bot does not have the create_instant_invite permission.

  • UserIsAtGuildLimit – The user cannot be added to the guild because they reached the guild limit of 100 (200 with nitro).

  • HTTPException – Adding the user to the guild failed.

Returns:

  • GuildMember – The guild member of the current user in the guild.

  • dict – The raw data if raw is True.

await fetch_connections(access_token, /, *, raw=False)

This function is a coroutine.

Fetches the connections of the current user. Requires the CONNECTIONS scope.

Parameters:
  • access_token (AccessToken) – The access token to fetch the connections for

  • raw (bool) – Whether to return the raw data, defaults to False

Raises:

AccessTokenExpired – The access token is expired (this might be handled automatically when auto_refresh is True)

Returns:

  • List[Connection] – The connections of the current user

  • dict – The raw data if raw is True

await fetch_user_app_role_connection(access_token, /, *, raw=False)

This function is a coroutine.

Fetches the role connection of the current user if any. Requires the WRITE_ROLE_CONNECTIONS scope.

Parameters:
  • access_token (AccessToken) – The access token to fetch the role connection for

  • raw (bool) – Whether to return the raw data, defaults to False

Raises:

AccessTokenExpired – The access token is expired (this might be handled automatically when auto_refresh is True)

Returns:

  • RoleConnection – The role connection of the current user

  • dict – The raw data if raw is True

await update_user_app_role_connection(access_token, /, *, platform_name=MISSING, platform_username=MISSING, metadata=MISSING, application_id=None, raw=False)

This function is a coroutine.

Updates the role connection of the current user. Requires the WRITE_ROLE_CONNECTIONS scope.

All parameters are optional and will only be updated if provided.

Parameters:
  • access_token (AccessToken) – The access token to update the role connection for

  • platform_name (str) – The vanity name of the platform a bot has connected (max 50 characters)

  • platform_username (str) – The username on the platform a bot has connected (max 100 characters)

  • metadata (Dict[str, str]) –

    The metadata of the role connection.

    Mapping of AppRoleConnectionMetadata.key s to their string-ified value (max 100 characters)

  • application_id (int) –

    The ID of the application to update the role connection for.

    Only required if the application id is not the same as the client id (e.g. for some older applications)

  • raw (bool) – Whether to return the raw data, defaults to False

Returns:

  • RoleConnection – The updated role connection of the current user

  • dict – The raw data if raw is True

await fetch_all_application_command_permissions(access_token, /, *, guild_id, application_id=None, raw=False)

This function is a coroutine.

Fetches all application command permissions for the given guild.

Parameters:
  • access_token (AccessToken) – An access token of a user that is a member of the guild to fetch the application-command permissions for.

  • guild_id (Union[int, str]) – The ID of the guild to fetch the application-command permissions for.

  • application_id (Optional[Union[int, str]]) –

    The ID of the application to fetch the permissions for. If not provided, defaults to the client’s application ID.

    Note

    This is only required if the application ID is not the same as the client ID (e.g. for some older applications).

  • raw (bool) – Whether to return the raw data, defaults to False

Raises:
Returns:

  • List[GuildApplicationCommandPermissions] – A list of all application command permissions for the given guild.

  • List[dict] – The raw data if raw is True.

await fetch_application_command_permissions(access_token, /, *, guild_id, command_id, application_id=None, raw=False)

This function is a coroutine.

Fetches the permission overwrites for an application-command in a guild.

Parameters:
  • access_token (AccessToken) – An access token of a user that is a member of the guild to fetch the application-commands permissions for.

  • guild_id (Union[int, str]) – The ID of the guild to fetch the application-command permissions for.

  • command_id (Union[int, str]) – The ID of the application-command to fetch the permissions for.

  • application_id (Optional[Union[int, str]]) –

    The ID of the application to fetch the permissions for. If not provided, defaults to the client’s application ID.

    Note

    This is only required if the application ID is not the same as the client ID (e.g. for some older applications).

  • raw (bool) – Whether to return the raw data, defaults to False

Raises:
  • AccessTokenExpired – The access token is expired (this might be handled automatically when auto_refresh is True)

  • Forbidden – The application does not have the permission to fetch the permissions.

  • NotFound – The application-command or the guild was not found.

Returns:

  • GuildApplicationCommandPermissions – The permission overwrites for the application-command in the guild.

  • dict – The raw data if raw is ``True

await edit_application_command_permissions(access_token, /, *, guild_id, command_id, permissions, application_id=None, raw=False)

This function is a coroutine.

Edits the permission overwrites for an application-command in a guild. Requires the UPDATE_APPLICATIONS_COMMANDS_PERMISSIONS scope.

Warning

This method will overwrite all existing permissions for the application-command. So if you want to keep the existing permissions, you need to include the existing ones in permissions.

Note

The access_token must be of a user that is a member of the guild and the following permissions are required:

  • Permissions.manage_guild

  • Permissions.manage_roles

  • Has the ability to run the application-command

  • Has the permissions to manage the resources that will be affected (roles, users, and/or channels depending on the ApplicationCommandPermissions.type)

Parameters:
  • access_token (AccessToken) – An access token of a user that is a member of the guild to edit the application-command permissions for.

  • guild_id (Union[int, str]) – The ID of the guild to edit the application-command permissions for.

  • command_id (Union[int, str]) – The ID of the application-command to edit the permissions for.

  • permissions (List[ApplicationCommandPermissions]) – The new permissions for the application-command.

  • application_id (Optional[Union[int, str]]) –

    The ID of the application to edit the permissions for. If not provided, defaults to the client’s application ID.

    Note

    This is only required if the application ID is not the same as the client ID (e.g. for some older applications).

  • raw (bool) – Whether to return the raw data, defaults to False

Raises:
  • AccessTokenExpired – The access token is expired (this might be handled automatically when auto_refresh is True)

  • .Forbidden – The application does not have the permission to edit the permissions.

  • NotFound – The application-command or the guild was not found.

Returns:

  • GuildApplicationCommandPermissions – The permission overwrites for the application-command in the guild.

  • dict – The raw data if raw is ``True

Examples

Editing the permissions for an application-command in a guild:

There is a command called “test” and now you want to ensure the following for the guild with the ID 852871920411475968:

  • @everyone should not be able to use the command

  • Every member with the role “Member” (ID: 852937257903456256) can use the command

  • The command should only be usable in the channel “commands” (ID: 853000092156035083)

import discord.oauth2 as oauth2

from discord import (
    AppCommandPermission
    AppCommandPermissionType
)

# Assuming you have a OAuth2Client instance and a command called "test" with the ID 919316347165495356

GUILD_ID = 852871920411475968
MEMBER_ROLE_ID = 852937257903456256
COMMAND_CHANNEL_ID = 853000092156035083
COMMAND_ID = 919316347165495356

permissions = [
    AppCommandPermission(
        type=AppCommandPermissionType.ROLE,
        id=GUILD_ID,  # Special constant for all members in the guild
        permission=False
    ),  # Deny permission for @everyone
    AppCommandPermission(
        type=AppCommandPermissionType.ROLE,
        id=MEMBER_ROLE_ID,
        permission=True
    ), # Allow permission for members with the "Member" role
    AppCommandPermission(
        type=AppCommandPermissionType.CHANNEL,
        id=GUILD_ID - 1,  # Special constant for "all channels"
        permission=False
    )  # Deny permission for all channels
    AppCommandPermission(
        type=AppCommandPermissionType.CHANNEL,
        id=COMMAND_CHANNEL_ID,
        permission=True
    )  # Allow permission for the "commands" channel
]

await client.edit_application_command_permissions(
    access_token,
    guild_id=guild_id,
    command_id=COMMAND_ID,
    permissions=permissions
)

Access Token Store

class discord.oauth2.AccessTokenStore

Bases: object

Base class for an access token store.

oauth2_client

The client that this store is associated with.

Type:

OAuth2Client

await on_startup()

This function is a coroutine.

This is called by the OAuth2Client when it is starting up.

This can be used to initialise a database connection or similar.

By default, this calls load_access_tokens().

await on_close()

This function is a coroutine.

This is called by the OAuth2Client when it is closing.

This can be used to close a database connection or similar.

By default, this calls store_access_tokens().

await store_access_token(access_token)

This function is a coroutine.

This is called by the OAuth2Client when a new access token is created using OAuth2Client.authorize().

It can be used to store the access token to a database or similar.

Parameters:

access_token (AccessToken) – The access token that was created.

await store_refreshed_access_token(old_access_token, new_access_token)

This function is a coroutine.

This is called by the OAuth2Client when an access token is refreshed using OAuth2Client.refresh_access_token().

It can be used to update the database entry for the access token with the new data.

Parameters:
  • old_access_token (AccessToken) – The old access token that was refreshed.

  • new_access_token (AccessToken) – The new access token that was refreshed.

await store_access_tokens()

This function is a coroutine.

This can be used to store access tokens to a database or similar.

Note

By default this is called by on_close().

await load_access_token(*args, **kwargs)

This function is a coroutine.

This can be used to load an access token from a database or similar.

await load_access_tokens()

This function is a coroutine.

This can be used to load access tokens from a database or similar.

Note

By default this is called by on_startup().

await remove_revoked_access_token(access_token)

This function is a coroutine.

This is called by the OAuth2Client when an access token is revoked using OAuth2Client.revoke_access_token().

It can be used to remove the access token from the database or similar.

Parameters:

access_token (AccessToken) – The access token that was revoked.

Models

Access Token

class discord.oauth2.AccessToken

Bases: object

A representation of a access token response from discord.

This can be also used to store additional data that can be accessed through getitem.

additional_data

Additional data that was stored in the access token.

Type:

dict

x == y

Checks if two access tokens are equal.

x != y

Checks if two access tokens are not equal.

str(x)

Returns the access_token Be careful where you use this!

x[key]

Returns the additional data stored in the access token.

x[key] = value

Sets the additional data stored in the access token.

del x[key]

Deletes the additional data stored in the access token.

key in x

Checks if the given key is stored in the additional data.

iter(x)

Returns an iterator over the additional data.

len(x)

Returns the amount of additional data stored in the access token.

A representation of a access token response from discord.

This can be also used to store additional data that can be accessed through get item.

Parameters:
  • client (OAuth2Client) – The client that created this access token

  • access_token (str) – The actual access token - this will also be returned when calling str(some_access_token)

  • expires_at (Union[int, str, datetime]) –

    When the access token will expire and needs to be refreshed. In order to make it compatible with most of the database drivers it allows the following types

    • integers/floats (POSIX timestamp)

    • strings (timestamps in any ISO 8601 format)

    • datetime objects for the drivers that already convert it to a datetime object

  • refresh_token (Optional[str]) – The token that is required to request a new access token when the previous one expires. This might be None depending on the grant type used

  • scopes (Iterable[str]) – A list of scopes the access token is authorized to

  • **additional_data – Additional data that should be stored as key=value pairs

property client

The OAuth2Client that manages this access token.

property access_token

The actual bearer access token.

Note

Note that this might be expired, and you need to refresh the token first. Use is_expired() to check if it is expired.

property expires_at

Wen the access token will expire

Type:

datetime

property refresh_token

The refresh token that is required to refresh the access token when it is expired

Type:

str

scopes

A set of OAuth2Scope that the access token is authorized to.

webhook

The webhook that was created with the webhook when the access token was authorized with the CREATE_WEBHOOK scope. Only available on the original access token instance

Type:

Webhook

property refreshable

Whether the access token is refreshable. This checks if the refresh_token is set

Type:

bool

is_expired()

bool: Whether the access token is expired. This just checks if the expires_at is in the past

classmethod from_raw_data(client, data)

Creates an AccessToken from raw data returned by discord.

Parameters:
  • client (OAuth2Client) – The client that created this access token

  • data (AccessToken) – The raw data returned by discord

Returns:

The access token object

Return type:

AccessToken

to_dict()

Converts the access token data to a dictionary.

Structure of the dictionary:

{
    'access_token': str,
    'token_type': 'Bearer',
    'expires_at': str,
    'scopes': List[str],
    'refresh_token': NotRequired[str]
    'webhook_url': NotRequired[str]
}

Example

{
    "access_token": "6qrZcUqja7812RVdnEKjpzOL4CvHBFG",
    "token_type": "Bearer",
    "expires_at": "2018-06-10T21:20:00+00:00",
    "scopes": ["identify", "guilds"],
    "refresh_token": "D43f5y0ahjqew82jZ4NViEr2YafMKhue"  # only available when refresh_token is set
    "webhook_url": "https://discord.com/api/v10/webhooks/12345678910/T0kEn0fw3Bh00K"  # only available when webhook is set
}
Returns:

The access token data as a dictionary

Return type:

Dict[str, Any]

await refresh(*, force=False)

This function is a coroutine.

Refreshes the access token when possible and returns the new one. If the token is still valid it will instantly return it unless force is set. This also updates the expires_at and refresh_token.

Note

This is only available when client and refresh_token is set

Parameters:

force (bool) – Whether to force-refresh the access token, even when is_expired() returns False

Raises:
Returns:

The new access token

Return type:

str

await revoke()

This function is a coroutine.

Revokes the access token.

For more details, see OAuth2Client.revoke_access_token().

await fetch_info(*, raw=False)

This function is a coroutine.

Fetches the authorization information for the access token.

Fpr details, see OAuth2Client.fetch_access_token_info().

await fetch_user(*, raw=False)

This function is a coroutine.

Fetches the user associated with the access token.

For details, see OAuth2Client.fetch_user().

await fetch_guilds(*, raw=False)

This function is a coroutine.

Fetches the guilds associated with the access token.

For details, see OAuth2Client.fetch_guilds().

await fetch_guild_member(guild_id, /, *, raw=False)

This function is a coroutine.

Fetches the guild member of the current user in the guild. Requires the OAuth2Scope.READ_GUILD_MEMBERS scope.

For details, see OAuth2Client.fetch_guild_member().

await add_guild_member(*, bot_token, guild_id, user_id, nick=MISSING, roles=MISSING, mute=MISSING, deaf=MISSING, raw=False)

This function is a coroutine.

Adds a user to a guild using their access token.

For details, see OAuth2Client.add_guild_member().

await fetch_connections(*, raw=False)

This function is a coroutine.

Fetches the connections associated with the access token.

For details, see OAuth2Client.fetch_connections().

await fetch_user_app_role_connection(*, raw=False)

This function is a coroutine.

Fetches the application role connection associated with the access token.

For details, see OAuth2Client.fetch_user_app_role_connection().

await update_user_app_role_connection(*, platform_name=MISSING, platform_username=MISSING, metadata=MISSING, application_id=None, raw=False)

This function is a coroutine.

Updates the application role connection associated with the access token.

For details, see OAuth2Client.update_user_app_role_connection().

Access Token Info

class discord.oauth2.AccessTokenInfo

Bases: object

Represents the authorization information for an access token.

property application

The application the access token is authorized for.

Type:

PartialAppInfo

property scopes

A list of scopes the access token is authorized to.

Type:

Set[OAuth2Scope]

property expires_at

The time when the access token expires.

Type:

datetime

property user

The user associated with the access token.

Type:

PartialUser

class discord.oauth2.PartialAppInfo

Bases: object

Represents the application info for the bot provided by Discord.

id

The application ID.

Type:

int

name

The application name.

Type:

str

icon

The icon hash, if it exists.

Type:

Optional[str]

description

The application description.

Type:

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

verify_key

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

Type:

str

property icon_url

Retrieves the application’s icon asset.

This is equivalent to calling icon_url_as() with the default parameters (‘webp’ format and a size of 1024).

Type:

Asset

icon_url_as(*, format='webp', size=1024)

Returns an Asset for the icon the application has.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’ or ‘png’. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (str) – The format to attempt to convert the icon to. Defaults to ‘webp’.

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or invalid size.

Returns:

The resulting CDN asset.

Return type:

Asset

Connection

class discord.oauth2.Connection

Bases: object

Represents a connection of a user to a service.

str(x)

Returns the connection’s name.

id

The connection id.

Type:

str

name

The connection’s name.

Type:

str

type

The connection’s type.

Type:

str

revoked

Indicates if the connection is revoked.

Type:

bool

verified

Indicates if the connection is verified.

Type:

bool

friend_sync

Indicates if the connection is syncing friends.

Type:

bool

show_activity

Indicates if the connection is showing activity.

Type:

bool

visibility

The visibility of the connection.

Type:

int

property integrations

A list of partial guild integrations for the connection.

Type:

List[Integration]

get_platform_user_url()

Optional[str]: Returns the platform user url for the connection if available.

Role Connection

class discord.oauth2.RoleConnection

Bases: object

Partial Guild

class discord.oauth2.PartialGuild

Bases: Hashable

Represents a partial guild returned by the OAuth2 API.

x == y

Checks if two partial guilds are equal.

x != y

Checks if two partial guilds are not equal.

hash(x)

Returns the partial guild’s hash.

str(x)
Returns the partial guild's name.
id

The guild’s ID.

Type:

int

name

The guild’s name.

Type:

str

features

The guild’s features.

Type:

List[str]

icon

The guild’s icon hash.

Type:

Optional[str]

owner

Indicates if the user is the owner of the guild.

Type:

Optional[bool]

permissions

The permissions the user has in the guild.

Type:

Optional[Permissions]

property icon_url

Returns the guild’s icon asset.

Type:

Asset

is_icon_animated()

bool: Returns True if the guild has an animated icon.

icon_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the guild’s icon.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the icon to. If the format is None, then it is automatically detected into either ‘gif’ or static_format depending on the icon being animated or not.

  • static_format (Optional[str]) – Format to attempt to convert only non-animated icons to.

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or invalid size.

Returns:

The resulting CDN asset.

Return type:

Asset

Guild Member

class discord.oauth2.GuildMember(*, client, data)

Bases: _BaseUser

Represents a member of a guild.

x == y

Checks if two members are equal.

x != y

Checks if two members are not equal.

hash(x)

Returns the member’s hash.

str(x)

Returns the member’s name with discriminator.

id

The member’s ID.

Type:

int

joined_at

When the member joined the guild.

Type:

datetime.datetime

deaf

Indicates if the member is deafened.

Type:

bool

mute

Indicates if the member is muted.

Type:

bool

pending

Indicates if the member is pending verification.

Type:

bool

nick

The member’s nickname. Could be None.

Type:

Optional[str]

guild_avatar

The member’s guild-specific avatar hash. Could be None.

Type:

Optional[str]

premium_since

When the member started boosting the guild.

Type:

Optional[datetime.datetime]

role_ids

A list of role ids for roles the member has.

Type:

SnowflakeList

property name

Equivalent to User.name

property created_at

Equivalent to User.created_at

property default_avatar

Equivalent to User.default_avatar

property public_flags

Equivalent to User.public_flags

property flags

Guild specific flags for the member.

Type:

GuildMemberFlags

property mention

Returns a string that allows you to mention the member in discord.

Type:

str

property display_name

Returns the user’s display name.

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

Type:

str

property communication_disabled_until

The time until the member is timeouted, if any

Type:

Optional[datetime.datetime]

property guild_avatar_url

Returns the guild-specific banner asset for the member if any.

Type:

Optional[Asset]

guild_avatar_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the guild-specific avatar of the member if any, else None.

The format must be one of ‘webp’, ‘jpeg’, or ‘png’. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (str) – The format to attempt to convert the avatar to.

  • static_format (Optional[str]) – Format to attempt to convert only non-animated avatars to.

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or invalid size.

Returns:

The resulting CDN asset if any.

Return type:

Optional[Asset]

is_guild_avatar_animated()

bool: Indicates if the member has an animated guild-avatar.

property display_avatar_url

Returns the guild-specific avatar asset for the member if he has one, else the default avatar asset

Type:

Asset

display_avatar_url_as(format=None, static_format='webp', size=1024)

Same behaviour as avatar_url_as() and guild_avatar_url_as() but it prefers the guild-specific avatar

Returns:

The resulting CDN asset for the avatar

Return type:

Asset

property avatar_url

Equivalent to User.avatar_url

avatar_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the avatar to. If the format is None, then it is automatically detected into either ‘gif’ or static_format depending on the avatar being animated or not.

  • static_format (Optional[str]) – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or static_format, or invalid size.

Returns:

The resulting CDN asset.

Return type:

Asset

property default_avatar_url

Equivalent to User.default_avatar_url

is_avatar_animated()

bool: Indicates if the user has an animated avatar.

property is_migrated

Equivalent to User.is_migrated

Partial Guild Integration

class discord.oauth2.PartialGuildIntegration

Bases: object

Represents a partial integration in a guild.

User

class discord.oauth2.User

Bases: BaseUser

Represents a full Discord user retrieved via an OAuth2 AccessToken.

Note

email and discord.oauth2.User.verified are only present if authorized with the email. Otherwise they are MISSING

id

The user’s ID.

Type:

int

username

The user’s username.

Type:

str

global_name

The users global name if set. In the client UI this referred to as “Display Name”.

Type:

Optional[str]

discriminator

The user’s discriminator.

Deprecated since version 2.0.

Important

This will be removed in the future. Read more about it here.

Type:

str

avatar

The user’s avatar hash.

Type:

Optional[str]

bot

Indicates if the user is a bot account. Should always be False as bots can’t use OAuth2.

Type:

bool

system

Indicates if the user is a system account.

Type:

bool

mfa_enabled

Indicates if the user has MFA enabled on their account.

Type:

bool

banner

The user’s banner hash.

Type:

Optional[str]

locale

The user’s chosen language option.

Type:

Optional[Locale]

verified

Indicates if the email on this account has been verified.

Type:

Optional[bool]

email

The user’s email.

Type:

Optional[str]

premium_type

The user’s premium subscription type.

Type:

PremiumType

property flags

The available flags the user has. This might be the same as public_flags.

Type:

PublicUserFlags

property accent_color

A colour object that represents the user’s banner colour.

Note

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

Type:

Optional[Colour]

property accent_colour

An alias for accent_color.

Type:

Optional[Colour]

avatar_decoration_url_as(*, format=None, size=1024)

Returns an Asset for the avatar decoration the user has. Could be None.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the avatar decoration to. If the format is None, then it is automatically detected into static_format.

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format, or invalid size.

Returns:

The resulting CDN asset if any.

Return type:

Optional[Asset]

property avatar_url

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

This is equivalent to calling avatar_url_as() with the default parameters (i.e. webp/gif detection and a size of 1024).

Type:

Asset

avatar_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the avatar to. If the format is None, then it is automatically detected into either ‘gif’ or static_format depending on the avatar being animated or not.

  • static_format (Optional[str]) – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or static_format, or invalid size.

Returns:

The resulting CDN asset.

Return type:

Asset

property banner_color

A colour object that represents the user’s banner colour.

Note

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

Type:

Optional[Colour]

property banner_colour

A colour object that represents the user’s banner colour.

Note

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

Type:

Optional[Colour]

property banner_url

Returns an asset for the banner the user has, if any. This is equal to calling banner_url_as() with the default arguments.

Returns:

The resulting CDN asset if any.

Return type:

Optional[Asset]

Type:

Optional[Asset]

banner_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the banner the user has. Could be None.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated banners. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the banner to. If the format is None, then it is automatically detected into either ‘gif’ or static_format depending on the banner being animated or not.

  • static_format (Optional[str]) – Format to attempt to convert only non-animated banner to. Defaults to ‘webp’

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or static_format, or invalid size.

Returns:

The resulting CDN asset if any.

Return type:

Optional[Asset]

property color

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

There is an alias for this named colour.

Type:

Colour

property colour

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

There is an alias for this named color.

Type:

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. For non-migrated users this is calculated by the user’s discriminator. For migrated users this is calculated by the user’s ID.

Type:

DefaultAvatar

property default_avatar_url

Returns a URL for a user’s default avatar.

Type:

Asset

property display_avatar

Returns the users display avatar.

For regular users this is equal to avatar_url.

Type:

Asset

property display_name

Returns the user’s display name.

For regular users this is just their global_name if set else their username, but if they have a guild specific nickname then that is returned instead.

Type:

str

property hex_banner_color

Returns a hexadecimal representation of the user’s banner colour, if available.

Type:

Optional[str]

is_avatar_animated()

bool: Indicates if the user has an animated avatar.

is_banner_animated()

bool: Indicates if the user has an animated banner.

property is_migrated

Indicates if the user has migrated to the new username system.

Type:

bool

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 (Message) – The message to check if you’re mentioned in.

Returns:

Indicates if the user is mentioned in the message.

Return type:

bool

property name

This is an alias of username which replaces the previous name attribute.

Note

It is recommended to use username instead as this might be removed in the future.

Type:

str

permissions_in(channel)

An alias for abc.GuildChannel.permissions_for().

Basically equivalent to:

channel.permissions_for(self)
Parameters:

channel (abc.GuildChannel) – The channel to check your permissions for.

property public_flags

The publicly available flags the user has.

Type:

PublicUserFlags

Partial User

class discord.oauth2.PartialUser

Bases: _BaseUser

Represents a partial Discord User retrieved via an OAuth2 AccessToken.

This

x == y
Checks if two partial users are equal.
x != y
Checks if two partial users are not equal.
hash(x)
Returns the partial user's hash.
str(x)
Returns the :attr:`username` if :attr:`is_migrated` is true, else the user's name with discriminator.

Note

When the migration is complete, this will always return the username .

Added in version 2.0.

id

The user’s ID.

Type:

int

username

The user’s username.

Type:

str

global_name

The users global name if set. In the client UI this referred to as “Display Name”.

Type:

Optional[str]

discriminator

The user’s discriminator.

Deprecated since version 2.0.

Important

This will be removed in the future. Read more about it here.

Type:

str

avatar

The user’s avatar hash.

Type:

Optional[str]

avatar_decoration

The user’s avatar decoration hash.

Type:

Optional[str]

property name

This is an alias of username which replaces the previous name attribute.

Note

It is recommended to use username instead as this might be removed in the future.

Type:

str

property is_migrated

Indicates if the user has migrated to the new username system.

Type:

bool

property public_flags

The available public flags the user has.

Type:

PublicUserFlags

property mention

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

Type:

str

property display_name

Returns the user’s display name.

For regular users this is just their global_name if set else their username, but if they have a guild specific nickname then that is returned instead.

Type:

str

property created_at

Returns the user’s creation time in UTC.

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

Type:

datetime

property avatar_url

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

This is equivalent to calling avatar_url_as() with the default parameters (i.e. webp/gif detection and a size of 1024).

Type:

Asset

is_avatar_animated()

bool: Indicates if the user has an animated avatar.

avatar_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the avatar to. If the format is None, then it is automatically detected into either ‘gif’ or static_format depending on the avatar being animated or not.

  • static_format (Optional[str]) – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or static_format, or invalid size.

Returns:

The resulting CDN asset.

Return type:

Asset

property default_avatar

Returns the default avatar for a given user. For non-migrated users this is calculated by the user’s discriminator. For migrated users this is calculated by the user’s ID.

Type:

DefaultAvatar

property default_avatar_url

Returns a URL for a user’s default avatar.

Type:

Asset

Enumerations

class discord.oauth2.OAuth2Scope

Bases: Enum

These are all the OAuth2 scopes that Discord supports. Some scopes require approval from Discord to use. Requesting them from a user without approval from Discord may cause errors or undocumented behavior in the OAuth2 flow.

Attribute

Name

Description

READ_ACTIVITIES

activities.read

allows your app to fetch data from a user’s “Now Playing/Recently Played” list - not currently available for apps

WRITE_ACTIVITIES

activities.write

allows your app to update a user’s activity - requires Discord approval (NOT REQUIRED FOR GAMESDK ACTIVITY MANAGER)

READ_APPLICATIONS_BUILDS

applications.builds.read

allows your app to read build data for a user’s applications

UPLOAD_APPLICATIONS_BUILDS

applications.builds.upload

allows your app to upload/update builds for a user’s applications - requires Discord approval

APPLICATIONS_COMMANDS

applications.commands

allows your app to use application-commands in a guild

UPDATE_APPLICATIONS_COMMANDS

applications.commands.update

allows your app to update its application-commands using a Bearer token - client credentials grant only

UPDATE_APPLICATIONS_COMMANDS_PERMISSIONS

applications.commands.permissions.update

allows your app to update permissions for its commands in a guild a user has permissions to

APPLICATIONS_ENTITLEMENTS

applications.entitlements

allows your app to read entitlements for a user’s applications

UPDATE_APPLICATIONS_STORE

applications.store.update

allows your app to read and update store data (SKUs, store listings, achievements, etc.) for a user’s applications

BOT

bot

for oauth2 bots, this puts the bot in the user’s selected guild by default

CONNECTIONS

connections

allows /users/@me/connections to return linked third-party accounts

READ_DM_CHANNELS

dm_channels.read

allows your app to see information about the user’s DMs and group DMs - requires Discord approval

ACCESS_EMAIL

email

enables /users/@me to return an email

JOIN_GROUPS

gdm.join

allows your app to join users to a group dm

ACCESS_GUILDS

guilds

allows /users/@me/guilds to return basic information about all of a user’s guilds

JOIN_GUILDS

guilds.join

allows /guilds/{guild.id}/members/{user.id} to be used for joining users to a guild

READ_GUILDS_MEMBERS

guilds.members.read

allows /users/@me/guilds/{guild.id}/member to return a user’s member information in a guild

IDENTIFY

identify

allows /users/@me without email

READ_MESSAGES

messages.read

for local rpc server api access, this allows you to read messages from all client channels (otherwise restricted to channels/guilds your app creates)

READ_RELATIONSHIPS

relationships.read

allows your app to know a user’s friends and implicit relationships - requires Discord approval

WRITE_ROLE_CONNECTIONS

role_connections.write

allows your app to update a user’s connection and metadata for the app

ACCESS_RPC

rpc

for local rpc server access, this allows you to control a user’s local Discord client - requires Discord approval

RPC_WRITE_ACTIVITIES

rpc.activities.write

for local rpc server access, this allows you to update a user’s activity - requires Discord approval

RPC_READ_NOTIFICATIONS

rpc.notifications.read

for local rpc server access, this allows you to receive notifications pushed out to the user - requires Discord approval

RPC_READ_VOICE

rpc.voice.read

for local rpc server access, this allows you to read a user’s voice settings and listen for voice events - requires Discord approval

RPC_WRITE_VOICE

rpc.voice.write

for local rpc server access, this allows you to update a user’s voice settings - requires Discord approval

VOICE

voice

allows your app to connect to voice on user’s behalf and see all the voice members - requires Discord approval

CREATE_WEBHOOK

webhook.incoming

this generates a webhook that is returned in the oauth token response for authorization code grants

Important

JOIN_GUILDS and BOT require you to have a bot account linked to your application. Also, in order to add a user to a guild, your bot has to already belong to that guild.

class discord.oauth2.ConnectionService

Bases: Enum

Represents the service of a Connection.

str(x)

Returns the connection type’s name.

Name

Value

Battlenet

battlenet

Crunchyroll

crunchyroll

eBay

ebay

Epic_Games

epicgames

Facebook

facebook

GitHub

github

Instagram

instagram

League_of_Legends

leagueoflegends

PayPal

paypal

Playstation

playstation

Reddit

reddit

Riotgames

riotgames

Skype

skype

Spotify

spotify

Steam

steam

TikTok

tiktok

Twitch

twitch

Twitter

twitter

xBox

xbox

YouTube

youtube

Exceptions

The following exceptions are thrown by the oauth2 sub-package

exception discord.oauth2.OAuth2Exception

Bases: DiscordException

Base class for all OAuth2 errors.

exception discord.oauth2.AccessTokenExpired(refreshable=True)

Bases: OAuth2Exception

Exception raised when an access token has expired.

exception discord.oauth2.AccessTokenNotRefreshable

Bases: OAuth2Exception

Exception raised when a token is not refreshable.

exception discord.oauth2.InvalidAccessToken

Bases: OAuth2Exception

Exception raised when an invalid access token is used.

exception discord.oauth2.InvalidRefreshToken

Bases: OAuth2Exception

Exception raised when an invalid refresh token is used.

exception discord.oauth2.InvalidAuthorizationCode

Bases: OAuth2Exception

Exception raised when an invalid authorization code is used.

exception discord.oauth2.UserIsAtGuildLimit

Bases: OAuth2Exception

Exception raised when the user is at the guild limit.

Exception Hierarchy