API Reference

This sections has reference to all of the available classes, their attributes and available methods.

Discord OAuth2 Client

class flask_discord.DiscordOAuth2Session(app=None, client_id=None, client_secret=None, redirect_uri=None, bot_token=None, users_cache=None, proxy=None, proxy_auth=None)[source]

Main client class representing hypothetical OAuth2 session with discord. It uses Flask session local proxy object to save state, authorization token and keeps record of users sessions across different requests. This class inherits flask_discord._http.DiscordOAuth2HttpClient class.

Parameters
  • app (Flask) – An instance of your flask application.

  • client_id (int, optional) – The client ID of discord application provided. Can be also set to flask config with key DISCORD_CLIENT_ID.

  • client_secret (str, optional) – The client secret of discord application provided. Can be also set to flask config with key DISCORD_CLIENT_SECRET.

  • redirect_uri (str, optional) – The default URL to use to redirect user to after authorization. Can be also set to flask config with key DISCORD_REDIRECT_URI.

  • bot_token (str, optional) – The bot token of the application. This is required when you also need to access bot scope resources beyond the normal resources provided by the OAuth. Can be also set to flask config with key DISCORD_BOT_TOKEN.

  • users_cache (cachetools.LFUCache, optional) – Any dict like mapping to internally cache the authorized users. Preferably an instance of cachetools.LFUCache or cachetools.TTLCache. If not specified, default cachetools.LFUCache is used. Uses the default max limit for cache if DISCORD_USERS_CACHE_MAX_LIMIT isn’t specified in app config.

client_id

The client ID of discord application provided.

Type

int

redirect_uri

The default URL to use to redirect user to after authorization.

Type

str

users_cache

A dict like mapping to internally cache the authorized users. Preferably an instance of cachetools.LFUCache or cachetools.TTLCache. If not specified, default cachetools.LFUCache is used. Uses the default max limit for cache if DISCORD_USERS_CACHE_MAX_LIMIT isn’t specified in app config.

Type

cachetools.LFUCache

property authorized

A boolean indicating whether current session has authorization token or not.

bot_request(route: str, method='GET', **kwargs)Union[dict, str]

Make HTTP request to specified endpoint with bot token as authorization headers.

Parameters
  • route (str) – Route or endpoint URL to send HTTP request to.

  • method (str, optional) – Specify the HTTP method to use to perform this request.

Returns

Dictionary containing received from sent HTTP GET request if content-type is application/json otherwise returns raw text content of the response.

Return type

dict, str

Raises
callback()[source]

A method which should be always called after completing authorization code grant process usually in callback view. It fetches the authorization token and saves it flask session object.

create_session(scope: Optional[list] = None, *, data: Optional[dict] = None, prompt: bool = True, permissions: Union[discord.permissions.Permissions, int] = 0, **params)[source]

Primary method used to create OAuth2 session and redirect users for authorization code grant.

Parameters
  • scope (list, optional) – An optional list of valid Discord OAuth2 Scopes.

  • data (dict, optional) – A mapping of your any custom data which you want to access after authorization grant. Use :py:meth:flask_discord.DiscordOAuth2Session.callback to retrieve this data in your callback view.

  • prompt (bool, optional) – Determines if the OAuth2 grant should be explicitly prompted and re-approved. Defaults to True. Specify False for implicit grant which will skip the authorization screen and redirect to redirect URI.

  • permissions (typing.Union[discord.Permissions, int], optional) – An optional parameter determining guild permissions of the bot while adding it to a guild using discord OAuth2 with bot scope. It is same as generating so called bot invite link which redirects to your callback endpoint after bot authorization flow. Defaults to 0 or no permissions.

  • params (kwargs, optional) – Additional query parameters to append to authorization URL for customized OAuth flow.

Returns

Flask redirect to discord authorization servers to complete authorization code grant process.

Return type

redirect

static fetch_connections()list[source]

This method returns list of user connection objects from internal cache if it exists otherwise makes an API call to do so.

Returns

List of flask_discord.models.UserConnection objects.

Return type

list

static fetch_guilds()list[source]

This method returns list of guild objects from internal cache if it exists otherwise makes an API call to do so.

Returns

List of flask_discord.models.Guild objects.

Return type

list

static fetch_user()flask_discord.models.user.User[source]

This method returns user object from the internal cache if it exists otherwise makes an API call to do so.

Returns

Return type

flask_discord.models.User

static get_authorization_token()dict[source]

