Clients

Client

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

Bases: object

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

A number of options can be passed to the Client.

Parameters:
  • max_messages (Optional[int]) –

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

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

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

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

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

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

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

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

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

  • gateway_version (int) – The gateway and api version to use. Defaults to v10.

  • api_error_locale (discord.Locale) – The locale language to use for api errors. This will be applied to the X-Discord-Local header in requests. Default to Locale.en_US

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

  • fetch_offline_members (bool) – A deprecated alias of chunk_guilds_at_startup.

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

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

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

  • allowed_mentions (Optional[AllowedMentions]) – Control how the client handles mentions by default on every message sent.

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

  • guild_ready_timeout (float) –

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

    New in version 1.4.

  • guild_subscriptions (bool) –

    Whether to dispatch presence or typing events. Defaults to True.

    New in version 1.3.

    Warning

    If this is set to False then the following features will be disabled:

    In short, this makes it so the only member you can reliably query is the message author. Useful for bots that do not require any state.

  • assume_unsync_clock (bool) –

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

    New in version 1.3.

  • sync_commands (bool) –

    Whether to sync application-commands on startup, default False.

    This will register global and guild application-commands(slash-, user- and message-commands) that are not registered yet, update changes and remove application-commands that could not be found in the code anymore if delete_not_existing_commands is set to True what it is by default.

  • delete_not_existing_commands (bool) – Whether to remove global and guild-only application-commands that are not in the code anymore, default True.

  • auto_check_for_updates (bool) –

    Whether to check for available updates automatically, default False for legal reasons. For more info see discord.on_update_available().

    Note

    For now, this may only work on the original repository, not on forks. This is because it uses an internal API that listens to a private application that is on the original repo.

    In the future this API might be open-sourced, or it will be possible to add your forks URL as a valid source.

ws

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

loop

The event loop that the client uses for HTTP requests and websocket operations.

Type:

asyncio.AbstractEventLoop

@event

A decorator that registers an event to listen to.

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

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

Example

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

TypeError – The coroutine passed is not actually a coroutine.

@once(name=None, check=None)

A decorator that registers an event to listen to only once. For example if you want to perform a database connection once the bot is ready.

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

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

Parameters:
  • name (str) – The name of the event we want to listen to. This is passed to wait_for(). Defaults to func.__name__.

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

Raises:

TypeError – The coroutine passed is not actually a coroutine.

Example

@client.once()
async def ready():
    print('Beep bop, I\'m ready!')

@client.once(check=lambda msg: msg.author.id == 693088765333471284)
async def message(message):
    await message.reply('Hey there, how are you?')
async for ... in fetch_guilds(*, limit=100, before=None, after=None)

Retrieves an AsyncIterator that enables receiving your guilds.

Note

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

Note

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

Examples

Usage

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

Flattening into a list

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

All parameters are optional.

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

  • before (Union[abc.Snowflake, datetime.datetime]) – Retrieves guilds before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • after (Union[abc.Snowflake, datetime.datetime]) – Retrieve guilds after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.

Raises:

discord.HTTPException – Getting the guilds failed.

Yields:

Guild – The guild with the guild data parsed.

@slash_command(name=None, name_localizations=<Localizations: None>, description=None, description_localizations=<Localizations: None>, allow_dm=MISSING, is_nsfw=MISSING, default_required_permissions=None, options=[], guild_ids=None, connector={}, option_descriptions={}, option_descriptions_localizations={}, base_name=None, base_name_localizations=<Localizations: None>, base_desc=None, base_desc_localizations=<Localizations: None>, group_name=None, group_name_localizations=<Localizations: None>, group_desc=None, group_desc_localizations=<Localizations: None>)

A decorator that adds a slash-command to the client. The function this is attached to must be a coroutine.

Warning

sync_commands of the Client instance must be set to True to register a command if it does not already exist and update it if changes where made.

Note

Any of the following parameters are only needed when the corresponding target was not used before (e.g. there is already a command in the code that has these parameters set) - otherwise it will replace the previous value:

  • allow_dm

  • is_nsfw

  • base_name_localizations

  • base_desc

  • base_desc_localizations

  • group_name_localizations

  • group_desc

  • group_desc_localizations

