Client Objects#
Bots#
- activity
- allowed_mentions
- application_flags
- application_id
- auto_sync_commands
- cached_messages
- cogs
- debug_guilds
- default_command_contexts
- default_command_integration_types
- description
- emojis
- extensions
- get_command
- guilds
- intents
- latency
- owner_id
- owner_ids
- persistent_views
- polls
- private_channels
- status
- stickers
- store_url
- user
- users
- voice_clients
- defadd_application_command
- defadd_check
- defadd_cog
- defadd_listener
- defadd_view
- @after_invoke
- @application_command
- asyncapplication_info
- asyncbefore_identify_hook
- @before_invoke
- asyncchange_presence
- @check
- @check_once
- defclear
- asyncclose
- defcommand
- asyncconnect
- asynccreate_dm
- defcreate_group
- asynccreate_guild
- asyncdelete_invite
- defentitlements
- @event
- asyncfetch_application
- asyncfetch_channel
- asyncfetch_guild
- deffetch_guilds
- asyncfetch_invite
- asyncfetch_premium_sticker_packs
- asyncfetch_role_connection_metadata_records
- asyncfetch_skus
- asyncfetch_stage_instance
- asyncfetch_sticker
- asyncfetch_template
- asyncfetch_user
- asyncfetch_webhook
- asyncfetch_widget
- defget_all_channels
- defget_all_members
- defget_application_command
- asyncget_application_context
- asyncget_autocomplete_context
- defget_channel
- defget_cog
- asyncget_desynced_commands
- defget_emoji
- defget_guild
- defget_message
- asyncget_or_fetch_user
- defget_partial_messageable
- defget_poll
- defget_stage_instance
- defget_sticker
- defget_user
- @group
- asyncinvoke_application_command
- defis_closed
- asyncis_owner
- defis_ready
- defis_ws_ratelimited
- @listen
- defload_extension
- defload_extensions
- asynclogin
- @message_command
- asyncon_application_command_error
- asyncon_error
- asyncprocess_application_commands
- asyncregister_command
- asyncregister_commands
- defreload_extension
- defremove_application_command
- defremove_check
- defremove_cog
- defremove_listener
- defrun
- @slash_command
- @slash_group
- asyncstart
- asyncsync_commands
- defunload_extension
- asyncupdate_role_connection_metadata_records
- @user_command
- asyncwait_for
- asyncwait_until_ready
- defwalk_application_commands
- class discord.Bot(description=None, *args, **options)[source]#
Represents a discord bot.
This class is a subclass of
discord.Client
and as a result anything that you can do with adiscord.Client
you can do with this bot.This class also subclasses
ApplicationCommandMixin
to provide the functionality to manage commands.New in version 2.0.
- owner_id#
The user ID that owns the bot. If this is not set and is then queried via
is_owner()
then it is fetched automatically usingapplication_info()
.- Type:
Optional[
int
]
- owner_ids#
The user IDs that owns the bot. This is similar to
owner_id
. If this is not set and the application is team based, then it is fetched automatically usingapplication_info()
. For performance reasons it is recommended to use aset
for the collection. You cannot set bothowner_id
andowner_ids
.New in version 1.3.
- Type:
Optional[Collection[
int
]]
- debug_guilds#
Guild IDs of guilds to use for testing commands. The bot will not create any global commands if debug guild IDs are passed.
New in version 2.0.
- Type:
Optional[List[
int
]]
- auto_sync_commands#
Whether to automatically sync slash commands. This will call
sync_commands()
indiscord.on_connect()
, and inprocess_application_commands
if the command is not found. Defaults toTrue
.New in version 2.0.
- Type:
- default_command_contexts#
The default context types that the bot will use for commands. Defaults to a set containing
InteractionContextType.guild
,InteractionContextType.bot_dm
, andInteractionContextType.private_channel
.New in version 2.6.
- Type:
Collection[
InteractionContextType
]
- default_command_integration_types#
The default integration types that the bot will use for commands. Defaults to a set containing
IntegrationType.guild_install
.New in version 2.6.
- Type:
Collection[
IntegrationType
]]
- @command(**kwargs)#
An alias for
application_command()
.Note
This decorator is overridden by
discord.ext.commands.Bot
.New in version 2.0.
- Returns:
A decorator that converts the provided method into an
ApplicationCommand
, adds it to the bot, then returns it.- Return type:
Callable[…,
ApplicationCommand
]
- @event(coro)#
A decorator that registers an event to listen to.
You can find more info about the events on the documentation below.
The events must be a coroutine, if not,
TypeError
is raised.Note
This replaces any default handlers. Developers are encouraged to use
listen()
for adding additional handlers instead ofevent()
unless default method replacement is intended.- Raises:
TypeError – The coroutine passed is not actually a coroutine.
Example
@client.event async def on_ready(): print('Ready!')
- @message_command(**kwargs)#
A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_application_command()
. This shortcut is made specifically forMessageCommand
.New in version 2.0.
- Returns:
A decorator that converts the provided method into a
MessageCommand
, adds it to the bot, then returns it.- Return type:
Callable[…,
MessageCommand
]
- @slash_command(**kwargs)#
A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_application_command()
. This shortcut is made specifically forSlashCommand
.New in version 2.0.
- Returns:
A decorator that converts the provided method into a
SlashCommand
, adds it to the bot, then returns it.- Return type:
Callable[…,
SlashCommand
]
- @user_command(**kwargs)#
A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_application_command()
. This shortcut is made specifically forUserCommand
.New in version 2.0.
- Returns:
A decorator that converts the provided method into a
UserCommand
, adds it to the bot, then returns it.- Return type:
Callable[…,
UserCommand
]
- @listen(name=..., once=False)#
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as
on_ready()
The functions being listened to must be a coroutine.
- Raises:
TypeError – The function being listened to is not a coroutine.
ValueError – The
name
(event name) does not start with ‘on_’
Example
@client.listen() async def on_message(message): print('one') # in some other file... @client.listen('on_message') async def my_message(message): print('two') # listen to the first event only @client.listen('on_ready', once=True) async def on_ready(): print('ready!')
Would print one and two in an unspecified order.
- property activity#
The activity being used upon logging in.
- Return type:
Optional[
BaseActivity
]
- add_application_command(command)#
Adds an
ApplicationCommand
into the internal list of commands.This is usually not called, instead the
command()
or other shortcut decorators are used instead.New in version 2.0.
- Parameters:
command (
ApplicationCommand
) – The command to add.- Return type:
- add_check(func, *, call_once=False)#
Adds a global check to the bot. This is the non-decorator interface to
check()
andcheck_once()
.- Parameters:
func – The function that was used as a global check.
call_once (
bool
) – If the function should only be called once perBot.invoke()
call.
- Return type:
- add_cog(cog, *, override=False)#
Adds a “cog” to the bot.
A cog is a class that has its own event listeners and commands.
Changed in version 2.0:
ClientException
is raised when a cog with the same name is already loaded.- Parameters:
- Raises:
ApplicationCommandError – An error happened during loading.
ClientException – A cog with the same name is already loaded.
- Return type:
- add_listener(func, name=...)#
The non decorator alternative to
listen()
.- Parameters:
- Raises:
TypeError – The
func
parameter is not a coroutine function.ValueError – The
name
(event name) does not start with ‘on_’
- Return type:
Example
async def on_ready(): pass async def my_message(message): pass client.add_listener(on_ready) client.add_listener(my_message, 'on_message')
- add_view(view, *, message_id=None)#
Registers a
View
for persistent listening.This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
- Parameters:
view (
discord.ui.View
) – The view to register for dispatching.message_id (Optional[
int
]) – The message ID that the view is attached to. This is currently used to refresh the view’s state during message update events. If not given then message update events are not propagated for the view.
- Raises:
TypeError – A view was not passed.
ValueError – The view is not persistent. A persistent view has no timeout and all their components have an explicitly provided
custom_id
.
- Return type:
None
- after_invoke(coro)#
A decorator that registers a coroutine as a post-invoke hook. A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required. This post-invoke hook takes a sole parameter, a
Context
.Note
Similar to
before_invoke()
, this is not called unless checks and argument parsing procedures succeed. This hook is, however, always called regardless of the internal command callback raising an error (i.e.CommandInvokeError
). This makes it ideal for clean-up scenarios.
- property allowed_mentions#
The allowed mention configuration.
New in version 1.4.
- application_command(**kwargs)#
A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_application_command()
.New in version 2.0.
- Returns:
A decorator that converts the provided method into an
ApplicationCommand
, adds it to the bot, then returns it.- Return type:
Callable[…,
ApplicationCommand
]
- property application_flags#
The client’s application flags.
New in version 2.0.
- property application_id#
The client’s application ID.
If this is not passed via
__init__
then this is retrieved through the gateway when an event contains the data. Usually afteron_connect()
is called.New in version 2.0.
- await application_info()#
This function is a coroutine.
Retrieves the bot’s application information.
- Returns:
The bot’s application information.
- Return type:
- Raises:
HTTPException – Retrieving the information failed somehow.
- 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.
- before_invoke(coro)#
A decorator that registers a coroutine as a pre-invoke hook. A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required. This pre-invoke hook takes a sole parameter, a
Context
.Note
The
before_invoke()
andafter_invoke()
hooks are only called if all checks and argument parsing procedures pass without error. If any check or argument parsing procedures fail then the hooks are not called.
- property cached_messages#
Read-only list of messages the connected client has cached.
New in version 1.1.
- await change_presence(*, activity=None, status=None)#
This function is a coroutine.
Changes the client’s presence.
- 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. IfNone
, thenStatus.online
is used.
- Raises:
InvalidArgument – If the
activity
parameter is not the proper type.
Example
game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game)
Changed in version 2.0: Removed the
afk
keyword-only parameter.
- check(func)#
A decorator that adds a global check to the bot. A global check is similar to a
check()
that is applied on a per-command basis except it is run before any command checks have been verified and applies to every command the bot has.Note
This function can either be a regular function or a coroutine. Similar to a command
check()
, this takes a single parameter of typeContext
and can only raise exceptions inherited fromApplicationCommandError
.Example
@bot.check def check_commands(ctx): return ctx.command.qualified_name in allowed_commands
- check_once(func)#
A decorator that adds a “call once” global check to the bot. Unlike regular global checks, this one is called only once per
Bot.invoke()
call. Regular global checks are called whenever a command is called orCommand.can_run()
is called. This type of check bypasses that and ensures that it’s called only once, even inside the default help command.Note
When using this function the
Context
sent to a group subcommand may only parse the parent command and not the subcommands due to it being invoked once perBot.invoke()
call.Note
This function can either be a regular function or a coroutine. Similar to a command
check()
, this takes a single parameter of typeContext
and can only raise exceptions inherited fromApplicationCommandError
.Example
@bot.check_once def whitelist(ctx): return ctx.message.author.id in my_whitelist
- clear()#
Clears the internal state of the bot.
After this, the bot can be considered “re-opened”, i.e.
is_closed()
andis_ready()
both returnFalse
along with the bot’s internal cache cleared.- Return type:
- property cogs#
A read-only mapping of cog name to cog.
- 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 – 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.
- Return type:
- await create_dm(user)#
This function is a coroutine.
Creates a
DMChannel
with this user.This should be rarely called, as this is done transparently for most people.
New in version 2.0.
- create_group(name, description=None, guild_ids=None, **kwargs)#
A shortcut method that creates a slash command group with no subcommands and adds it to the internal command list via
add_application_command()
.New in version 2.0.
- Parameters:
name (
str
) – The name of the group to create.description (Optional[
str
]) – The description of the group to create.guild_ids (Optional[List[
int
]]) – A list of the IDs of each guild this group should be added to, making it a guild command. This will be a global command ifNone
is passed.kwargs – Any additional keyword arguments to pass to
SlashCommandGroup
.
- Returns:
The slash command group that was created.
- Return type:
- await create_guild(*, name, icon=..., code=...)#
This function is a coroutine.
Creates a
Guild
.Bot accounts in more than 10 guilds are not allowed to create guilds.
- Parameters:
name (
str
) – The name of the guild.icon (Optional[
bytes
]) – The bytes-like object representing the icon. SeeClientUser.edit()
for more details on what is expected.code (
str
) –The code for a template to create the guild with.
New in version 1.4.
- Returns:
The guild created. This is not the same guild that is added to cache.
- Return type:
- Raises:
HTTPException – Guild creation failed.
InvalidArgument – Invalid icon image format given. Must be PNG or JPG.
- 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:
- Raises:
Forbidden – You do not have permissions to revoke invites.
NotFound – The invite is invalid or expired.
HTTPException – Revoking the invite failed.
- Return type:
None
- property emojis#
The emojis that the connected client has.
- entitlements(user=None, skus=None, before=None, after=None, limit=100, guild=None, exclude_ended=False)#
Returns an
AsyncIterator
that enables fetching the application’s entitlements.New in version 2.6.
- Parameters:
user (
abc.Snowflake
| None) – Limit the fetched entitlements to entitlements owned by this user.skus (list[
abc.Snowflake
] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake
|datetime.datetime
| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake
|datetime.datetime
| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int
]) – The number of entitlements to retrieve. IfNone
, retrieves every entitlement, which may be slow. Defaults to100
.guild (
abc.Snowflake
| None) – Limit the fetched entitlements to entitlements owned by this guild.exclude_ended (
bool
) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse
.
- Yields:
Entitlement
– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- Return type:
EntitlementIterator
Examples
Usage
async for entitlement in client.entitlements(): print(entitlement.user_id)
Flattening into a list
entitlements = await user.entitlements().flatten()
All parameters are optional.
- property extensions#
A read-only mapping of extension name to extension.
- await fetch_application(application_id, /)#
This function is a coroutine. Retrieves a
PartialAppInfo
from an application ID.- Parameters:
application_id (
int
) – The application ID to retrieve information from.- Returns:
The application information.
- Return type:
- Raises:
NotFound – An application with this ID does not exist.
HTTPException – Retrieving the application failed.
- await fetch_channel(channel_id, /)#
This function is a coroutine.
Retrieves a
abc.GuildChannel
,abc.PrivateChannel
, orThread
with the specified ID.Note
This method is an API call. For general usage, consider
get_channel()
instead.New in version 1.2.
- Returns:
The channel from the ID.
- Return type:
Union[
abc.GuildChannel
,abc.PrivateChannel
,Thread
]- 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.
- Parameters:
channel_id (int) –
- await fetch_guild(guild_id, /, *, with_counts=True)#
This function is a coroutine.
Retrieves a
Guild
from an ID.Note
Using this, you will not receive
Guild.channels
,Guild.members
,Member.activity
andMember.voice
perMember
.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.with_counts (
bool
) –Whether to include count information in the guild. This fills the
Guild.approximate_member_count
andGuild.approximate_presence_count
fields.New in version 2.0.
- Returns:
The guild from the ID.
- Return type:
- Raises:
Forbidden – You do not have access to the guild.
HTTPException – Getting the guild failed.
- 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
, andGuild.name
perGuild
.Note
This method is an API call. For general usage, consider
guilds
instead.- Parameters:
limit (Optional[
int
]) – The number of guilds to retrieve. IfNone
, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to100
.before (Union[
abc.Snowflake
,datetime.datetime
]) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Union[
abc.Snowflake
,datetime.datetime
]) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
Guild
– The guild with the guild data parsed.- Raises:
HTTPException – Getting the guilds failed.
- Return type:
GuildIterator
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.
- await fetch_invite(url, *, with_counts=True, with_expiration=True, event_id=None)#
This function is a coroutine.
Gets an
Invite
from a discord.gg URL or ID.Note
If the invite is for a guild you have not joined, the guild and channel attributes of the returned
Invite
will bePartialInviteGuild
andPartialInviteChannel
respectively.- Parameters:
url (Union[
Invite
,str
]) – The Discord invite ID or URL (must be a discord.gg URL).with_counts (
bool
) – Whether to include count information in the invite. This fills theInvite.approximate_member_count
andInvite.approximate_presence_count
fields.with_expiration (
bool
) –Whether to include the expiration date of the invite. This fills the
Invite.expires_at
field.New in version 2.0.
event_id (Optional[
int
]) –The ID of the scheduled event to be associated with the event.
See
Invite.set_scheduled_event()
for more info on event invite linking.New in version 2.0.
- Returns:
The invite from the URL/ID.
- Return type:
- Raises:
NotFound – The invite has expired or is invalid.
HTTPException – Getting the invite failed.
This function is a coroutine.
Retrieves all available premium sticker packs.
New in version 2.0.
- Returns:
All available premium sticker packs.
- Return type:
List[
StickerPack
]- Raises:
HTTPException – Retrieving the sticker packs failed.
- await fetch_role_connection_metadata_records()#
This function is a coroutine.
Fetches the bot’s role connection metadata records.
New in version 2.4.
- Returns:
The bot’s role connection metadata records.
- Return type:
- await fetch_skus()#
This function is a coroutine.
Fetches the bot’s SKUs.
New in version 2.5.
- Returns:
The bot’s SKUs.
- Return type:
List[
SKU
]
- await fetch_stage_instance(channel_id, /)#
This function is a coroutine.
Gets a
StageInstance
for a stage channel id.New in version 2.0.
- Parameters:
channel_id (
int
) – The stage channel ID.- Returns:
The stage instance from the stage channel ID.
- Return type:
- Raises:
NotFound – The stage instance or channel could not be found.
HTTPException – Getting the stage instance failed.
- await fetch_sticker(sticker_id, /)#
This function is a coroutine.
Retrieves a
Sticker
with the specified ID.New in version 2.0.
- Returns:
The sticker you requested.
- Return type:
Union[
StandardSticker
,GuildSticker
]- Raises:
HTTPException – Retrieving the sticker failed.
NotFound – Invalid sticker ID.
- Parameters:
sticker_id (int) –
- 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).- Returns:
The template from the URL/code.
- Return type:
- Raises:
NotFound – The template is invalid.
HTTPException – Getting the template failed.
- await fetch_user(user_id, /)#
This function is a coroutine.
Retrieves a
User
based on their ID. 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
discord.Intents.members
and member cache enabled, considerget_user()
instead.- Parameters:
user_id (
int
) – The user’s ID to fetch from.- Returns:
The user you requested.
- Return type:
- Raises:
NotFound – A user with this ID does not exist.
HTTPException – Fetching the user failed.
- await fetch_webhook(webhook_id, /)#
This function is a coroutine.
Retrieves a
Webhook
with the specified ID.- Returns:
The webhook you requested.
- Return type:
- Raises:
HTTPException – Retrieving the webhook failed.
NotFound – Invalid webhook ID.
Forbidden – You do not have permission to fetch this webhook.
- Parameters:
webhook_id (
int
) –
- 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.- Returns:
The guild’s widget.
- Return type:
- Raises:
Forbidden – The widget for this guild is disabled.
HTTPException – Retrieving the widget failed.
- 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
- Return type:
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
- get_application_command(name, guild_ids=None, type=<class 'discord.commands.core.ApplicationCommand'>)#
Get an
ApplicationCommand
from the internal list of commands.New in version 2.0.
- Parameters:
name (
str
) – The qualified name of the command to get.guild_ids (List[
int
]) – The guild ids associated to the command to get.type (Type[
ApplicationCommand
]) – The type of the command to get. Defaults toApplicationCommand
.
- Returns:
The command that was requested. If not found, returns
None
.- Return type:
Optional[
ApplicationCommand
]
- await get_application_context(interaction, cls=<class 'discord.commands.context.ApplicationContext'>)#
This function is a coroutine.
Returns the invocation context from the interaction.
This is a more low-level counter-part for
process_application_commands()
to allow users more fine-grained control over the processing.- Parameters:
interaction (
discord.Interaction
) – The interaction to get the invocation context from.cls (
Any
) – The factory class that will be used to create the context. By default, this isApplicationContext
. Should a custom class be provided, it must be similar enough toApplicationContext
's interface.
- Returns:
The invocation context. The type of this can change via the
cls
parameter.- Return type:
- await get_autocomplete_context(interaction, cls=<class 'discord.commands.context.AutocompleteContext'>)#
This function is a coroutine.
Returns the autocomplete context from the interaction.
This is a more low-level counter-part for
process_application_commands()
to allow users more fine-grained control over the processing.- Parameters:
interaction (
discord.Interaction
) – The interaction to get the invocation context from.cls (
Any
) – The factory class that will be used to create the context. By default, this isAutocompleteContext
. Should a custom class be provided, it must be similar enough toAutocompleteContext
's interface.
- Returns:
The autocomplete context. The type of this can change via the
cls
parameter.- Return type:
- get_channel(id, /)#
Returns a channel or thread 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
,Thread
,abc.PrivateChannel
]]
- get_cog(name)#
Gets the cog instance requested.
If the cog is not found,
None
is returned instead.
- property get_command#
Shortcut for
get_application_command()
.Note
Overridden in
ext.commands.Bot
.New in version 2.0.
- await get_desynced_commands(guild_id=None, prefetched=None)#
This function is a coroutine.
Gets the list of commands that are desynced from discord. If
guild_id
is specified, it will only return guild commands that are desynced from said guild, else it will return global commands.Note
This function is meant to be used internally, and should only be used if you want to override the default command registration behavior.
New in version 2.0.
- Parameters:
guild_id (Optional[
int
]) – The guild id to get the desynced commands for, else global commands if unspecified.prefetched (Optional[List[
ApplicationCommand
]]) – If you already fetched the commands, you can pass them here to be used. Not recommended for typical usage.
- Returns:
A list of the desynced commands. Each will come with at least the
cmd
andaction
keys, which respectively contain the command and the action to perform. Other keys may also be present depending on the action, includingid
.- Return type:
List[Dict[
str
, Any]]
- get_emoji(id, /)#
Returns an emoji with the given ID.
- get_guild(id, /)#
Returns a guild with the given ID.
- get_message(id, /)#
Returns a message the given ID.
This is useful if you have a message_id but don’t want to do an API call to access the message.
- await get_or_fetch_user(id, /)#
This function is a coroutine.
Looks up a user in the user cache or fetches if not found.
- get_partial_messageable(id, *, type=None)#
Returns a partial messageable with the given channel ID.
This is useful if you have a channel_id but don’t want to do an API call to send messages to it.
New in version 2.0.
- Parameters:
id (
int
) – The channel ID to create a partial messageable for.type (Optional[
ChannelType
]) – The underlying channel type for the partial messageable.
- Returns:
The partial messageable
- Return type:
- get_poll(id, /)#
Returns a poll attached to the given message ID.
- get_stage_instance(id, /)#
Returns a stage instance with the given stage channel ID.
New in version 2.0.
- Parameters:
id (
int
) – The ID to search for.- Returns:
The stage instance or
None
if not found.- Return type:
Optional[
StageInstance
]
- get_sticker(id, /)#
Returns a guild sticker with the given ID.
New in version 2.0.
Note
To retrieve standard stickers, use
fetch_sticker()
. orfetch_premium_sticker_packs()
.- Returns:
The sticker or
None
if not found.- Return type:
Optional[
GuildSticker
]- Parameters:
id (int) –
- get_user(id, /)#
Returns a user with the given ID.
- group(name=None, description=None, guild_ids=None)#
A shortcut decorator that initializes the provided subclass of
SlashCommandGroup
and adds it to the internal command list viaadd_application_command()
.New in version 2.0.
- Parameters:
name (Optional[
str
]) – The name of the group to create. This will resolve to the name of the decorated class ifNone
is passed.description (Optional[
str
]) – The description of the group to create.guild_ids (Optional[List[
int
]]) – A list of the IDs of each guild this group should be added to, making it a guild command. This will be a global command ifNone
is passed.
- Returns:
The slash command group that was created.
- Return type:
Callable[[Type[SlashCommandGroup]], SlashCommandGroup]
- property guilds#
The guilds that the connected client is a member of.
- property intents#
The intents configured for this connection.
New in version 1.5.
- await invoke_application_command(ctx)#
This function is a coroutine.
Invokes the application command given under the invocation context and handles all the internal event dispatch mechanisms.
- Parameters:
ctx (
ApplicationCommand
) – The invocation context to invoke.- Return type:
- await is_owner(user)#
This function is a coroutine.
Checks if a
User
orMember
is the owner of this bot.If an
owner_id
is not set, it is fetched automatically through the use ofapplication_info()
.Changed in version 1.3: The function also checks if the application is team-owned if
owner_ids
is not set.
- is_ws_ratelimited()#
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. :rtype:
bool
New in version 1.6.
- property latency#
Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
- load_extension(name, *, package=None, recursive=False, store=False)#
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function,
setup
defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, thebot
.The extension passed can either be the direct name of a file within the current working directory or a folder that contains multiple extensions.
- Parameters:
name (
str
) – The extension or folder name to load. It must be dot separated like regular Python imports if accessing a submodule. e.g.foo.test
if you want to importfoo/test.py
.package (Optional[
str
]) –The package name to resolve relative imports with. This is required when loading an extension using a relative path, e.g
.foo.test
. Defaults toNone
.New in version 1.7.
recursive (Optional[
bool
]) –If subdirectories under the given head directory should be recursively loaded. Defaults to
False
.New in version 2.0.
store (Optional[
bool
]) –If exceptions should be stored or raised. If set to
True
, all exceptions encountered will be stored in a returned dictionary as a load status. If set toFalse
, if any exceptions are encountered they will be raised and the bot will be closed. If no exceptions are encountered, a list of loaded extension names will be returned. Defaults toFalse
.New in version 2.0.
- Returns:
If the store parameter is set to
True
, a dictionary will be returned that contains keys to represent the loaded extension names. The values bound to each key can either be an exception that occurred when loading that extension or aTrue
boolean representing a successful load. If the store parameter is set toFalse
, either a list containing a list of loaded extensions or nothing due to an encountered exception.- Return type:
Optional[Union[Dict[
str
, Union[errors.ExtensionError
,bool
]], List[str
]]]- Raises:
ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided
package
parameter.ExtensionAlreadyLoaded – The extension is already loaded.
NoEntryPointError – The extension does not have a setup function.
ExtensionFailed – The extension or its setup function had an execution error.
- load_extensions(*names, package=None, recursive=False, store=False)#
Loads multiple extensions at once.
This method simplifies the process of loading multiple extensions by handling the looping of
load_extension
.- Parameters:
names (
str
) – The extension or folder names to load. It must be dot separated like regular Python imports if accessing a submodule. e.g.foo.test
if you want to importfoo/test.py
.package (Optional[
str
]) –The package name to resolve relative imports with. This is required when loading an extension using a relative path, e.g
.foo.test
. Defaults toNone
.New in version 1.7.
recursive (Optional[
bool
]) –If subdirectories under the given head directory should be recursively loaded. Defaults to
False
.New in version 2.0.
store (Optional[
bool
]) –If exceptions should be stored or raised. If set to
True
, all exceptions encountered will be stored in a returned dictionary as a load status. If set toFalse
, if any exceptions are encountered they will be raised and the bot will be closed. If no exceptions are encountered, a list of loaded extension names will be returned. Defaults toFalse
.New in version 2.0.
- Returns:
If the store parameter is set to
True
, a dictionary will be returned that contains keys to represent the loaded extension names. The values bound to each key can either be an exception that occurred when loading that extension or aTrue
boolean representing a successful load. If the store parameter is set toFalse
, either a list containing names of loaded extensions or nothing due to an encountered exception.- Return type:
Optional[Union[Dict[
str
, Union[errors.ExtensionError
,bool
]], List[str
]]]- Raises:
ExtensionNotFound – A given extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided
package
parameter.ExtensionAlreadyLoaded – A given extension is already loaded.
NoEntryPointError – A given extension does not have a setup function.
ExtensionFailed – A given extension or its setup function had an execution error.
- await login(token)#
This function is a coroutine.
Logs in the client with the specified credentials.
- Parameters:
token (
str
) – The authentication token. Do not prefix this token with anything as the library will do it for you.- Raises:
TypeError – The token was in invalid type.
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.
- Return type:
- await on_application_command_error(context, exception)#
This function is a coroutine.
The default command error handler provided by the bot.
By default, this prints to
sys.stderr
however it could be overridden to have a different implementation.This only fires if you do not specify any listeners for command error.
- Parameters:
context (
ApplicationContext
) –exception (
DiscordException
) –
- Return type:
- 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. Checkon_error()
for more details.
- property persistent_views#
A sequence of persistent views added to the client.
New in version 2.0.
- property polls#
The polls that the connected client has.
New in version 2.6.
- 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.
- await process_application_commands(interaction, auto_sync=None)#
This function is a coroutine.
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the
on_interaction()
event. If you choose to override theon_interaction()
event, then you should invoke this coroutine as well.This function finds a registered command matching the interaction id from application commands and invokes it. If no matching command was found, it replies to the interaction with a default message.
New in version 2.0.
- Parameters:
interaction (
discord.Interaction
) – The interaction to processauto_sync (Optional[
bool
]) – Whether to automatically sync and unregister the command if it is not found in the internal cache. This will invoke thesync_commands()
method on the context of the command, either globally or per-guild, based on the type of the command, respectively. Defaults toBot.auto_sync_commands
.
- Return type:
None
- await register_command(command, force=True, guild_ids=None)#
This function is a coroutine.
Registers a command. If the command has
guild_ids
set, or if theguild_ids
parameter is passed, the command will be registered as a guild command for those guilds.- Parameters:
command (
ApplicationCommand
) – The command to register.force (
bool
) – Whether to force the command to be registered. If this is set to False, the command will only be registered if it seems to already be registered and up to date with our internal cache. Defaults to True.guild_ids (
list
) – A list of guild ids to register the command for. If this is not set, the command’sApplicationCommand.guild_ids
attribute will be used.
- Returns:
The command that was registered
- Return type:
- await register_commands(commands=None, guild_id=None, method='bulk', force=False, delete_existing=True)#
This function is a coroutine.
Register a list of commands.
New in version 2.0.
- Parameters:
commands (Optional[List[
ApplicationCommand
]]) – A list of commands to register. If this is not set (None
), then all commands will be registered.guild_id (Optional[int]) – If this is set, the commands will be registered as a guild command for the respective guild. If it is not set, the commands will be registered according to their
ApplicationCommand.guild_ids
attribute.method (Literal['individual', 'bulk', 'auto']) – The method to use when registering the commands. If this is set to “individual”, then each command will be registered individually. If this is set to “bulk”, then all commands will be registered in bulk. If this is set to “auto”, then the method will be determined automatically. Defaults to “bulk”.
force (
bool
) – Registers the commands regardless of the state of the command on Discord. This uses one less API call, but can result in hitting rate limits more often. Defaults to False.delete_existing (
bool
) – Whether to delete existing commands that are not in the list of commands to register. Defaults to True.
- reload_extension(name, *, package=None)#
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a
unload_extension()
followed by aload_extension()
except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll back to the prior working state.- Parameters:
name (
str
) – The extension name to reload. It must be dot separated like regular Python imports if accessing a submodule. e.g.foo.test
if you want to importfoo/test.py
.package (Optional[
str
]) –The package name to resolve relative imports with. This is required when reloading an extension using a relative path, e.g
.foo.test
. Defaults toNone
.New in version 1.7.
- Raises:
ExtensionNotLoaded – The extension was not loaded.
ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided
package
parameter.NoEntryPointError – The extension does not have a setup function.
ExtensionFailed – The extension setup function had an execution error.
- Return type:
None
- remove_application_command(command)#
Remove an
ApplicationCommand
from the internal list of commands.New in version 2.0.
- Parameters:
command (
ApplicationCommand
) – The command to remove.- Returns:
The command that was removed. If the command has not been added,
None
is returned instead.- Return type:
Optional[
ApplicationCommand
]
- remove_check(func, *, call_once=False)#
Removes a global check from the bot. This function is idempotent and will not raise an exception if the function is not in the global checks.
- Parameters:
func – The function to remove from the global checks.
call_once (
bool
) – If the function was added withcall_once=True
in theBot.add_check()
call or usingcheck_once()
.
- Return type:
- remove_cog(name)#
Removes a cog from the bot and returns it.
All registered commands and event listeners that the cog has registered will be removed as well.
If no cog is found then this method has no effect.
- remove_listener(func, name=...)#
Removes a listener from the pool of listeners.
- run(*args, **kwargs)#
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 orconnect()
+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()
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.
- slash_group(name=None, description=None, guild_ids=None)#
A shortcut decorator that initializes the provided subclass of
SlashCommandGroup
and adds it to the internal command list viaadd_application_command()
.New in version 2.0.
- Parameters:
name (Optional[
str
]) – The name of the group to create. This will resolve to the name of the decorated class ifNone
is passed.description (Optional[
str
]) – The description of the group to create.guild_ids (Optional[List[
int
]]) – A list of the IDs of each guild this group should be added to, making it a guild command. This will be a global command ifNone
is passed.
- Returns:
The slash command group that was created.
- Return type:
Callable[[Type[SlashCommandGroup]], SlashCommandGroup]
- property status#
The status being used upon logging on to Discord.
- property stickers#
The stickers that the connected client has.
New in version 2.0.
- property store_url#
The URL that leads to the application’s store page for monetization.
New in version 2.6.
- Type:
- await sync_commands(commands=None, method='bulk', force=False, guild_ids=None, register_guild_commands=True, check_guilds=[], delete_existing=True)#
This function is a coroutine.
Registers all commands that have been added through
add_application_command()
. This method cleans up all commands over the API and should sync them with the internal cache of commands. It attempts to register the commands in the most efficient way possible, unlessforce
is set toTrue
, in which case it will always register all commands.By default, this coroutine is called inside the
on_connect()
event. If you choose to override theon_connect()
event, then you should invoke this coroutine as well such as the following:@bot.event async def on_connect(): if bot.auto_sync_commands: await bot.sync_commands() print(f"{bot.user.name} connected.")
Note
If you remove all guild commands from a particular guild, the library may not be able to detect and update the commands accordingly, as it would have to individually check for each guild. To force the library to unregister a guild’s commands, call this function with
commands=[]
andguild_ids=[guild_id]
.New in version 2.0.
- Parameters:
commands (Optional[List[
ApplicationCommand
]]) – A list of commands to register. If this is not set (None), then all commands will be registered.method (Literal['individual', 'bulk', 'auto']) – The method to use when registering the commands. If this is set to “individual”, then each command will be registered individually. If this is set to “bulk”, then all commands will be registered in bulk. If this is set to “auto”, then the method will be determined automatically. Defaults to “bulk”.
force (
bool
) – Registers the commands regardless of the state of the command on Discord. This uses one less API call, but can result in hitting rate limits more often. Defaults to False.guild_ids (Optional[List[
int
]]) – A list of guild ids to register the commands for. If this is not set, the commands’guild_ids
attribute will be used.register_guild_commands (
bool
) – Whether to register guild commands. Defaults to True.check_guilds (Optional[List[
int
]]) – A list of guilds ids to check for commands to unregister, since the bot would otherwise have to check all guilds. Unlikeguild_ids
, this does not alter the commands’guild_ids
attribute, instead it adds the guild ids to a list of guilds to sync commands for. Ifregister_guild_commands
is set to False, then this parameter is ignored.delete_existing (
bool
) – Whether to delete existing commands that are not in the list of commands to register. Defaults to True.
- unload_extension(name, *, package=None)#
Unloads an extension.
When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported.
The extension can provide an optional global function,
teardown
, to do miscellaneous clean-up if necessary. This function takes a single parameter, thebot
, similar tosetup
fromload_extension()
.- Parameters:
name (
str
) – The extension name to unload. It must be dot separated like regular Python imports if accessing a submodule. e.g.foo.test
if you want to importfoo/test.py
.package (Optional[
str
]) –The package name to resolve relative imports with. This is required when unloading an extension using a relative path, e.g
.foo.test
. Defaults toNone
.New in version 1.7.
- Raises:
ExtensionNotFound – The name of the extension could not be resolved using the provided
package
parameter.ExtensionNotLoaded – The extension was not loaded.
- Return type:
None
- await update_role_connection_metadata_records(*role_connection_metadata)#
This function is a coroutine.
Updates the bot’s role connection metadata records.
New in version 2.4.
- Parameters:
*role_connection_metadata (
ApplicationRoleConnectionMetadata
) – The new metadata records to send to Discord.- Returns:
The updated role connection metadata records.
- Return type:
- property user#
Represents the connected client.
None
if not logged in.
- property users#
Returns a list of all the users the bot can see.
- property voice_clients#
Represents a list of voice connections.
These are usually
VoiceClient
instances.
- 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 ontoasyncio.wait_for()
. By default, it does not timeout. Note that this does propagate theasyncio.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.
- Parameters:
event (
str
) – The event name, similar to the event reference, but without theon_
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 raisingasyncio.TimeoutError
.
- 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
- Raises:
asyncio.TimeoutError – Raised if a timeout is provided and reached.
Examples
Waiting for a user reply:
@client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send(f'Hello {msg.author}!')
Waiting for a thumbs up reaction from the message author:
@client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that 👍 reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '👍' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('👎') else: await channel.send('👍')
- await wait_until_ready()#
This function is a coroutine.
Waits until the client’s internal cache is all ready.
- Return type:
- for ... in walk_application_commands()#
An iterator that recursively walks through all application commands and subcommands.
- Yields:
ApplicationCommand
– An application command from the internal list of application commands.- Return type:
- class discord.AutoShardedBot(description=None, *args, **options)[source]#
This is similar to
Bot
except that it is inherited fromdiscord.AutoShardedClient
instead.New in version 2.0.
Clients#
- defadd_listener
- defadd_view
- asyncapplication_info
- asyncbefore_identify_hook
- asyncchange_presence
- defclear
- asyncclose
- asyncconnect
- asynccreate_dm
- asynccreate_guild
- asyncdelete_invite
- defentitlements
- @event
- asyncfetch_application
- asyncfetch_channel
- asyncfetch_guild
- deffetch_guilds
- asyncfetch_invite
- asyncfetch_premium_sticker_packs
- asyncfetch_role_connection_metadata_records
- asyncfetch_skus
- asyncfetch_stage_instance
- asyncfetch_sticker
- asyncfetch_template
- asyncfetch_user
- asyncfetch_webhook
- asyncfetch_widget
- defget_all_channels
- defget_all_members
- defget_channel
- defget_emoji
- defget_guild
- defget_message
- asyncget_or_fetch_user
- defget_partial_messageable
- defget_poll
- defget_stage_instance
- defget_sticker
- defget_user
- defis_closed
- defis_ready
- defis_ws_ratelimited
- @listen
- asynclogin
- asyncon_error
- defremove_listener
- defrun
- asyncstart
- asyncupdate_role_connection_metadata_records
- asyncwait_for
- asyncwait_until_ready
- class discord.Client(*, loop=None, **options)[source]#
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 inNone
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
]) – Theasyncio.AbstractEventLoop
to use for asynchronous operations. Defaults toNone
, in which case the default event loop is used viaasyncio.get_event_loop()
.connector (Optional[
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 at0
and less thanshard_count
.shard_count (Optional[
int
]) – The total number of shards.application_id (
int
) – The client’s application ID.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.New in version 1.5.
member_cache_flags (
MemberCacheFlags
) –Allows for finer control over how the library caches members. If not given, defaults to cache as much as possible with the currently selected intents.
New in version 1.5.
chunk_guilds_at_startup (
bool
) –Indicates if
on_ready()
should be delayed to chunk all guilds at start-up if necessary. This operation is incredibly slow for large amounts of guilds. The default isTrue
ifIntents.members
isTrue
.New in version 1.5.
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.
New in version 1.4.
heartbeat_timeout (
float
) – The maximum numbers of seconds before timing out and restarting the WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful if processing the initial packets take too long to the point of disconnecting you. The default timeout is 60 seconds.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.
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 isFalse
then your system clock is used to calculate how long to sleep for. If this is set toFalse
it is recommended to sync your system clock to Google’s NTP server.New in version 1.3.
enable_debug_events (
bool
) –Whether to enable events that are useful only for debugging gateway related information.
Right now this involves
on_socket_raw_receive()
andon_socket_raw_send()
. If this isFalse
then those events will not be dispatched (due to performance considerations). To enable these events, this must be set toTrue
. Defaults toFalse
.New in version 2.0.
- ws#
The WebSocket gateway the client is currently connected to. Could be
None
.
- loop#
The event loop that the client uses for asynchronous operations.
- Parameters:
options (Any) –
- @event(coro)[source]#
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.Note
This replaces any default handlers. Developers are encouraged to use
listen()
for adding additional handlers instead ofevent()
unless default method replacement is intended.- Raises:
TypeError – The coroutine passed is not actually a coroutine.
Example
@client.event async def on_ready(): print('Ready!')
- async for ... in fetch_guilds(*, limit=100, before=None, after=None)[source]#
Retrieves an
AsyncIterator
that enables receiving your guilds.Note
Using this, you will only receive
Guild.owner
,Guild.icon
,Guild.id
, andGuild.name
perGuild
.Note
This method is an API call. For general usage, consider
guilds
instead.- Parameters:
limit (Optional[
int
]) – The number of guilds to retrieve. IfNone
, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to100
.before (Union[
abc.Snowflake
,datetime.datetime
]) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Union[
abc.Snowflake
,datetime.datetime
]) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
Guild
– The guild with the guild data parsed.- Raises:
HTTPException – Getting the guilds failed.
- Return type:
GuildIterator
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.
- @listen(name=..., once=False)[source]#
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as
on_ready()
The functions being listened to must be a coroutine.
- Raises:
TypeError – The function being listened to is not a coroutine.
ValueError – The
name
(event name) does not start with ‘on_’
Example
@client.listen() async def on_message(message): print('one') # in some other file... @client.listen('on_message') async def my_message(message): print('two') # listen to the first event only @client.listen('on_ready', once=True) async def on_ready(): print('ready!')
Would print one and two in an unspecified order.
- property latency#
Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
- is_ws_ratelimited()[source]#
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. :rtype:
bool
New in version 1.6.
- property user#
Represents the connected client.
None
if not logged in.
- property guilds#
The guilds that the connected client is a member of.
- property emojis#
The emojis that the connected client has.
- property stickers#
The stickers that the connected client has.
New in version 2.0.
- property polls#
The polls that the connected client has.
New in version 2.6.
- property cached_messages#
Read-only list of messages the connected client has cached.
New in version 1.1.
- 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.
- property voice_clients#
Represents a list of voice connections.
These are usually
VoiceClient
instances.
- property application_id#
The client’s application ID.
If this is not passed via
__init__
then this is retrieved through the gateway when an event contains the data. Usually afteron_connect()
is called.New in version 2.0.
- property application_flags#
The client’s application flags.
New in version 2.0.
- await on_error(event_method, *args, **kwargs)[source]#
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. Checkon_error()
for more details.
- await before_identify_hook(shard_id, *, initial=False)[source]#
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.
- await login(token)[source]#
This function is a coroutine.
Logs in the client with the specified credentials.
- Parameters:
token (
str
) – The authentication token. Do not prefix this token with anything as the library will do it for you.- Raises:
TypeError – The token was in invalid type.
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.
- Return type:
- await connect(*, reconnect=True)[source]#
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 – 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.
- Return type:
- clear()[source]#
Clears the internal state of the bot.
After this, the bot can be considered “re-opened”, i.e.
is_closed()
andis_ready()
both returnFalse
along with the bot’s internal cache cleared.- Return type:
- run(*args, **kwargs)[source]#
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 orconnect()
+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()
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.
- property activity#
The activity being used upon logging in.
- Return type:
Optional[
BaseActivity
]
- property status#
The status being used upon logging on to Discord.
- property allowed_mentions#
The allowed mention configuration.
New in version 1.4.
- property intents#
The intents configured for this connection.
New in version 1.5.
- property users#
Returns a list of all the users the bot can see.
- await fetch_application(application_id, /)[source]#
This function is a coroutine. Retrieves a
PartialAppInfo
from an application ID.- Parameters:
application_id (
int
) – The application ID to retrieve information from.- Returns:
The application information.
- Return type:
- Raises:
NotFound – An application with this ID does not exist.
HTTPException – Retrieving the application failed.
- get_channel(id, /)[source]#
Returns a channel or thread 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
,Thread
,abc.PrivateChannel
]]
- get_message(id, /)[source]#
Returns a message the given ID.
This is useful if you have a message_id but don’t want to do an API call to access the message.
- get_partial_messageable(id, *, type=None)[source]#
Returns a partial messageable with the given channel ID.
This is useful if you have a channel_id but don’t want to do an API call to send messages to it.
New in version 2.0.
- Parameters:
id (
int
) – The channel ID to create a partial messageable for.type (Optional[
ChannelType
]) – The underlying channel type for the partial messageable.
- Returns:
The partial messageable
- Return type:
- get_stage_instance(id, /)[source]#
Returns a stage instance with the given stage channel ID.
New in version 2.0.
- Parameters:
id (
int
) – The ID to search for.- Returns:
The stage instance or
None
if not found.- Return type:
Optional[
StageInstance
]
- get_sticker(id, /)[source]#
Returns a guild sticker with the given ID.
New in version 2.0.
Note
To retrieve standard stickers, use
fetch_sticker()
. orfetch_premium_sticker_packs()
.- Returns:
The sticker or
None
if not found.- Return type:
Optional[
GuildSticker
]- Parameters:
id (int) –
- for ... in get_all_channels()[source]#
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
- Return type:
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()[source]#
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
- await get_or_fetch_user(id, /)[source]#
This function is a coroutine.
Looks up a user in the user cache or fetches if not found.
- await wait_until_ready()[source]#
This function is a coroutine.
Waits until the client’s internal cache is all ready.
- Return type:
- wait_for(event, *, check=None, timeout=None)[source]#
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 ontoasyncio.wait_for()
. By default, it does not timeout. Note that this does propagate theasyncio.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.
- Parameters:
event (
str
) – The event name, similar to the event reference, but without theon_
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 raisingasyncio.TimeoutError
.
- 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
- Raises:
asyncio.TimeoutError – Raised if a timeout is provided and reached.
Examples
Waiting for a user reply:
@client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send(f'Hello {msg.author}!')
Waiting for a thumbs up reaction from the message author:
@client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that 👍 reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '👍' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('👎') else: await channel.send('👍')
- add_listener(func, name=...)[source]#
The non decorator alternative to
listen()
.- Parameters:
- Raises:
TypeError – The
func
parameter is not a coroutine function.ValueError – The
name
(event name) does not start with ‘on_’
- Return type:
Example
async def on_ready(): pass async def my_message(message): pass client.add_listener(on_ready) client.add_listener(my_message, 'on_message')
- await change_presence(*, activity=None, status=None)[source]#
This function is a coroutine.
Changes the client’s presence.
- 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. IfNone
, thenStatus.online
is used.
- Raises:
InvalidArgument – If the
activity
parameter is not the proper type.
Example
game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game)
Changed in version 2.0: Removed the
afk
keyword-only parameter.
- await fetch_template(code)[source]#
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).- Returns:
The template from the URL/code.
- Return type:
- Raises:
NotFound – The template is invalid.
HTTPException – Getting the template failed.
- await fetch_guild(guild_id, /, *, with_counts=True)[source]#
This function is a coroutine.
Retrieves a
Guild
from an ID.Note
Using this, you will not receive
Guild.channels
,Guild.members
,Member.activity
andMember.voice
perMember
.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.with_counts (
bool
) –Whether to include count information in the guild. This fills the
Guild.approximate_member_count
andGuild.approximate_presence_count
fields.New in version 2.0.
- Returns:
The guild from the ID.
- Return type:
- Raises:
Forbidden – You do not have access to the guild.
HTTPException – Getting the guild failed.
- await create_guild(*, name, icon=..., code=...)[source]#
This function is a coroutine.
Creates a
Guild
.Bot accounts in more than 10 guilds are not allowed to create guilds.
- Parameters:
name (
str
) – The name of the guild.icon (Optional[
bytes
]) – The bytes-like object representing the icon. SeeClientUser.edit()
for more details on what is expected.code (
str
) –The code for a template to create the guild with.
New in version 1.4.
- Returns:
The guild created. This is not the same guild that is added to cache.
- Return type:
- Raises:
HTTPException – Guild creation failed.
InvalidArgument – Invalid icon image format given. Must be PNG or JPG.
- await fetch_stage_instance(channel_id, /)[source]#
This function is a coroutine.
Gets a
StageInstance
for a stage channel id.New in version 2.0.
- Parameters:
channel_id (
int
) – The stage channel ID.- Returns:
The stage instance from the stage channel ID.
- Return type:
- Raises:
NotFound – The stage instance or channel could not be found.
HTTPException – Getting the stage instance failed.
- await fetch_invite(url, *, with_counts=True, with_expiration=True, event_id=None)[source]#
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 bePartialInviteGuild
andPartialInviteChannel
respectively.- Parameters:
url (Union[
Invite
,str
]) – The Discord invite ID or URL (must be a discord.gg URL).with_counts (
bool
) – Whether to include count information in the invite. This fills theInvite.approximate_member_count
andInvite.approximate_presence_count
fields.with_expiration (
bool
) –Whether to include the expiration date of the invite. This fills the
Invite.expires_at
field.New in version 2.0.
event_id (Optional[
int
]) –The ID of the scheduled event to be associated with the event.
See
Invite.set_scheduled_event()
for more info on event invite linking.New in version 2.0.
- Returns:
The invite from the URL/ID.
- Return type:
- Raises:
NotFound – The invite has expired or is invalid.
HTTPException – Getting the invite failed.
- await delete_invite(invite)[source]#
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:
- Raises:
Forbidden – You do not have permissions to revoke invites.
NotFound – The invite is invalid or expired.
HTTPException – Revoking the invite failed.
- Return type:
None
- await fetch_widget(guild_id, /)[source]#
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.- Returns:
The guild’s widget.
- Return type:
- Raises:
Forbidden – The widget for this guild is disabled.
HTTPException – Retrieving the widget failed.
- await application_info()[source]#
This function is a coroutine.
Retrieves the bot’s application information.
- Returns:
The bot’s application information.
- Return type:
- Raises:
HTTPException – Retrieving the information failed somehow.
- await fetch_user(user_id, /)[source]#
This function is a coroutine.
Retrieves a
User
based on their ID. 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
discord.Intents.members
and member cache enabled, considerget_user()
instead.- Parameters:
user_id (
int
) – The user’s ID to fetch from.- Returns:
The user you requested.
- Return type:
- Raises:
NotFound – A user with this ID does not exist.
HTTPException – Fetching the user failed.
- await fetch_channel(channel_id, /)[source]#
This function is a coroutine.
Retrieves a
abc.GuildChannel
,abc.PrivateChannel
, orThread
with the specified ID.Note
This method is an API call. For general usage, consider
get_channel()
instead.New in version 1.2.
- Returns:
The channel from the ID.
- Return type:
Union[
abc.GuildChannel
,abc.PrivateChannel
,Thread
]- 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.
- Parameters:
channel_id (int) –
- await fetch_webhook(webhook_id, /)[source]#
This function is a coroutine.
Retrieves a
Webhook
with the specified ID.- Returns:
The webhook you requested.
- Return type:
- Raises:
HTTPException – Retrieving the webhook failed.
NotFound – Invalid webhook ID.
Forbidden – You do not have permission to fetch this webhook.
- Parameters:
webhook_id (
int
) –
- await fetch_sticker(sticker_id, /)[source]#
This function is a coroutine.
Retrieves a
Sticker
with the specified ID.New in version 2.0.
- Returns:
The sticker you requested.
- Return type:
Union[
StandardSticker
,GuildSticker
]- Raises:
HTTPException – Retrieving the sticker failed.
NotFound – Invalid sticker ID.
- Parameters:
sticker_id (int) –
This function is a coroutine.
Retrieves all available premium sticker packs.
New in version 2.0.
- Returns:
All available premium sticker packs.
- Return type:
List[
StickerPack
]- Raises:
HTTPException – Retrieving the sticker packs failed.
- await create_dm(user)[source]#
This function is a coroutine.
Creates a
DMChannel
with this user.This should be rarely called, as this is done transparently for most people.
New in version 2.0.
- add_view(view, *, message_id=None)[source]#
Registers a
View
for persistent listening.This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
- Parameters:
view (
discord.ui.View
) – The view to register for dispatching.message_id (Optional[
int
]) – The message ID that the view is attached to. This is currently used to refresh the view’s state during message update events. If not given then message update events are not propagated for the view.
- Raises:
TypeError – A view was not passed.
ValueError – The view is not persistent. A persistent view has no timeout and all their components have an explicitly provided
custom_id
.
- Return type:
None
- property persistent_views#
A sequence of persistent views added to the client.
New in version 2.0.
- await fetch_role_connection_metadata_records()[source]#
This function is a coroutine.
Fetches the bot’s role connection metadata records.
New in version 2.4.
- Returns:
The bot’s role connection metadata records.
- Return type:
- await update_role_connection_metadata_records(*role_connection_metadata)[source]#
This function is a coroutine.
Updates the bot’s role connection metadata records.
New in version 2.4.
- Parameters:
*role_connection_metadata (
ApplicationRoleConnectionMetadata
) – The new metadata records to send to Discord.- Returns:
The updated role connection metadata records.
- Return type:
- await fetch_skus()[source]#
This function is a coroutine.
Fetches the bot’s SKUs.
New in version 2.5.
- Returns:
The bot’s SKUs.
- Return type:
List[
SKU
]
- entitlements(user=None, skus=None, before=None, after=None, limit=100, guild=None, exclude_ended=False)[source]#
Returns an
AsyncIterator
that enables fetching the application’s entitlements.New in version 2.6.
- Parameters:
user (
abc.Snowflake
| None) – Limit the fetched entitlements to entitlements owned by this user.skus (list[
abc.Snowflake
] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake
|datetime.datetime
| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake
|datetime.datetime
| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int
]) – The number of entitlements to retrieve. IfNone
, retrieves every entitlement, which may be slow. Defaults to100
.guild (
abc.Snowflake
| None) – Limit the fetched entitlements to entitlements owned by this guild.exclude_ended (
bool
) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse
.
- Yields:
Entitlement
– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- Return type:
EntitlementIterator
Examples
Usage
async for entitlement in client.entitlements(): print(entitlement.user_id)
Flattening into a list
entitlements = await user.entitlements().flatten()
All parameters are optional.
- asyncchange_presence
- asyncclose
- asyncconnect
- defget_shard
- defis_ws_ratelimited
- class discord.AutoShardedClient(*args, loop=None, **kwargs)[source]#
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 thatshard_count
must be provided if this is used. By default, when omitted, the client will launch shards from 0 toshard_count - 1
.- Parameters:
args (Any) –
loop (asyncio.AbstractEventLoop | None) –
kwargs (Any) –
- 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 thelatencies
property. Returnsnan
if there are no shards ready.
- 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)
.
- property shards#
Returns a mapping of shard IDs to their respective info object.
- await connect(*, reconnect=True)[source]#
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 – 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.
- Return type:
- await change_presence(*, activity=None, status=None, shard_id=None)[source]#
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)
Changed in version 2.0: Removed the
afk
keyword-only parameter.- 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. IfNone
, thenStatus.online
is used.shard_id (Optional[
int
]) – The shard_id to change the presence to. If not specified orNone
, then it will change the presence of every shard the bot can see.
- Raises:
InvalidArgument – If the
activity
parameter is not of proper type.- Return type:
None
- is_ws_ratelimited()[source]#
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()
. :rtype:bool
New in version 1.6.