A static method which returns a dict containing Discord OAuth2 token and other secrets which was saved previously by :py:meth:`flask_discord.DiscordOAuth2Session.save_authorization_token from user’s cookies.

You must override this method if you are implementing server side session handling.

init_app(app)

A method to lazily initialize the application. Use this when you’re using flask factory pattern to create your instances of your flask application.

Parameters

app (Flask) –

An instance of your flask application.

request(route: str, method='GET', data=None, oauth=True, **kwargs)Union[dict, str]

Sends HTTP request to provided route or discord endpoint.

Note

It automatically prefixes the API Base URL so you will just have to pass routes or URL endpoints.

Parameters
  • route (str) – Route or endpoint URL to send HTTP request to. Example: /users/@me

  • method (str, optional) – Specify the HTTP method to use to perform this request.

  • data (dict, optional) – The optional payload the include with the request.

  • oauth (bool) – A boolean determining if this should be Discord OAuth2 session request or any standard request.

Returns

Dictionary containing received from sent HTTP GET request if content-type is application/json otherwise returns raw text content of the response.

Return type

dict, str

Raises
revoke()[source]

This method clears current discord token, state and all session data from flask session. Which means user will have to go through discord authorization token grant flow again. Also tries to remove the user from internal cache if they exist.

static save_authorization_token(token: dict)[source]

A staticmethod which saves a dict containing Discord OAuth2 token and other secrets to the user’s cookies. Meaning by default, it uses client side session handling.

Override this method if you want to handle the user’s session server side. If this method is overridden then, you must also override flask_discord.DiscordOAuth2Session.get_authorization_token().

property user_id: Optional[int]

A property which returns Discord user ID if it exists in flask flask.session object.

Returns

  • int – The Discord user ID of current user.

  • None – If the user ID doesn’t exists in flask flask.session.

class flask_discord._http.DiscordOAuth2HttpClient(app=None, client_id=None, client_secret=None, redirect_uri=None, bot_token=None, users_cache=None, proxy=None, proxy_auth=None)[source]

An OAuth2 http abstract base class providing some factory methods. This class is meant to be overridden by flask_discord.DiscordOAuth2Session and should not be used directly.

bot_request(route: str, method='GET', **kwargs)Union[dict, str][source]

Make HTTP request to specified endpoint with bot token as authorization headers.

Parameters
  • route (str) – Route or endpoint URL to send HTTP request to.

  • method (str, optional) – Specify the HTTP method to use to perform this request.

Returns

Dictionary containing received from sent HTTP GET request if content-type is application/json otherwise returns raw text content of the response.

Return type

dict, str

Raises
init_app(app)[source]

A method to lazily initialize the application. Use this when you’re using flask factory pattern to create your instances of your flask application.

Parameters

app (Flask) –

An instance of your flask application.

request(route: str, method='GET', data=None, oauth=True, **kwargs)Union[dict, str][source]

Sends HTTP request to provided route or discord endpoint.

Note

It automatically prefixes the API Base URL so you will just have to pass routes or URL endpoints.

Parameters
  • route (str) – Route or endpoint URL to send HTTP request to. Example: /users/@me

  • method (str, optional) – Specify the HTTP method to use to perform this request.

  • data (dict, optional) – The optional payload the include with the request.

  • oauth (bool) – A boolean determining if this should be Discord OAuth2 session request or any standard request.

Returns

Dictionary containing received from sent HTTP GET request if content-type is application/json otherwise returns raw text content of the response.

Return type

dict, str

Raises
property user_id: Optional[int]

A property which returns Discord user ID if it exists in flask flask.session object.

Returns

  • int – The Discord user ID of current user.

  • None – If the user ID doesn’t exists in flask flask.session.

Models

class flask_discord.models.Guild(payload)[source]

Class representing discord Guild the user is part of.

x == y

Checks if two guild’s are the same.

x != y

Checks if two guild’s are not the same.

str(x)

Returns the guild’s name.

id

Discord ID of the guild.

Type

int

name

Name of the guild.

Type

str

icon_hash

Hash of guild’s icon.

Type

str

is_owner

Boolean determining if current user is owner of the guild or not.

Type

bool

permissions

An instance of discord.Permissions representing permissions of current user in the guild.

Type

discord.Permissions

classmethod fetch_from_api(cache=True)[source]

A class method which returns an instance or list of instances of this model by implicitly making an API call to Discord. If an instance of flask_discord.User exists in the users internal cache who belongs to these guilds then, the cached property flask_discord.User.guilds is updated.

Parameters

cache (bool) – Determines if the flask_discord.User.guilds cache should be updated with the new guilds.

Returns

List of instances of flask_discord.Guild to which this user belongs.

Return type

list[flask_discord.Guild, …]

property icon_url

A property returning direct URL to the guild’s icon. Returns None if guild has no icon set.

to_json()

A utility method which returns raw payload object as it was received from discord.

Returns

A dict representing raw payload object received from discord.

Return type

dict

class flask_discord.models.User(payload)[source]

Class representing Discord User.

x == y

Checks if two user’s are the same.

x != y

Checks if two user’s are not the same.

str(x)

Returns the user’s name with discriminator.

id

The discord ID of the user.

Type

int

username

The discord username of the user.

Type

str

discriminator

4 length string representing discord tag of the user.

Type

str

avatar_hash

Hash of users avatar.

Type

str

bot

A boolean representing whether the user belongs to an OAuth2 application.

Type

bool

mfa_enabled

A boolean representing whether the user has two factor enabled on their account.

Type

bool

locale

The user’s chosen language option.

Type

str

verified

A boolean representing whether the email on this account has been verified.

Type

bool

email

User’s email ID.

Type

str

flags

An integer representing the user flags.

Type

int

premium_type

An integer representing the type of nitro subscription.

Type

int

connections

A list of flask_discord.UserConnection instances. These are cached and this list might be empty.

Type

list

add_to_guild(guild_id)dict[source]

Method to add user to the guild, provided OAuth2 session has already been created with guilds.join scope.

Parameters

guild_id (int) – The ID of the guild you want this user to be added.

Returns

A dict of guild member object. Returns an empty dict if user is already present in the guild.

Return type

dict

Raises

flask_discord.Unauthorized – Raises flask_discord.Unauthorized if current user is not authorized.

property avatar_url

A property returning direct URL to user’s avatar.

property default_avatar_url

A property which returns the default avatar URL as when user doesn’t has any avatar set.

fetch_connections()list[source]

A method which makes an API call to Discord to get user’s connections. It prepares the internal connection cache and returns list of all connection instances.

Returns

A list of flask_discord.UserConnection instances.

Return type

list

classmethod fetch_from_api(guilds=False, connections=False)[source]

A class method which returns an instance of this model by implicitly making an API call to Discord. The user returned from API will always be cached and update in internal cache.

Parameters
  • guilds (bool) – A boolean indicating if user’s guilds should be cached or not. Defaults to False. If chose to not cache, user’s guilds can always be obtained from flask_discord.Guilds.fetch_from_api().

  • connections (bool) – A boolean indicating if user’s connections should be cached or not. Defaults to False. If chose to not cache, user’s connections can always be obtained from flask_discord.Connections.fetch_from_api().

Returns

  • cls – An instance of this model itself.

  • [cls, …] – List of instances of this model when many of these models exist.

fetch_guilds()list[source]

A method which makes an API call to Discord to get user’s guilds. It prepares the internal guilds cache and returns list of all guilds the user is member of.

Returns

List of flask_discord.Guilds instances.

Return type

list

classmethod get_from_cache()[source]

A class method which returns an instance of this model if it exists in internal cache.

Returns

  • flask_discord.User – An user instance if it exists in internal cache.

  • None – If the current doesn’t exists in internal cache.

property guilds

A cached mapping of user’s guild ID to flask_discord.Guild. The guilds are cached when the first API call for guilds is requested so it might be an empty dict.

property is_avatar_animated

A boolean representing if avatar of user is animated. Meaning user has GIF avatar.

property name

An alias to the username attribute.

to_json()

A utility method which returns raw payload object as it was received from discord.

Returns

A dict representing raw payload object received from discord.

Return type

dict

class flask_discord.models.Bot(payload)[source]

Class representing the client user itself.

add_to_guild(guild_id)dict

Method to add user to the guild, provided OAuth2 session has already been created with guilds.join scope.

Parameters

guild_id (int) – The ID of the guild you want this user to be added.

Returns

A dict of guild member object. Returns an empty dict if user is already present in the guild.

Return type

dict

Raises

flask_discord.Unauthorized – Raises flask_discord.Unauthorized if current user is not authorized.

property avatar_url

A property returning direct URL to user’s avatar.

property default_avatar_url

A property which returns the default avatar URL as when user doesn’t has any avatar set.

fetch_connections()list

A method which makes an API call to Discord to get user’s connections. It prepares the internal connection cache and returns list of all connection instances.

Returns

A list of flask_discord.UserConnection instances.

Return type

list

classmethod fetch_from_api(guilds=False, connections=False)

A class method which returns an instance of this model by implicitly making an API call to Discord. The user returned from API will always be cached and update in internal cache.

Parameters
  • guilds (bool) – A boolean indicating if user’s guilds should be cached or not. Defaults to False. If chose to not cache, user’s guilds can always be obtained from flask_discord.Guilds.fetch_from_api().

  • connections (bool) – A boolean indicating if user’s connections should be cached or not. Defaults to False. If chose to not cache, user’s connections can always be obtained from flask_discord.Connections.fetch_from_api().

Returns

  • cls – An instance of this model itself.

  • [cls, …] – List of instances of this model when many of these models exist.

fetch_guilds()list

A method which makes an API call to Discord to get user’s guilds. It prepares the internal guilds cache and returns list of all guilds the user is member of.

Returns

List of flask_discord.Guilds instances.

Return type

list

classmethod get_from_cache()

A class method which returns an instance of this model if it exists in internal cache.

Returns

  • flask_discord.User – An user instance if it exists in internal cache.

  • None – If the current doesn’t exists in internal cache.

property guilds

A cached mapping of user’s guild ID to flask_discord.Guild. The guilds are cached when the first API call for guilds is requested so it might be an empty dict.

property is_avatar_animated

A boolean representing if avatar of user is animated. Meaning user has GIF avatar.

property name

An alias to the username attribute.

to_json()

A utility method which returns raw payload object as it was received from discord.

Returns

A dict representing raw payload object received from discord.

Return type

dict

class flask_discord.models.Integration(payload)[source]

“Class representing discord server integrations.

id

Integration ID.

Type

int

name

Name of integration.

Type

str

type

Integration type (twitch, youtube, etc).

Type

str

enabled

A boolean representing if this integration is enabled.

Type

bool

syncing

A boolean representing if this integration is syncing.

Type

bool

role_id

ID that this integration uses for subscribers.

Type

int

expire_behaviour

An integer representing the behaviour of expiring subscribers.

Type

int

expire_grace_period

An integer representing the grace period before expiring subscribers.

Type

int

account

A dictionary representing raw account object.

Type

dict

synced_at

Representing when this integration was last synced.

Type

ISO8601 timestamp

class flask_discord.models.UserConnection(payload)[source]

Class representing connections in discord account of the user.

id

ID of the connection account.

Type

str

name

The username of the connection account.

Type

str

type

The service of connection (twitch, youtube).

Type

str

revoked

A boolean representing whether the connection is revoked.

Type

bool

integrations

A list of server Integration objects.

Type

list

verified

A boolean representing whether the connection is verified.

Type

bool

friend_sync

A boolean representing whether friend sync is enabled for this connection.

Type

bool

show_activity

A boolean representing whether activities related to this connection will be shown in presence updates.

Type

bool

visibility

An integer representing visibility of this connection.

Type

int

classmethod fetch_from_api(cache=True)[source]

A class method which returns an instance or list of instances of this model by implicitly making an API call to Discord. If an instance of flask_discord.User exists in the users internal cache who are attached to these connections then, the cached property flask_discord.User.connections is updated.

Parameters

cache (bool) – Determines if the flask_discord.User.guilds cache should be updated with the new guilds.

Returns

List of instances of flask_discord.UserConnection to which this user belongs.

Return type

list[flask_discord.UserConnection, …]

property is_visible

A property returning bool if this integration is visible to everyone.

to_json()

A utility method which returns raw payload object as it was received from discord.

Returns

A dict representing raw payload object received from discord.

Return type

dict

Utilities

@flask_discord.requires_authorization[source]

A decorator for flask views which raises exception flask_discord.Unauthorized if the user is not authorized from Discord OAuth2.

Exceptions

class flask_discord.HttpException[source]

Base Exception class representing a HTTP exception.

class flask_discord.RateLimited(json, headers)[source]

A HTTP Exception raised when the application is being rate limited. It provides the response attribute which can be used to get more details of the actual response from the Discord API with few more shorthands to response.json().

json

The actual JSON data received. Shorthand to response.json().

Type

dict

message

A message saying you are being rate limited.

Type

str

retry_after

The number of milliseconds to wait before submitting another request.

Type

int

is_global

A value indicating if you are being globally rate limited or not

Type

bool

class flask_discord.Unauthorized[source]

A HTTP Exception raised when user is not authorized.

class flask_discord.AccessDenied[source]

Exception raised when user cancels OAuth authorization grant.

Configuration Values

Flask Discord attempts to fetch expected configuration keys from the config of initialized flask app.

DISCORD_CLIENT_ID

Client ID of your Discord application. Can be retrieved from your Discord developers dashboard. This can be also passed as client_id to flask_discord.DiscordOAuth2Session constructor.

DISCORD_CLIENT_SECRET

The client secret of your Discord application. Can also be retrieved from your Discord developers dashboard. This can be also passed as client_secret to flask_discord.DiscordOAuth2Session constructor.

DISCORD_REDIRECT_URI

The default URL to use to redirect user to after authorization. This should be exactly same as what you’ve specified in Redirects in Discord developers dashboard OAuth2 section. This can be also passed as redirect_uri to flask_discord.DiscordOAuth2Session constructor.

DISCORD_BOT_TOKEN

The bot token of the application. This is required when you also need to access bot scope resources beyond the normal resources provided by the OAuth. This can be also passed as bot_token to flask_discord.DiscordOAuth2Session constructor.

DISCORD_USERS_CACHE_MAX_LIMIT

Flask Discord has an internal caching layer to prevent rate limits. This specifies the max number of users to be cached using the default Last Frequently Used cache implementation. Defaults to 100.