Parameters:
  • name (Optional[str]) – The name of the command. Must only contain a-z, _ and - and be 1-32 characters long. Default to the functions name.

  • name_localizations (Optional[Localizations]) – Localizations object for name field. Values follow the same restrictions as name

  • description (Optional[str]) – The description of the command shows up in the client. Must be between 1-100 characters long. Default to the functions docstring or “No Description”.

  • description_localizations (Optional[Localizations]) – Localizations object for description field. Values follow the same restrictions as description

  • allow_dm (Optional[bool]) – Indicates whether the command is available in DMs with the app, only for globally-scoped commands. By default, commands are visible.

  • is_nsfw (bool) –

    Whether this command is an NSFW command, default False

    Note

    Currently all sub-commands of a command that is marked as NSFW are NSFW too.

  • default_required_permissions (Optional[Permissions]) – Permissions that a Member needs by default to execute(see) the command.

  • options (Optional[List[SlashCommandOption]]) – A list of max. 25 options for the command. If not provided the options will be generated using generate_options() that creates the options out of the function parameters. Required options must be listed before optional ones. Use options to connect non-ascii option names with the parameter of the function.

  • guild_ids (Optional[List[int]]) – ID’s of guilds this command should be registered in. If empty, the command will be global.

  • connector (Optional[Dict[str, str]]) – A dictionary containing the name of function-parameters as keys and the name of the option as values. Useful for using non-ascii Letters in your option names without getting ide-errors.

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

    Descriptions the generate_options() should take for the Options that will be generated. The keys are the name of the option and the value the description.

    Note

    This will only be used if options is not set.

  • option_descriptions_localizations (Optional[Dict[str, Localizations]]) – Localized description for the options. In the format {'option_name': Localizations(...)}

  • base_name (Optional[str]) – The name of the base-command(a-z, _ and -, 1-32 characters) if you want the command to be in a command-/sub-command-group. If the base-command does not exist yet, it will be added.

  • base_name_localizations (Optional[Localizations]) – Localized base_name’s for the command.

  • base_desc (Optional[str]) – The description of the base-command(1-100 characters).

  • base_desc_localizations (Optional[Localizations]) – Localized base_description’s for the command.

  • group_name (Optional[str]) – The name of the command-group(a-z, _ and -, 1-32 characters) if you want the command to be in a sub-command-group.

  • group_name_localizations (Optional[Localizations]) – Localized group_name’s for the command.

  • group_desc (Optional[str]) – The description of the sub-command-group(1-100 characters).

  • group_desc_localizations (Optional[Localizations]) – Localized group_desc’s for the command.

Raises:
  • TypeError – The function the decorator is attached to is not actual a coroutine or a parameter passed to SlashCommandOption is invalid for the option_type or the option_type itself is invalid.

  • InvalidArgument – You passed group_name but no base_name.

  • ValueError – Any of name, description, options, base_name, base_desc, group_name or group_desc is not valid.

Returns:

  • If neither guild_ids nor base_name passed: An instance of SlashCommand.

  • If guild_ids and no base_name where passed: An instance of GuildOnlySlashCommand representing the guild-only slash-commands.

  • If base_name and no guild_ids where passed: An instance of SubCommand.

  • If base_name and guild_ids passed: instance of GuildOnlySubCommand representing the guild-only sub-commands.

Return type:

Union[SlashCommand, GuildOnlySlashCommand, SubCommand, GuildOnlySubCommand]

@message_command(name=None, name_localizations=<Localizations: None>, default_required_permissions=None, allow_dm=True, is_nsfw=False, guild_ids=None)

A decorator that registers a MessageCommand (shows up under Apps when right-clicking on a message) to the client. The function this is attached to must be a coroutine.

Note

sync_commands of the Client instance must be set to True to register a command if it does not already exit and update it if changes where made.

