OAuth2 API Reference
The following section outlines the OAuth2 API of discord4py
OAuth2 Client
- asyncadd_guild_member
- asyncauthorize
- asyncedit_application_command_permissions
- asyncfetch_access_token_info
- asyncfetch_all_application_command_permissions
- asyncfetch_application_command_permissions
- asyncfetch_connections
- asyncfetch_guild_member
- asyncfetch_guilds
- asyncfetch_user
- asyncfetch_user_app_role_connection
- asyncrefresh_access_token
- asyncrevoke_access_token
- defsetup_logging
- asyncstart
- asyncupdate_user_app_role_connection
- class discord.oauth2.OAuth2Client
Bases:
objectA 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 ofAccessTokenStoreauto_refresh (
bool) – Whether to automatically refresh access tokens whenAccessTokenExpiredis 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.
- 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:
- auto_refresh
Whether to automatically refresh access tokens when
AccessTokenExpiredis raised.- Type:
- 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
Noneto thelog_handlerparameter.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 isNonethen the library will not set up anything logging related. Logging will still work ifNoneis passed, though it is your responsibility to set it up. The default log handler if not provided islogging.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 thelog_handlerparameter is notNone. Defaults to the value oflog_levelin the init orlogging.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 toTruethen the root logger is set up as well. Defaults toFalse.
- 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_startupevent.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:
- Raises:
InvalidAuthorizationCode – The authorization code is invalid or has expired
HTTPException – Requesting the access token failed
- Returns:
The access token for the user
- Return type:
- await refresh_access_token(access_token, /)
This function is a coroutine.
Refreshes an access token using its
refresh_tokenand 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:
- 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 forraw (
bool) – Whether to return the raw data or not
- Raises:
AccessTokenExpired – The access token is expired (this might be handled automatically when
auto_refreshisTrue)- Returns:
AccessTokenInfo– The info about the current authorizationdict– The raw data ifrawisTrue
- await fetch_user(access_token, /, *, raw=False)
This function is a coroutine.
Fetches the user associated with the access token. Requires the
IDENTIFYscope.- Parameters:
access_token (
AccessToken) – The access token to fetch the user forraw (
bool) – Whether to return the raw data, defaults toFalse
- Returns:
- await fetch_guilds(access_token, /, *, raw=False)
This function is a coroutine.
Fetches the guilds the current user is a member of. Requires the
GUILDSscope.- Parameters:
access_token (
AccessToken) – The access token to fetch the guilds forraw (
bool) – Whether to return the raw data, defaults toFalse
- Returns:
List[
PartialGuild] – The guilds the current user is a member ofList[
dict] – The raw data ifrawisTrue
- 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_MEMBERSscope.- Parameters:
access_token (
AccessToken) – The access token to fetch the guild member forguild_id (
SupportsStr) – The ID of the guild to fetch the guild member forraw (
bool) – Whether to return the raw data, defaults toFalse
- Raises:
AccessTokenExpired – The access token is expired (this might be handled automatically when
auto_refreshisTrue)- Returns:
GuildMember– The guild member of the current user in the guilddict– The raw data ifrawisTrue
- 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_tokento be authorized with theJOIN_GUILDSscope. Furthermore, the bot must be a member of the guild with thecreate_instant_invitepermissions.Warning
You should always ask for the user’s consent before adding them to a guild.
The
nick,roles,muteanddeafparameters are optional and requires different permission for the bot.Parameter
Required Permissions
nickrolesmutedeaf- 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 usingfetch_user().nick (
str) – The nickname to give the user. Defaults toNone.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 (
pendingwill beFalse).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 toFalse.deaf (
bool) – Whether to deafen the user on join. Defaults toFalse.raw (
bool) – Whether to return the raw data. Defaults toFalse.
- Raises:
AccessTokenExpired – The access token is expired (this might be handled automatically when
auto_refreshisTrue)Forbidden – The bot does not have the
create_instant_invitepermission.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 ifrawisTrue.
- await fetch_connections(access_token, /, *, raw=False)
This function is a coroutine.
Fetches the connections of the current user. Requires the
CONNECTIONSscope.- Parameters:
access_token (
AccessToken) – The access token to fetch the connections forraw (
bool) – Whether to return the raw data, defaults toFalse
- Raises:
AccessTokenExpired – The access token is expired (this might be handled automatically when
auto_refreshisTrue)- Returns:
List[
Connection] – The connections of the current userdict– The raw data ifrawisTrue
- 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_CONNECTIONSscope.- Parameters:
access_token (
AccessToken) – The access token to fetch the role connection forraw (
bool) – Whether to return the raw data, defaults toFalse
- Raises:
AccessTokenExpired – The access token is expired (this might be handled automatically when
auto_refreshisTrue)- Returns:
RoleConnection– The role connection of the current userdict– The raw data ifrawisTrue
- 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_CONNECTIONSscope.All parameters are optional and will only be updated if provided.
- Parameters:
access_token (
AccessToken) – The access token to update the role connection forplatform_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)The metadata of the role connection.
Mapping of
AppRoleConnectionMetadata.keys 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 toFalse
- Returns:
RoleConnection– The updated role connection of the current userdict– The raw data ifrawisTrue
- 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 toFalse
- Raises:
AccessTokenExpired – The access token is expired (this might be handled automatically when
auto_refreshisTrue)HTTPException – Fetching the application-command permissions failed.
- Returns:
List[
GuildApplicationCommandPermissions] – A list of all application command permissions for the given guild.List[
dict] – The raw data ifrawisTrue.
- 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 toFalse
- Raises:
AccessTokenExpired – The access token is expired (this might be handled automatically when
auto_refreshisTrue)Forbidden – The application does not have the permission to fetch the permissions.
NotFound – The application-command or the guild was not found.
- Returns:
- 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_PERMISSIONSscope.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_tokenmust be of a user that is a member of the guild and the following permissions are required: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 toFalse
- Raises:
AccessTokenExpired – The access token is expired (this might be handled automatically when
auto_refreshisTrue).Forbidden – The application does not have the permission to edit the permissions.
NotFound – The application-command or the guild was not found.
- Returns:
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:
@everyoneshould not be able to use the commandEvery 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
- asyncload_access_token
- asyncload_access_tokens
- asyncon_close
- asyncon_startup
- asyncremove_revoked_access_token
- asyncstore_access_token
- asyncstore_access_tokens
- asyncstore_refreshed_access_token
- class discord.oauth2.AccessTokenStore
Bases:
objectBase class for an access token store.
- await on_startup()
This function is a coroutine.
This is called by the
OAuth2Clientwhen 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
OAuth2Clientwhen 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
OAuth2Clientwhen a new access token is created usingOAuth2Client.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
OAuth2Clientwhen an access token is refreshed usingOAuth2Client.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
OAuth2Clientwhen an access token is revoked usingOAuth2Client.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
- clsAccessToken.from_raw_data
- asyncadd_guild_member
- asyncfetch_connections
- asyncfetch_guild_member
- asyncfetch_guilds
- asyncfetch_info
- asyncfetch_user
- asyncfetch_user_app_role_connection
- defis_expired
- asyncrefresh
- asyncrevoke
- defto_dict
- asyncupdate_user_app_role_connection
- class discord.oauth2.AccessToken
Bases:
objectA representation of a access token response from discord.
This can be also used to store additional data that can be accessed through getitem.
- x == y
Checks if two access tokens are equal.
- x != y
Checks if two access tokens are not equal.
- str(x)
Returns the
access_tokenBe 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 tokenaccess_token (
str) – The actual access token - this will also be returned when callingstr(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)
datetimeobjects 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 beNonedepending on the grant type usedscopes (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
OAuth2Clientthat 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 refresh_token
The refresh token that is required to refresh the access token when it is expired
- Type:
- scopes
A set of
OAuth2Scopethat the access token is authorized to.
- webhook
The webhook that was created with the webhook when the access token was authorized with the
CREATE_WEBHOOKscope. Only available on the original access token instance- Type:
- property refreshable
Whether the access token is refreshable. This checks if the
refresh_tokenis set- Type:
- is_expired()
bool: Whether the access token is expired. This just checks if theexpires_atis in the past
- classmethod from_raw_data(client, data)
Creates an
AccessTokenfrom raw data returned by discord.- Parameters:
client (
OAuth2Client) – The client that created this access tokendata (
AccessToken) – The raw data returned by discord
- Returns:
The access token object
- Return type:
- 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
forceis set. This also updates theexpires_atandrefresh_token.Note
This is only available when
clientandrefresh_tokenis set- Parameters:
force (
bool) – Whether to force-refresh the access token, even whenis_expired()returnsFalse- Raises:
AttributeError – The client attribute is not set
AccessTokenNotRefreshable – The access token is not refreshable
InvalidRefreshToken – The refresh token is invalid or has expired
- Returns:
The new access token
- Return type:
- 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_MEMBERSscope.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:
objectRepresents the authorization information for an access token.
- property scopes
A list of scopes the access token is authorized to.
- Type:
Set[
OAuth2Scope]
- class discord.oauth2.PartialAppInfo
Bases:
objectRepresents the application info for the bot provided by Discord.
- 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:
- bot_require_code_grant
Whether the bot requires the completion of the full oauth2 code grant flow to join.
- Type:
- verify_key
The hex encoded key for verification in interactions and the GameSDK’s GetTicket.
- Type:
- 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:
- icon_url_as(*, format='webp', size=1024)
Returns an
Assetfor 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:
- Raises:
InvalidArgument – Bad image format passed to
formator invalidsize.- Returns:
The resulting CDN asset.
- Return type:
Connection
- class discord.oauth2.Connection
Bases:
objectRepresents a connection of a user to a service.
- str(x)
Returns the connection’s name.
- 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
- deficon_url_as
- defis_icon_animated
- class discord.oauth2.PartialGuild
Bases:
HashableRepresents 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.
- 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]
- 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
Assetfor 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 isNone, 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
formator invalidsize.- Returns:
The resulting CDN asset.
- Return type:
Guild Member
- class discord.oauth2.GuildMember(*, client, data)
Bases:
_BaseUserRepresents 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.
- 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]
When the member started boosting the guild.
- Type:
Optional[
datetime.datetime]
- 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 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:
- 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
Assetfor the guild-specific avatar of the member if any, elseNone.The format must be one of ‘webp’, ‘jpeg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
formator invalidsize.- 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:
- display_avatar_url_as(format=None, static_format='webp', size=1024)
Same behaviour as
avatar_url_as()andguild_avatar_url_as()but it prefers the guild-specific avatar- Returns:
The resulting CDN asset for the avatar
- Return type:
- property avatar_url
Equivalent to
User.avatar_url
- avatar_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Assetfor 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 isNone, 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
formatorstatic_format, or invalidsize.- Returns:
The resulting CDN asset.
- Return type:
- 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:
objectRepresents a partial integration in a guild.
User
- class discord.oauth2.User
Bases:
BaseUserRepresents a full Discord user retrieved via an OAuth2
AccessToken.Note
emailanddiscord.oauth2.User.verifiedare only present if authorized with theemail. Otherwise they areMISSING- 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:
- avatar
The user’s avatar hash.
- Type:
Optional[
str]
- bot
Indicates if the user is a bot account. Should always be
Falseas bots can’t use OAuth2.- Type:
- 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]
The user’s email.
- Type:
Optional[
str]
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
Assetfor the avatar decoration the user has. Could beNone.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format, or invalidsize.- Returns:
The resulting CDN asset if any.
- Return type:
Optional[
Asset]
- property avatar_url
Returns an
Assetfor 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
Assetfor 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 isNone, 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
formatorstatic_format, or invalidsize.- 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
Assetfor the banner the user has. Could beNone.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 isNone, 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
formatorstatic_format, or invalidsize.- 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:
- 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 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_nameif set else theirusername, but if they have a guild specific nickname then that is returned instead.- Type:
- 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:
- 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:
- property name
This is an alias of
usernamewhich replaces the previous name attribute.Note
It is recommended to use
usernameinstead as this might be removed in the future.- Type:
Partial User
- class discord.oauth2.PartialUser
Bases:
_BaseUserRepresents 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.
- 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:
- 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
usernamewhich replaces the previous name attribute.Note
It is recommended to use
usernameinstead as this might be removed in the future.- Type:
- property is_migrated
Indicates if the user has migrated to the new username system.
- Type:
- property display_name
Returns the user’s display name.
For regular users this is just their
global_nameif set else theirusername, but if they have a guild specific nickname then that is returned instead.- Type:
- property created_at
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
- Type:
- property avatar_url
Returns an
Assetfor 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:
- is_avatar_animated()
bool: Indicates if the user has an animated avatar.
- avatar_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Assetfor 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 isNone, 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
formatorstatic_format, or invalidsize.- Returns:
The resulting CDN asset.
- Return type:
- 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
Enumerations
- class discord.oauth2.OAuth2Scope
Bases:
EnumThese 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
activities.read
allows your app to fetch data from a user’s “Now Playing/Recently Played” list - not currently available for apps
activities.write
allows your app to update a user’s activity - requires Discord approval (NOT REQUIRED FOR GAMESDK ACTIVITY MANAGER)
applications.builds.read
allows your app to read build data for a user’s applications
applications.builds.upload
allows your app to upload/update builds for a user’s applications - requires Discord approval
applications.commands
allows your app to use application-commands in a guild
applications.commands.update
allows your app to update its application-commands using a Bearer token - client credentials grant only
applications.commands.permissions.update
allows your app to update permissions for its commands in a guild a user has permissions to
applications.entitlements
allows your app to read entitlements for a user’s applications
applications.store.update
allows your app to read and update store data (SKUs, store listings, achievements, etc.) for a user’s applications
bot
for oauth2 bots, this puts the bot in the user’s selected guild by default
connections
allows
/users/@me/connectionsto return linked third-party accountsdm_channels.read
allows your app to see information about the user’s DMs and group DMs - requires Discord approval
email
enables
/users/@meto return anemailgdm.join
allows your app to join users to a group dm
guilds
allows
/users/@me/guildsto return basic information about all of a user’s guildsguilds.join
allows
/guilds/{guild.id}/members/{user.id}to be used for joining users to a guildguilds.members.read
allows
/users/@me/guilds/{guild.id}/memberto return a user’s member information in a guildidentify
allows
/users/@mewithoutemailmessages.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)
relationships.read
allows your app to know a user’s friends and implicit relationships - requires Discord approval
role_connections.write
allows your app to update a user’s connection and metadata for the app
rpc
for local rpc server access, this allows you to control a user’s local Discord client - requires Discord approval
rpc.activities.write
for local rpc server access, this allows you to update a user’s activity - requires Discord approval
rpc.notifications.read
for local rpc server access, this allows you to receive notifications pushed out to the user - requires Discord approval
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.voice.write
for local rpc server access, this allows you to update a user’s voice settings - requires Discord approval
voice
allows your app to connect to voice on user’s behalf and see all the voice members - requires Discord approval
webhook.incoming
this generates a webhook that is returned in the oauth token response for authorization code grants
Important
JOIN_GUILDSandBOTrequire 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:
EnumRepresents the service of a
Connection.- str(x)
Returns the connection type’s name.
Name
Value
battlenet
crunchyroll
ebay
epicgames
facebook
github
instagram
leagueoflegends
paypal
playstation
reddit
riotgames
skype
spotify
steam
tiktok
twitch
twitter
xbox
youtube
Exceptions
The following exceptions are thrown by the oauth2 sub-package
- exception discord.oauth2.OAuth2Exception
Bases:
DiscordExceptionBase class for all OAuth2 errors.
- exception discord.oauth2.AccessTokenExpired(refreshable=True)
Bases:
OAuth2ExceptionException raised when an access token has expired.
- exception discord.oauth2.AccessTokenNotRefreshable
Bases:
OAuth2ExceptionException raised when a token is not refreshable.
- exception discord.oauth2.InvalidAccessToken
Bases:
OAuth2ExceptionException raised when an invalid access token is used.
- exception discord.oauth2.InvalidRefreshToken
Bases:
OAuth2ExceptionException raised when an invalid refresh token is used.
- exception discord.oauth2.InvalidAuthorizationCode
Bases:
OAuth2ExceptionException raised when an invalid authorization code is used.
- exception discord.oauth2.UserIsAtGuildLimit
Bases:
OAuth2ExceptionException raised when the user is at the guild limit.