Parameters:
  • name (Optional[str]) – The name of the message-command, default to the functions name. Must be between 1-32 characters long.

  • name_localizations (Localizations) – Localized name’s.

  • default_required_permissions (Optional[Permissions]) – Permissions that a member needs by default to execute(see) the command.

  • allow_dm (bool) – Indicates whether the command is available in DMs with the app, only for globally-scoped commands. By default, commands are visible.

  • is_nsfw (bool) –

    Whether this command is an NSFW command, default False.

  • guild_ids (Optional[List[int]]) – ID’s of guilds this command should be registered in. If empty, the command will be global.

Returns:

The message-command registered.

Return type:

MessageCommand

Raises:

TypeError – The function the decorator is attached to is not actual a coroutine.

@user_command(name=None, name_localizations=<Localizations: None>, default_required_permissions=None, allow_dm=True, is_nsfw=False, guild_ids=None)

A decorator that registers a UserCommand (shows up under Apps when right-clicking on a user) to the client. The function this is attached to must be a coroutine.

Note

sync_commands of the Client instance must be set to True to register a command if it does not already exist and update it if changes where made.

Parameters:
  • name (Optional[str]) – The name of the user-command, default to the functions name. Must be between 1-32 characters long.

  • name_localizations (Localizations) – Localized name’s.

  • default_required_permissions (Optional[Permissions]) – Permissions that a member needs by default to execute(see) the command.

  • allow_dm (bool) – Indicates whether the command is available in DMs with the app, only for globally-scoped commands. By default, commands are visible.

  • is_nsfw (bool) –

    Whether this command is an NSFW command, default False.

  • guild_ids (Optional[List[int]]) – ID’s of guilds this command should be registered in. If empty, the command will be global.

Returns:

The user-command registered.

Return type:

UserCommand

Raises:

TypeError – The function the decorator is attached to is not actual a coroutine.

@on_click(custom_id=None)

A decorator with wich you can assign a function to a specific Button (or its custom_id).

Important

The function this is attached to must take the same parameters as a on_raw_button_click() event.

Warning

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

Parameters:

custom_id (Optional[Union[Pattern[AnyStr], AnyStr]]) –

If the custom_id of the Button could not be used as a function name, or you want to give the function a different name then the custom_id use this one to set the custom_id. You can also specify a regex and if the custom_id matches it, the function will be executed.

Note

As the custom_id is converted to a Pattern put ^ in front and $ at the end of the custom_id if you want that the custom_id must exactly match the specified value. Otherwise, something like ‘cool blue Button is blue’ will let the function bee invoked too.

Example

# the button
Button(label='Hey im a cool blue Button',
        custom_id='cool blue Button',
        style=ButtonStyle.blurple)

# function that's called when the button pressed
@client.on_click(custom_id='^cool blue Button$')
async def cool_blue_button(i: discord.ComponentInteraction, button: Button):
    await i.respond(f'Hey you pressed a {button.custom_id}!', hidden=True)
Return type:

The decorator for the function called when the button clicked

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@on_select(custom_id=None)

A decorator with which you can assign a function to a specific SelectMenu (or its custom_id).

Important

The function this is attached to must take the same parameters as a on_raw_selection_select() event.

Warning

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

Parameters:

custom_id (Optional[Union[Pattern[AnyStr], AnyStr]] = None) –

If the custom_id of the SelectMenu could not be used as a function name, or you want to give the function a different name then the custom_id use this one to set the custom_id. You can also specify a regex and if the custom_id matches it, the function will be executed.

Note

As the custom_id is converted to a Pattern put ^ in front and $ at the end of the custom_id if you want that the custom_id must exactly match the specified value. Otherwise, something like ‘choose_your_gender later’ will let the function bee invoked too.

Example

# the SelectMenu
SelectMenu(custom_id='choose_your_gender',
           options=[
               SelectOption(label='Female', value='Female', emoji='♀️'),
               SelectOption(label='Male', value='Male', emoji='♂️'),
               SelectOption(label='Trans/Non Binary', value='Trans/Non Binary', emoji='⚧')
           ], placeholder='Choose your Gender')

# function that's called when the SelectMenu is used
@client.on_select()
async def choose_your_gender(i: discord.Interaction, select_menu):
    await i.respond(f'You selected `{select_menu.values[0]}`!', hidden=True)
Raises:

TypeError – The coroutine passed is not actually a coroutine.

@on_submit(custom_id=None)

A decorator with wich you can assign a function to a specific Modal (or its custom_id).

Important

The function this is attached to must take the same parameters as a on_modal_submit() event.

Warning

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

Parameters:

custom_id (Optional[Union[Pattern[AnyStr], AnyStr]]) –

If the custom_id of the modal could not be used as a function name, or you want to give the function a different name then the custom_id use this one to set the custom_id. You can also specify a regex and if the custom_id matches it, the function will be executed.

Note

As the custom_id is converted to a Pattern put ^ in front and $ at the end of the custom_id if you want that the custom_id must exactly match the specified value. Otherwise, something like ‘suggestions_modal_submit_private’ will let the function bee invoked too.

Tip

The resulting Match object will be available under the match attribute of the interaction.

See example below.

Examples

Simple example of a Modal with a custom_id and a function that’s called when the Modal is submitted.
# the Modal
Modal(
    title='Create a new suggestion',
    custom_id='suggestions_modal',
    components=[...]
)

# function that's called when the Modal is submitted
@client.on_submit(custom_id='^suggestions_modal$')
async def suggestions_modal_callback(i: discord.ModalSubmitInteraction):
    ...

# This can also be done based on the function name
@client.on_submit()
async def suggestions_modal(i: discord.ModalSubmitInteraction):
    ...
You can also use a more advanced RegEx containing groups to easily allow dynamic custom-id’s
@client.on_submit(custom_id='^ticket_answer:(?P<id>[0-9]+)$')
async def ticket_answer_callback(i: discord.ModalSubmitInteraction):
    user_id = int(i.match['id'])
    user = client.get_user(user_id) or await client.fetch_user(user_id)
Raises:

TypeError – The coroutine passed is not actually a coroutine.

property latency

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.

Type:

float

is_ws_ratelimited()

bool: Whether the websocket is currently rate limited.

This can be useful to know when deciding whether you should query members using HTTP or via the gateway.

New in version 1.6.

property user

Represents the connected client. None if not logged in.

Type:

Optional[ClientUser]

property guilds

The guilds that the connected client is a member of.

Type:

List[Guild]

property emojis

The emojis that the connected client has.

Type:

List[Emoji]

property stickers

The stickers that the connected client has.

Type:

List[Sticker]

property cached_messages

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

New in version 1.1.

Type:

Sequence[Message]

property private_channels

The private channels that the connected client is participating on.

Note

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

Type:

List[abc.PrivateChannel]

property voice_clients

Represents a list of voice connections.

These are usually VoiceClient instances.

Type:

List[VoiceProtocol]

is_ready()

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

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

This function is a coroutine.

The default error handler provided by the client.

By default, this prints to sys.stderr however it could be overridden to have a different implementation. Check on_error() for more details.

await on_application_command_error(cmd, interaction, exception)

This function is a coroutine.

The default error handler when an Exception was raised when invoking an application-command.

By default, this prints to sys.stderr however it could be overridden to have a different implementation. Check on_application_command_error() for more details.

await request_offline_members(*guilds)

This function is a coroutine.

Requests previously offline members from the guild to be filled up into the Guild.members cache. This function is usually not called. It should only be used if you have the fetch_offline_members parameter set to False.

When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if Guild.large is True.

Warning

This method is deprecated. Use Guild.chunk() instead.

Parameters:

*guilds (Guild) – An argument list of guilds to request offline members for.

Raises:

.InvalidArgument – If any guild is unavailable in the collection.

await before_identify_hook(shard_id, *, initial=False)

This function is a coroutine.

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

The default implementation sleeps for 5 seconds.

New in version 1.4.

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

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

await login(token)

This function is a coroutine.

Logs in the client with the specified credentials.

This function can be used in two different ways.

Parameters:

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

Raises:
  • .LoginFailure – The wrong credentials are passed.

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

await logout()

This function is a coroutine.

Logs out of Discord and closes all connections.

Deprecated since version 1.7.

Note

This is just an alias to close(). If you want to do extraneous cleanup when subclassing, it is suggested to override close() instead.

await connect(*, reconnect=True)

This function is a coroutine.

Creates a websocket connection and lets the websocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated.

Parameters:

reconnect (bool) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).

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

  • .ConnectionClosed – The websocket connection has been terminated.

await close()

This function is a coroutine.

Closes the connection to Discord.

clear()

Clears the internal state of the bot.

After this, the bot can be considered “re-opened”, i.e. is_closed() and is_ready() both return False along with the bot’s internal cache cleared.

await start(token, reconnect=True)

This function is a coroutine.

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

Raises:

TypeError – An unexpected keyword argument was received.

run(token, reconnect=True, *, log_handler=MISSING, log_formatter=MISSING, log_level=MISSING, root_logger=False)

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

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

Roughly Equivalent to:

try:
    loop.run_until_complete(start(*args, **kwargs))
except KeyboardInterrupt:
    loop.run_until_complete(close())
    # cancel all tasks lingering
finally:
    loop.close()

This function also 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.

Warning

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

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

  • reconnect (bool) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).

  • log_handler (Optional[logging.Handler]) – The log handler to use for the library’s logger. If this is None then the library will not set up anything logging related. Logging will still work if None is passed, though it is your responsibility to set it up. The default log handler if not provided is logging.StreamHandler.

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

is_closed()

bool: Indicates if the websocket connection is closed.

property activity

The activity being used upon logging in.

Type:

Optional[BaseActivity]

property allowed_mentions

The allowed mention configuration.

New in version 1.4.

Type:

Optional[AllowedMentions]

property intents

The intents configured for this connection.

New in version 1.5.

Type:

Intents

property users

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

Type:

List[User]

get_message(id)

Returns a Message with the given ID if it exists in the cache, else None

get_channel(id)

Returns a channel with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The returned channel or None if not found.

Return type:

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

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

Returns a PartialMessageable with the given channel ID. This is useful if you have the ID of a channel but don’t want to do an API call to send messages to it.

Parameters:
  • id (int) – The channel ID to create a PartialMessageable for.

  • guild_id (Optional[int]) – The optional guild ID to create a PartialMessageable for. This is not required to actually send messages, but it does allow the jump_url() and guild properties to function properly.

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

Returns:

The partial messageable created

Return type:

PartialMessageable

get_guild(id)

Returns a guild with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The guild or None if not found.

Return type:

Optional[Guild]

get_user(id)

Returns a user with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The user or None if not found.

Return type:

Optional[User]

get_emoji(id)

Returns an emoji with the given ID.

Parameters:

id (int) – The ID to search for.

Returns:

The custom emoji or None if not found.

Return type:

Optional[Emoji]

for ... in get_all_channels()

A generator that retrieves every abc.GuildChannel the client can ‘access’.

This is equivalent to:

for guild in client.guilds:
    for channel in guild.channels:
        yield channel

Note

Just because you receive a abc.GuildChannel does not mean that you can communicate in said channel. abc.GuildChannel.permissions_for() should be used for that.

Yields:

abc.GuildChannel – A channel the client can ‘access’.

for ... in get_all_members()

Returns a generator with every Member the client can see.

This is equivalent to:

for guild in client.guilds:
    for member in guild.members:
        yield member
Yields:

Member – A member the client can see.

await wait_until_ready()

This function is a coroutine.

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

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

This function is a coroutine.

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the first event that meets the requirements.

Examples

Waiting for a user reply:

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

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

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

Waiting for a thumbs up reaction from the message author:

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

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

        try:
            reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
        except asyncio.TimeoutError:
            await channel.send('👎')
        else:
            await channel.send('👍')
Parameters:
  • event (str) – The event name, similar to the event reference, but without the on_ prefix, to wait for.

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

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

Raises:

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

Returns:

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

Return type:

Any

property application_commands

Returns a list of any application command that is registered for the bot`

Type:

List[ApplicationCommand]

property global_application_commands

Returns a list of all global application commands that are registered for the bot

Note

This requires the bot running and all commands cached, otherwise the list will be empty

Returns:

A list of registered global application commands for the bot

Return type:

List[ApplicationCommand]

await change_presence(*, activity=None, status='online')

This function is a coroutine.

Changes the client’s presence.

Changed in version 2.0: Removed the afk parameter

Example

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

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

Raises:

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

await fetch_template(code)

This function is a coroutine.

Gets a Template from a discord.new URL or code.

Parameters:

code (Union[Template, str]) – The Discord Template Code or URL (must be a discord.new URL).

Raises:
  • .NotFound – The template is invalid.

  • .HTTPException – Getting the template failed.

Returns:

The template from the URL/code.

Return type:

Template

await fetch_guild(guild_id)

This function is a coroutine.

Retrieves a Guild from an ID.

Note

Using this, you will not receive Guild.channels, Guild.members, Member.activity and Member.voice per Member.

Note

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

Parameters:

guild_id (int) – The guild’s ID to fetch from.

Raises:
  • .Forbidden – You do not have access to the guild.

  • .HTTPException – Getting the guild failed.

Returns:

The guild from the ID.

Return type:

Guild

await create_guild(name, region=None, icon=None, *, code=None)

This function is a coroutine.

Creates a Guild.

Bot accounts in more than 10 guilds are not allowed to create guilds.

Parameters:
Raises:
  • .HTTPException – Guild creation failed.

  • .InvalidArgument – Invalid icon image format given. Must be PNG or JPG.

Returns:

The guild created. This is not the same guild that is added to cache.

Return type:

Guild

await fetch_invite(url, *, with_counts=True)

This function is a coroutine.

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

Note

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

Parameters:
Raises:
  • .NotFound – The invite has expired or is invalid.

  • .HTTPException – Getting the invite failed.

Returns:

The invite from the URL/ID.

Return type:

Invite

await delete_invite(invite)

This function is a coroutine.

Revokes an Invite, URL, or ID to an invite.

You must have the manage_channels permission in the associated guild to do this.

Parameters:

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

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

  • .NotFound – The invite is invalid or expired.

  • .HTTPException – Revoking the invite failed.

await fetch_widget(guild_id)

This function is a coroutine.

Gets a Widget from a guild ID.

Note

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

Parameters:

guild_id (int) – The ID of the guild.

Raises:
  • .Forbidden – The widget for this guild is disabled.

  • .HTTPException – Retrieving the widget failed.

Returns:

The guild’s widget.

Return type:

Widget

await application_info()

This function is a coroutine.

Retrieves the bot’s application information.

Raises:

.HTTPException – Retrieving the information failed somehow.

Returns:

The bot’s application information.

Return type:

AppInfo

await fetch_user(user_id)

This function is a coroutine.

Retrieves a User based on their ID. This can only be used by bot accounts. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

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

Parameters:

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

Raises:
  • .NotFound – A user with this ID does not exist.

  • .HTTPException – Fetching the user failed.

Returns:

The user you requested.

Return type:

User

await fetch_channel(channel_id)

This function is a coroutine.

Retrieves a abc.GuildChannel or abc.PrivateChannel with the specified ID.

Note

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

New in version 1.2.

Raises:
  • .InvalidData – An unknown channel type was received from Discord.

  • .HTTPException – Retrieving the channel failed.

  • .NotFound – Invalid Channel ID.

  • .Forbidden – You do not have permission to fetch this channel.

Returns:

The channel from the ID.

Return type:

Union[abc.GuildChannel, abc.PrivateChannel]

await fetch_webhook(webhook_id)

This function is a coroutine.

Retrieves a Webhook with the specified ID.

Raises:
  • .HTTPException – Retrieving the webhook failed.

  • .NotFound – Invalid webhook ID.

  • .Forbidden – You do not have permission to fetch this webhook.

Returns:

The webhook you requested.

Return type:

Webhook

await fetch_all_nitro_stickers()

This function is a coroutine.

Retrieves a list with all build-in StickerPack ‘s.

Returns:

A list containing all build-in sticker-packs.

Return type:

StickerPack

await fetch_voice_regions()

This function is a coroutine.

Returns a list of VoiceRegionInfo that can be used when creating or editing a VoiceChannel or StageChannel’s region.

Note

This method is an API call. For general usage, consider using the VoiceRegion enum instead.

Returns:

The voice regions that can be used.

Return type:

List[VoiceRegionInfo]

await create_test_entitlement(sku_id, target, owner_type=MISSING)

This function is a coroutine.

Note

This method is only temporary and probably will be removed with or even before a stable v2 release as discord is already redesigning the testing system based on developer feedback.

See https://github.com/discord/discord-api-docs/pull/6502 for more information.

Creates a test entitlement to a given SKU for a given guild or user. Discord will act as though that user or guild has entitlement to your premium offering.

After creating a test entitlement, you’ll need to reload your Discord client. After doing so, you’ll see that your server or user now has premium access.

Parameters:
  • sku_id (int) – The ID of the SKU to create a test entitlement for.

  • target (Union[User, Guild, Snowflake]) –

    The target to create a test entitlement for.

    This can be a user, guild or just the ID, if so the owner_type parameter must be set.

  • owner_type (str) – The type of the target, could be guild or user.

Returns:

The created test entitlement.

Return type:

Entitlement

await delete_test_entitlement(entitlement_id)

This function is a coroutine.

Note

This method is only temporary and probably will be removed with or even before a stable v2 release as discord is already redesigning the testing system based on developer feedback.

See https://github.com/discord/discord-api-docs/pull/6502 for more information.

Deletes a currently-active test entitlement. Discord will act as though that user or guild no longer has entitlement to your premium offering.

Parameters:

entitlement_id (int) – The ID of the entitlement to delete.

await fetch_entitlements(*, limit=100, user=None, guild=None, sku_ids=None, before=None, after=None, exclude_ended=False)

This function is a coroutine.

Parameters:
  • limit (int) – The maximum amount of entitlements to fetch. Defaults to 100.

  • user (Optional[User]) – The user to fetch entitlements for.

  • guild (Optional[Guild]) – The guild to fetch entitlements for.

  • sku_ids (Optional[List[int]]) – Optional list of SKU IDs to check entitlements for

  • before (Optional[Union[datetime.datetime, Snowflake]]) – Retrieve entitlements before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • after (Optional[Union[datetime.datetime, Snowflake]]) – Retrieve entitlements after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • exclude_ended (bool) – Whether ended entitlements should be fetched or not. Defaults to False.

Returns:

An iterator to fetch all entitlements for the current application.

Return type:

AsyncIterator

AutoShardedClient

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

Bases: Client

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

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

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

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

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

shard_ids

An optional list of shard_ids to launch the shards with.

Type:

Optional[List[int]]

property latency

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

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

Type:

float

property latencies

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

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

Type:

List[Tuple[int, float]]

get_shard(shard_id)

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

property shards

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

Type:

Mapping[int, ShardInfo]

await request_offline_members(*guilds)

This function is a coroutine.

Requests previously offline members from the guild to be filled up into the Guild.members cache. This function is usually not called. It should only be used if you have the fetch_offline_members parameter set to False.

When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if Guild.large is True.

Warning

This method is deprecated. Use Guild.chunk() instead.

Parameters:

*guilds (Guild) – An argument list of guilds to request offline members for.

Raises:

InvalidArgument – If any guild is unavailable in the collection.

await connect(*, reconnect=True)

This function is a coroutine.

Creates a websocket connection and lets the websocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated.

Parameters:

reconnect (bool) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).

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

  • .ConnectionClosed – The websocket connection has been terminated.

await close()

This function is a coroutine.

Closes the connection to Discord.

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

This function is a coroutine.

Changes the client’s presence.

Example:

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

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

  • afk (bool) – Indicates if you are going AFK. This allows the discord client to know how to handle push notifications better for you in case you are actually idle and not lying.

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

Raises:

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

is_ws_ratelimited()

bool: Whether the websocket is currently rate limited.

This can be useful to know when deciding whether you should query members using HTTP or via the gateway.

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

New in version 1.6.