API Reference¶
The following section outlines the API of discord.py.
Note
This module uses the Python logging module to log diagnostic and errors in an output independent way. If the logging module is not configured, these logs will not be output anywhere. See Setting Up Logging for more information on how to set up and use the logging module with discord.py.
Clients¶
Client¶
- defadd_dynamic_items
- defadd_view
- asyncapplication_info
- asyncbefore_identify_hook
- asyncchange_presence
- defclear
- asyncclose
- asyncconnect
- asynccreate_dm
- asynccreate_entitlement
- asynccreate_guild
- asyncdelete_invite
- async forentitlements
- @event
- asyncfetch_channel
- asyncfetch_entitlement
- asyncfetch_guild
- async forfetch_guilds
- asyncfetch_invite
- asyncfetch_premium_sticker_packs
- 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_partial_messageable
- defget_stage_instance
- defget_sticker
- defget_user
- defis_closed
- defis_ready
- defis_ws_ratelimited
- asynclogin
- asyncon_error
- defremove_dynamic_items
- defrun
- asyncsetup_hook
- asyncstart
- asyncwait_for
- asyncwait_until_ready
- class discord.Client(*, intents, **options)¶
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
- async with x
Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
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
.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.
New in version 1.5.
Changed in version 2.0: Parameter is now required.
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.
http_trace (
aiohttp.TraceConfig
) –The trace configuration to use for tracking HTTP requests the library does using
aiohttp
. This allows you to check requests the library is using. For more information, check the aiohttp documentation.New in version 2.0.
max_ratelimit_timeout (Optional[
float
]) –The maximum number of seconds to wait when a non-global rate limit is encountered. If a request requires sleeping for more than the seconds passed in, then
RateLimited
will be raised. By default, there is no timeout limit. In order to prevent misuse and unnecessary bans, the minimum value this can be set to is30.0
seconds.New in version 2.0.
- ws¶
The websocket gateway the client is currently connected to. Could be
None
.
- @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!')
Changed in version 2.0:
coro
parameter is now positional-only.- 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
- 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 stickers¶
The stickers that the connected client has.
New in version 2.0.
- Type
Sequence[
GuildSticker
]
- 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
Sequence[
abc.PrivateChannel
]
- property voice_clients¶
Represents a list of voice connections.
These are usually
VoiceClient
instances.- Type
List[
VoiceProtocol
]
- 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 or after a call tologin()
. Usually afteron_connect()
is called.New in version 2.0.
- Type
Optional[
int
]
- property application_flags¶
The client’s application flags.
New in version 2.0.
- Type
- property application¶
The client’s application info.
This is retrieved on
login()
and is not updated afterwards. This allows populating the application_id without requiring a gateway connection.This is
None
if accessed beforelogin()
is called.See also
The
application_info()
API callNew in version 2.0.
- Type
Optional[
AppInfo
]
- await on_error(event_method, /, *args, **kwargs)¶
This function is a coroutine.
The default error handler provided by the client.
By default this logs to the library logger however it could be overridden to have a different implementation. Check
on_error()
for more details.Changed in version 2.0:
event_method
parameter is now positional-only and instead of writing tosys.stderr
it logs instead.
- 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.
- await setup_hook()¶
This function is a coroutine.
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in
login()
, and will be called before any events are dispatched, making it a better solution than doing such setup in theon_ready()
event.Warning
Since this is called before the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like
wait_for()
andwait_until_ready()
.New in version 2.0.
- await login(token)¶
This function is a coroutine.
Logs in the client with the specified credentials and calls the
setup_hook()
.- 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 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.
- 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.
- await start(token, *, reconnect=True)¶
This function is a coroutine.
A shorthand coroutine for
login()
+connect()
.- 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).
- Raises
TypeError – An unexpected keyword argument was received.
- run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., 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 orconnect()
+login()
.This function also sets up the 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 thelog_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 ifNone
is passed, though it is your responsibility to set it up.The default log handler if not provided is
logging.StreamHandler
.New in version 2.0.
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).
New in version 2.0.
log_level (
int
) –The default log level for the library’s logger. This is only applied if the
log_handler
parameter is notNone
. Defaults tologging.INFO
.New in version 2.0.
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 toTrue
then the root logger is set up as well.Defaults to
False
.New in version 2.0.
- 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
]
- get_channel(id, /)¶
Returns a channel or thread with the given ID.
Changed in version 2.0:
id
parameter is now positional-only.- 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_partial_messageable(id, *, guild_id=None, 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.guild_id (Optional[
int
]) –The optional guild ID to create a partial messageable for.
This is not required to actually send messages, but it does allow the
jump_url()
andguild
properties to function properly.type (Optional[
ChannelType
]) – The underlying channel type for the partial messageable.
- Returns
The partial messageable
- Return type
- 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_guild(id, /)¶
Returns a guild with the given ID.
Changed in version 2.0:
id
parameter is now positional-only.
- get_user(id, /)¶
Returns a user with the given ID.
Changed in version 2.0:
id
parameter is now positional-only.
- get_emoji(id, /)¶
Returns an emoji with the given ID.
Changed in version 2.0:
id
parameter is now positional-only.
- 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
]
- 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.
Warning
Calling this inside
setup_hook()
can lead to a deadlock.
- 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.
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('👍')
Changed in version 2.0:
event
parameter is now positional-only.- 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
.
- 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
- await change_presence(*, activity=None, status=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)
Changed in version 2.0: Removed the
afk
keyword-only parameter.Changed in version 2.0: This function will now raise
TypeError
instead ofInvalidArgument
.- 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
TypeError – If the
activity
parameter is not the proper type.
- async for ... in fetch_guilds(*, limit=200, before=None, after=None, with_counts=True)¶
Retrieves an asynchronous iterator that enables receiving your guilds.
Note
Using this, you will only receive
Guild.owner
,Guild.icon
,Guild.id
,Guild.name
,Guild.approximate_member_count
, andGuild.approximate_presence_count
perGuild
.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 = [guild async for guild in client.fetch_guilds(limit=150)] # 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 to200
.Changed in version 2.0: The default has been changed to 200.
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.with_counts (
bool
) –Whether to include count information in the guilds. This fills the
Guild.approximate_member_count
andGuild.approximate_presence_count
attributes without needing any privileged intents. Defaults toTrue
.New in version 2.3.
- Raises
HTTPException – Getting the guilds failed.
- Yields
Guild
– The guild with the guild data parsed.
- 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
- 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.Changed in version 2.0:
guild_id
parameter is now positional-only.- 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
attributes without needing any privileged intents. Defaults toTrue
.New in version 2.0.
- Raises
NotFound – The guild doesn’t exist or you got no access to it.
HTTPException – Getting the guild failed.
- Returns
The guild from the ID.
- 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.
Changed in version 2.0:
name
andicon
parameters are now keyword-only. Theregion
parameter has been removed.Changed in version 2.0: This function will now raise
ValueError
instead ofInvalidArgument
.- 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.
- Raises
HTTPException – Guild creation failed.
ValueError – 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
- 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.- Raises
NotFound – The stage instance or channel could not be found.
HTTPException – Getting the stage instance failed.
- Returns
The stage instance from the stage channel ID.
- Return type
- await fetch_invite(url, *, with_counts=True, with_expiration=True, scheduled_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.
scheduled_event_id (Optional[
int
]) –The ID of the scheduled event this invite is for.
Note
It is not possible to provide a url that contains an
event_id
parameter when using this parameter.New in version 2.0.
- Raises
ValueError – The url contains an
event_id
, butscheduled_event_id
has also been provided.NotFound – The invite has expired or is invalid.
HTTPException – Getting the invite failed.
- Returns
The invite from the URL/ID.
- Return type
- await delete_invite(invite, /)¶
This function is a coroutine.
Revokes an
Invite
, URL, or ID to an invite.You must have
manage_channels
in the associated guild to do this.Changed in version 2.0:
invite
parameter is now positional-only.- Parameters
- 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.
Changed in version 2.0:
guild_id
parameter is now positional-only.- 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
- 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
- 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.Changed in version 2.0:
user_id
parameter is now positional-only.- 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
- 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.
Changed in version 2.0:
channel_id
parameter is now positional-only.- 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
,Thread
]
- await fetch_webhook(webhook_id, /)¶
This function is a coroutine.
Retrieves a
Webhook
with the specified ID.Changed in version 2.0:
webhook_id
parameter is now positional-only.- 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
- await fetch_sticker(sticker_id, /)¶
This function is a coroutine.
Retrieves a
Sticker
with the specified ID.New in version 2.0.
- Raises
HTTPException – Retrieving the sticker failed.
NotFound – Invalid sticker ID.
- Returns
The sticker you requested.
- Return type
Union[
StandardSticker
,GuildSticker
]
- await fetch_skus()¶
This function is a coroutine.
Retrieves the bot’s available SKUs.
New in version 2.4.
- Raises
MissingApplicationID – The application ID could not be found.
HTTPException – Retrieving the SKUs failed.
- Returns
The bot’s available SKUs.
- Return type
List[
SKU
]
- await fetch_entitlement(entitlement_id, /)¶
This function is a coroutine.
Retrieves a
Entitlement
with the specified ID.New in version 2.4.
- Parameters
entitlement_id (
int
) – The entitlement’s ID to fetch from.- Raises
NotFound – An entitlement with this ID does not exist.
MissingApplicationID – The application ID could not be found.
HTTPException – Fetching the entitlement failed.
- Returns
The entitlement you requested.
- Return type
- async for ... in entitlements(*, limit=100, before=None, after=None, skus=None, user=None, guild=None, exclude_ended=False)¶
Retrieves an asynchronous iterator of the
Entitlement
that applications has.New in version 2.4.
Examples
Usage
async for entitlement in client.entitlements(limit=100): print(entitlement.user_id, entitlement.ends_at)
Flattening into a list
entitlements = [entitlement async for entitlement in client.entitlements(limit=100)] # entitlements is now a list of Entitlement...
All parameters are optional.
- Parameters
limit (Optional[
int
]) – The number of entitlements to retrieve. IfNone
, it retrieves every entitlement for this application. Note, however, that this would make it a slow operation. Defaults to100
.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve entitlements before this date or entitlement. 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 (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve entitlements after this date or entitlement. 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.skus (Optional[Sequence[
Snowflake
]]) – A list of SKUs to filter by.user (Optional[
Snowflake
]) – The user to filter by.guild (Optional[
Snowflake
]) – The guild to filter by.exclude_ended (
bool
) – Whether to exclude ended entitlements. Defaults toFalse
.
- Raises
MissingApplicationID – The application ID could not be found.
HTTPException – Fetching the entitlements failed.
TypeError – Both
after
andbefore
were provided, as Discord does not support this type of pagination.
- Yields
Entitlement
– The entitlement with the application.
- await create_entitlement(sku, owner, owner_type)¶
This function is a coroutine.
Creates a test
Entitlement
for the application.New in version 2.4.
- Parameters
sku (
Snowflake
) – The SKU to create the entitlement for.owner (
Snowflake
) – The ID of the owner.owner_type (
EntitlementOwnerType
) – The type of the owner.
- Raises
MissingApplicationID – The application ID could not be found.
NotFound – The SKU or owner could not be found.
HTTPException – Creating the entitlement failed.
This function is a coroutine.
Retrieves all available premium sticker packs.
New in version 2.0.
- Raises
HTTPException – Retrieving the sticker packs failed.
- Returns
All available premium sticker packs.
- Return type
List[
StickerPack
]
- 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.
- add_dynamic_items(*items)¶
Registers
DynamicItem
classes for persistent listening.This method accepts class types rather than instances.
New in version 2.4.
- Parameters
*items (Type[
DynamicItem
]) – The classes of dynamic items to add.- Raises
TypeError – A class is not a subclass of
DynamicItem
.
- remove_dynamic_items(*items)¶
Removes
DynamicItem
classes from persistent listening.This method accepts class types rather than instances.
New in version 2.4.
- Parameters
*items (Type[
DynamicItem
]) – The classes of dynamic items to remove.- Raises
TypeError – A class is not a subclass of
DynamicItem
.
- 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 or is already finished. A persistent view has no timeout and all their components have an explicitly provided custom_id.
AutoShardedClient¶
- asyncchange_presence
- asyncclose
- asyncconnect
- defget_shard
- defis_ws_ratelimited
- class discord.AutoShardedClient(*args, intents, **kwargs)¶
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
.- async with x
Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
- shard_connect_timeout¶
The maximum number of seconds to wait before timing out when launching a shard. Defaults to 180 seconds.
New in version 2.4.
- Type
Optional[
float
]
- 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.- Type
- 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)
.
- get_shard(shard_id, /)¶
Gets the shard information at a given shard ID or
None
if not found.Changed in version 2.0:
shard_id
parameter is now positional-only.- Returns
Information about the shard with given ID.
None
if not found.- Return type
Optional[
ShardInfo
]
- property shards¶
Returns a mapping of shard IDs to their respective info object.
- Type
Mapping[int,
ShardInfo
]
- 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 change_presence(*, activity=None, status=None, 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)
Changed in version 2.0: Removed the
afk
keyword-only parameter.Changed in version 2.0: This function will now raise
TypeError
instead ofInvalidArgument
.- 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
TypeError – 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.
Application Info¶
AppInfo¶
- approximate_guild_count
- bot_public
- bot_require_code_grant
- cover_image
- custom_install_url
- description
- flags
- guild
- guild_id
- icon
- id
- install_params
- interactions_endpoint_url
- name
- owner
- primary_sku_id
- privacy_policy_url
- redirect_uris
- role_connections_verification_url
- rpc_origins
- slug
- tags
- team
- terms_of_service_url
- verify_key
- asyncedit
- class discord.AppInfo¶
Represents the application info for the bot provided by Discord.
- bot_public¶
Whether the bot can be invited by anyone or if it is locked to the application owner.
- Type
- bot_require_code_grant¶
Whether the bot requires the completion of the full oauth2 code grant flow to join.
- Type
- verify_key¶
The hex encoded key for verification in interactions and the GameSDK’s GetTicket.
New in version 1.3.
- Type
- guild_id¶
If this application is a game sold on Discord, this field will be the guild to which it has been linked to.
New in version 1.3.
- Type
Optional[
int
]
- primary_sku_id¶
If this application is a game sold on Discord, this field will be the id of the “Game SKU” that is created, if it exists.
New in version 1.3.
- Type
Optional[
int
]
- slug¶
If this application is a game sold on Discord, this field will be the URL slug that links to the store page.
New in version 1.3.
- Type
Optional[
str
]
- terms_of_service_url¶
The application’s terms of service URL, if set.
New in version 2.0.
- Type
Optional[
str
]
- privacy_policy_url¶
The application’s privacy policy URL, if set.
New in version 2.0.
- Type
Optional[
str
]
- tags¶
The list of tags describing the functionality of the application.
New in version 2.0.
- Type
List[
str
]
- custom_install_url¶
The custom authorization URL for the application, if enabled.
New in version 2.0.
- Type
List[
str
]
- install_params¶
The settings for custom authorization URL of application, if enabled.
New in version 2.0.
- Type
Optional[
AppInstallParams
]
- role_connections_verification_url¶
The application’s connection verification URL which will render the application as a verification method in the guild’s role verification configuration.
New in version 2.2.
- Type
Optional[
str
]
- interactions_endpoint_url¶
The interactions endpoint url of the application to receive interactions over this endpoint rather than over the gateway, if configured.
New in version 2.4.
- Type
Optional[
str
]
- approximate_guild_count¶
The approximate count of the guilds the bot was added to.
New in version 2.4.
- Type
- property cover_image¶
Retrieves the cover image on a store embed, if any.
This is only available if the application is a game sold on Discord.
- Type
Optional[
Asset
]
- property guild¶
If this application is a game sold on Discord, this field will be the guild to which it has been linked
New in version 1.3.
- Type
Optional[
Guild
]
- property flags¶
The application’s flags.
New in version 2.0.
- Type
- await edit(*, reason=..., custom_install_url=..., description=..., role_connections_verification_url=..., install_params_scopes=..., install_params_permissions=..., flags=..., icon=..., cover_image=..., interactions_endpoint_url=..., tags=...)¶
This function is a coroutine.
Edits the application info.
New in version 2.4.
- Parameters
custom_install_url (Optional[
str
]) – The new custom authorization URL for the application. Can beNone
to remove the URL.description (Optional[
str
]) – The new application description. Can beNone
to remove the description.role_connections_verification_url (Optional[
str
]) – The new application’s connection verification URL which will render the application as a verification method in the guild’s role verification configuration. Can beNone
to remove the URL.install_params_scopes (Optional[List[
str
]]) – The new list of OAuth2 scopes of theinstall_params
. Can beNone
to remove the scopes.install_params_permissions (Optional[
Permissions
]) – The new permissions of theinstall_params
. Can beNone
to remove the permissions.flags (Optional[
ApplicationFlags
]) –The new application’s flags. Only limited intent flags (
gateway_presence_limited
,gateway_guild_members_limited
,gateway_message_content_limited
) can be edited. Can beNone
to remove the flags.Warning
Editing the limited intent flags leads to the termination of the bot.
icon (Optional[
bytes
]) – The new application’s icon as a bytes-like object. Can beNone
to remove the icon.cover_image (Optional[
bytes
]) – The new application’s cover image as a bytes-like object on a store embed. The cover image is only available if the application is a game sold on Discord. Can beNone
to remove the image.interactions_endpoint_url (Optional[
str
]) – The new interactions endpoint url of the application to receive interactions over this endpoint rather than over the gateway. Can beNone
to remove the URL.tags (Optional[List[
str
]]) – The new list of tags describing the functionality of the application. Can beNone
to remove the tags.reason (Optional[
str
]) – The reason for editing the application. Shows up on the audit log.
- Raises
HTTPException – Editing the application failed
ValueError – The image format passed in to
icon
orcover_image
is invalid. This is also raised wheninstall_params_scopes
andinstall_params_permissions
are incompatible with each other.
- Returns
The newly updated application info.
- Return type
PartialAppInfo¶
- class discord.PartialAppInfo¶
Represents a partial AppInfo given by
create_invite()
New in version 2.0.
- approximate_guild_count¶
The approximate count of the guilds the bot was added to.
New in version 2.3.
- Type
- interactions_endpoint_url¶
The interactions endpoint url of the application to receive interactions over this endpoint rather than over the gateway, if configured.
New in version 2.3.
- Type
Optional[
str
]
- role_connections_verification_url¶
The application’s connection verification URL which will render the application as a verification method in the guild’s role verification configuration.
New in version 2.3.
- Type
Optional[
str
]
- property cover_image¶
Retrieves the cover image of the application’s default rich presence.
This is only available if the application is a game sold on Discord.
New in version 2.3.
- Type
Optional[
Asset
]
- property flags¶
The application’s flags.
New in version 2.0.
- Type
AppInstallParams¶
- class discord.AppInstallParams¶
Represents the settings for custom authorization URL of an application.
New in version 2.0.
- scopes¶
The list of OAuth2 scopes to add the application to a guild with.
- Type
List[
str
]
- permissions¶
The permissions to give to application in the guild.
- Type
Team¶
- class discord.Team¶
Represents an application team for a bot provided by Discord.
- members¶
A list of the members in the team
New in version 1.3.
- Type
List[
TeamMember
]
- property owner¶
The team’s owner.
- Type
Optional[
TeamMember
]
TeamMember¶
- defmentioned_in
- class discord.TeamMember¶
Represents a team member in a team.
- x == y
Checks if two team members are equal.
- x != y
Checks if two team members are not equal.
- hash(x)
Return the team member’s hash.
- str(x)
Returns the team member’s handle (e.g.
name
orname#discriminator
).
New in version 1.3.
- discriminator¶
The team member’s discriminator. This is a legacy concept that is no longer used.
- Type
- global_name¶
The team member’s global nickname, taking precedence over the username in display.
New in version 2.3.
- Type
Optional[
str
]
- membership_state¶
The membership state of the member (e.g. invited or accepted)
- Type
- role¶
The role of the member within the team.
New in version 2.4.
- Type
- property accent_color¶
Returns the user’s accent color, if applicable.
A user’s accent color is only shown if they do not have a banner. This will only be available if the user explicitly sets a color.
There is an alias for this named
accent_colour
.New in version 2.0.
Note
This information is only available via
Client.fetch_user()
.- Type
Optional[
Colour
]
- property accent_colour¶
Returns the user’s accent colour, if applicable.
A user’s accent colour is only shown if they do not have a banner. This will only be available if the user explicitly sets a colour.
There is an alias for this named
accent_color
.New in version 2.0.
Note
This information is only available via
Client.fetch_user()
.- Type
Optional[
Colour
]
- property avatar¶
Returns an
Asset
for the avatar the user has.If the user has not uploaded a global avatar,
None
is returned. If you want the avatar that a user has displayed, considerdisplay_avatar
.- Type
Optional[
Asset
]
- property avatar_decoration¶
Returns an
Asset
for the avatar decoration the user has.If the user has not set an avatar decoration,
None
is returned.New in version 2.4.
- Type
Optional[
Asset
]
- property avatar_decoration_sku_id¶
Returns the SKU ID of the avatar decoration the user has.
If the user has not set an avatar decoration,
None
is returned.New in version 2.4.
- Type
Optional[
int
]
- property banner¶
Returns the user’s banner asset, if available.
New in version 2.0.
Note
This information is only available via
Client.fetch_user()
.- Type
Optional[
Asset
]
- property color¶
A property that returns a color denoting the rendered color for the user. This always returns
Colour.default()
.There is an alias for this named
colour
.- Type
- property colour¶
A property that returns a colour denoting the rendered colour for the user. This always returns
Colour.default()
.There is an alias for this named
color
.- Type
- property created_at¶
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
- Type
- property display_avatar¶
Returns the user’s display avatar.
For regular users this is just their default avatar or uploaded avatar.
New in version 2.0.
- Type
- property display_name¶
Returns the user’s display name.
For regular users this is just their global name or their username, but if they have a guild specific nickname then that is returned instead.
- Type
- mentioned_in(message)¶
Checks if the user is mentioned in the specified message.
- property public_flags¶
The publicly available flags the user has.
- Type
Event Reference¶
This section outlines the different types of events listened by Client
.
There are two ways to register an event, the first way is through the use of
Client.event()
. The second way is through subclassing Client
and
overriding the specific events. For example:
import discord
class MyClient(discord.Client):
async def on_message(self, message):
if message.author == self.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello World!')
If an event handler raises an exception, on_error()
will be called
to handle it, which defaults to logging the traceback and ignoring the exception.
Warning
All the events must be a coroutine. If they aren’t, then you might get unexpected
errors. In order to turn a function into a coroutine they must be async def
functions.
App Commands¶
- discord.on_raw_app_command_permissions_update(payload)¶
Called when application command permissions are updated.
New in version 2.0.
- Parameters
payload (
RawAppCommandPermissionsUpdateEvent
) – The raw event payload data.
- discord.on_app_command_completion(interaction, command)¶
Called when a
app_commands.Command
orapp_commands.ContextMenu
has successfully completed without error.New in version 2.0.
- Parameters
interaction (
Interaction
) – The interaction of the command.command (Union[
app_commands.Command
,app_commands.ContextMenu
]) – The command that completed successfully
AutoMod¶
- discord.on_automod_rule_create(rule)¶
Called when a
AutoModRule
is created. You must havemanage_guild
to receive this.This requires
Intents.auto_moderation_configuration
to be enabled.New in version 2.0.
- Parameters
rule (
AutoModRule
) – The rule that was created.
- discord.on_automod_rule_update(rule)¶
Called when a
AutoModRule
is updated. You must havemanage_guild
to receive this.This requires
Intents.auto_moderation_configuration
to be enabled.New in version 2.0.
- Parameters
rule (
AutoModRule
) – The rule that was updated.
- discord.on_automod_rule_delete(rule)¶
Called when a
AutoModRule
is deleted. You must havemanage_guild
to receive this.This requires
Intents.auto_moderation_configuration
to be enabled.New in version 2.0.
- Parameters
rule (
AutoModRule
) – The rule that was deleted.
- discord.on_automod_action(execution)¶
Called when a
AutoModAction
is created/performed. You must havemanage_guild
to receive this.This requires
Intents.auto_moderation_execution
to be enabled.New in version 2.0.
- Parameters
execution (
AutoModAction
) – The rule execution that was performed.
Channels¶
- discord.on_guild_channel_delete(channel)¶
- discord.on_guild_channel_create(channel)¶
Called whenever a guild channel is deleted or created.
Note that you can get the guild from
guild
.This requires
Intents.guilds
to be enabled.- Parameters
channel (
abc.GuildChannel
) – The guild channel that got created or deleted.
- discord.on_guild_channel_update(before, after)¶
Called whenever a guild channel is updated. e.g. changed name, topic, permissions.
This requires
Intents.guilds
to be enabled.- Parameters
before (
abc.GuildChannel
) – The updated guild channel’s old info.after (
abc.GuildChannel
) – The updated guild channel’s new info.
- discord.on_guild_channel_pins_update(channel, last_pin)¶
Called whenever a message is pinned or unpinned from a guild channel.
This requires
Intents.guilds
to be enabled.- Parameters
channel (Union[
abc.GuildChannel
,Thread
]) – The guild channel that had its pins updated.last_pin (Optional[
datetime.datetime
]) – The latest message that was pinned as an aware datetime in UTC. Could beNone
.
- discord.on_private_channel_update(before, after)¶
Called whenever a private group DM is updated. e.g. changed name or topic.
This requires
Intents.messages
to be enabled.- Parameters
before (
GroupChannel
) – The updated group channel’s old info.after (
GroupChannel
) – The updated group channel’s new info.
- discord.on_private_channel_pins_update(channel, last_pin)¶
Called whenever a message is pinned or unpinned from a private channel.
- Parameters
channel (
abc.PrivateChannel
) – The private channel that had its pins updated.last_pin (Optional[
datetime.datetime
]) – The latest message that was pinned as an aware datetime in UTC. Could beNone
.
- discord.on_typing(channel, user, when)¶
Called when someone begins typing a message.
The
channel
parameter can be aabc.Messageable
instance. Which could either beTextChannel
,GroupChannel
, orDMChannel
.If the
channel
is aTextChannel
then theuser
parameter is aMember
, otherwise it is aUser
.If the channel or user could not be found in the internal cache this event will not be called, you may use
on_raw_typing()
instead.This requires
Intents.typing
to be enabled.- Parameters
channel (
abc.Messageable
) – The location where the typing originated from.when (
datetime.datetime
) – When the typing started as an aware datetime in UTC.
- discord.on_raw_typing(payload)¶
Called when someone begins typing a message. Unlike
on_typing()
this is called regardless of the channel and user being in the internal cache.This requires
Intents.typing
to be enabled.New in version 2.0.
- Parameters
payload (
RawTypingEvent
) – The raw event payload data.
Connection¶
- discord.on_connect()¶
Called when the client has successfully connected to Discord. This is not the same as the client being fully prepared, see
on_ready()
for that.The warnings on
on_ready()
also apply.
- discord.on_disconnect()¶
Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. This could happen either through the internet being disconnected, explicit calls to close, or Discord terminating the connection one way or the other.
This function can be called many times without a corresponding
on_connect()
call.
- discord.on_shard_connect(shard_id)¶
Similar to
on_connect()
except used byAutoShardedClient
to denote when a particular shard ID has connected to Discord.New in version 1.4.
- Parameters
shard_id (
int
) – The shard ID that has connected.
- discord.on_shard_disconnect(shard_id)¶
Similar to
on_disconnect()
except used byAutoShardedClient
to denote when a particular shard ID has disconnected from Discord.New in version 1.4.
- Parameters
shard_id (
int
) – The shard ID that has disconnected.
Debug¶
- discord.on_error(event, *args, **kwargs)¶
Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to
sys.exc_info()
.Note
on_error
will only be dispatched toClient.event()
.It will not be received by
Client.wait_for()
, or, if used, Bots listeners such aslisten()
orlistener()
.Changed in version 2.0: The traceback is now logged rather than printed.
- Parameters
event (
str
) – The name of the event that raised the exception.args – The positional arguments for the event that raised the exception.
kwargs – The keyword arguments for the event that raised the exception.
- discord.on_socket_event_type(event_type)¶
Called whenever a websocket event is received from the WebSocket.
This is mainly useful for logging how many events you are receiving from the Discord gateway.
New in version 2.0.
- Parameters
event_type (
str
) – The event type from Discord that is received, e.g.'READY'
.
- discord.on_socket_raw_receive(msg)¶
Called whenever a message is completely received from the WebSocket, before it’s processed and parsed. This event is always dispatched when a complete message is received and the passed data is not parsed in any way.
This is only really useful for grabbing the WebSocket stream and debugging purposes.
This requires setting the
enable_debug_events
setting in theClient
.Note
This is only for the messages received from the client WebSocket. The voice WebSocket will not trigger this event.
- Parameters
msg (
str
) – The message passed in from the WebSocket library.
- discord.on_socket_raw_send(payload)¶
Called whenever a send operation is done on the WebSocket before the message is sent. The passed parameter is the message that is being sent to the WebSocket.
This is only really useful for grabbing the WebSocket stream and debugging purposes.
This requires setting the
enable_debug_events
setting in theClient
.Note
This is only for the messages sent from the client WebSocket. The voice WebSocket will not trigger this event.
Entitlements¶
- discord.on_entitlement_create(entitlement)¶
Called when a user subscribes to a SKU.
New in version 2.4.
- Parameters
entitlement (
Entitlement
) – The entitlement that was created.
- discord.on_entitlement_update(entitlement)¶
Called when a user updates their subscription to a SKU. This is usually called when the user renews or cancels their subscription.
New in version 2.4.
- Parameters
entitlement (
Entitlement
) – The entitlement that was updated.
- discord.on_entitlement_delete(entitlement)¶
Called when a users subscription to a SKU is cancelled. This is typically only called when:
Discord issues a refund for the subscription.
Discord removes an entitlement from a user.
Warning
This event won’t be called if the user cancels their subscription manually, instead
on_entitlement_update()
will be called withEntitlement.ends_at
set to the end of the current billing period.New in version 2.4.
- Parameters
entitlement (
Entitlement
) – The entitlement that was deleted.
Gateway¶
- discord.on_ready()¶
Called when the client is done preparing the data received from Discord. Usually after login is successful and the
Client.guilds
and co. are filled up.Warning
This function is not guaranteed to be the first event called. Likewise, this function is not guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
- discord.on_resumed()¶
Called when the client has resumed a session.
- discord.on_shard_ready(shard_id)¶
Similar to
on_ready()
except used byAutoShardedClient
to denote when a particular shard ID has become ready.- Parameters
shard_id (
int
) – The shard ID that is ready.
- discord.on_shard_resumed(shard_id)¶
Similar to
on_resumed()
except used byAutoShardedClient
to denote when a particular shard ID has resumed a session.New in version 1.4.
- Parameters
shard_id (
int
) – The shard ID that has resumed.
Guilds¶
- discord.on_guild_available(guild)¶
Called when a guild becomes available or unavailable. The guild must have existed in the
Client.guilds
cache.This requires
Intents.guilds
to be enabled.- Parameters
guild – The
Guild
that has changed availability.
- discord.on_guild_join(guild)¶
Called when a
Guild
is either created by theClient
or when theClient
joins a guild.This requires
Intents.guilds
to be enabled.- Parameters
guild (
Guild
) – The guild that was joined.
- discord.on_guild_remove(guild)¶
Called when a
Guild
is removed from theClient
.This happens through, but not limited to, these circumstances:
The client got banned.
The client got kicked.
The client left the guild.
The client or the guild owner deleted the guild.
In order for this event to be invoked then the
Client
must have been part of the guild to begin with. (i.e. it is part ofClient.guilds
)This requires
Intents.guilds
to be enabled.- Parameters
guild (
Guild
) – The guild that got removed.
- discord.on_guild_update(before, after)¶
Called when a
Guild
updates, for example:Changed name
Changed AFK channel
Changed AFK timeout
etc
This requires
Intents.guilds
to be enabled.
- discord.on_guild_emojis_update(guild, before, after)¶
Called when a
Guild
adds or removesEmoji
.This requires
Intents.emojis_and_stickers
to be enabled.
- discord.on_guild_stickers_update(guild, before, after)¶
Called when a
Guild
updates its stickers.This requires
Intents.emojis_and_stickers
to be enabled.New in version 2.0.
- Parameters
guild (
Guild
) – The guild who got their stickers updated.before (Sequence[
GuildSticker
]) – A list of stickers before the update.after (Sequence[
GuildSticker
]) – A list of stickers after the update.
- discord.on_audit_log_entry_create(entry)¶
Called when a
Guild
gets a new audit log entry. You must haveview_audit_log
to receive this.This requires
Intents.moderation
to be enabled.New in version 2.2.
Warning
Audit log entries received through the gateway are subject to data retrieval from cache rather than REST. This means that some data might not be present when you expect it to be. For example, the
AuditLogEntry.target
attribute will usually be adiscord.Object
and theAuditLogEntry.user
attribute will depend on user and member cache.To get the user ID of entry,
AuditLogEntry.user_id
can be used instead.- Parameters
entry (
AuditLogEntry
) – The audit log entry that was created.
- discord.on_invite_create(invite)¶
Called when an
Invite
is created. You must havemanage_channels
to receive this.New in version 1.3.
Note
There is a rare possibility that the
Invite.guild
andInvite.channel
attributes will be ofObject
rather than the respective models.This requires
Intents.invites
to be enabled.- Parameters
invite (
Invite
) – The invite that was created.
- discord.on_invite_delete(invite)¶
Called when an
Invite
is deleted. You must havemanage_channels
to receive this.New in version 1.3.
Note
There is a rare possibility that the
Invite.guild
andInvite.channel
attributes will be ofObject
rather than the respective models.Outside of those two attributes, the only other attribute guaranteed to be filled by the Discord gateway for this event is
Invite.code
.This requires
Intents.invites
to be enabled.- Parameters
invite (
Invite
) – The invite that was deleted.
Integrations¶
- discord.on_integration_create(integration)¶
Called when an integration is created.
This requires
Intents.integrations
to be enabled.New in version 2.0.
- Parameters
integration (
Integration
) – The integration that was created.
- discord.on_integration_update(integration)¶
Called when an integration is updated.
This requires
Intents.integrations
to be enabled.New in version 2.0.
- Parameters
integration (
Integration
) – The integration that was updated.
- discord.on_guild_integrations_update(guild)¶
Called whenever an integration is created, modified, or removed from a guild.
This requires
Intents.integrations
to be enabled.New in version 1.4.
- Parameters
guild (
Guild
) – The guild that had its integrations updated.
- discord.on_webhooks_update(channel)¶
Called whenever a webhook is created, modified, or removed from a guild channel.
This requires
Intents.webhooks
to be enabled.- Parameters
channel (
abc.GuildChannel
) – The channel that had its webhooks updated.
- discord.on_raw_integration_delete(payload)¶
Called when an integration is deleted.
This requires
Intents.integrations
to be enabled.New in version 2.0.
- Parameters
payload (
RawIntegrationDeleteEvent
) – The raw event payload data.
Interactions¶
- discord.on_interaction(interaction)¶
Called when an interaction happened.
This currently happens due to slash command invocations or components being used.
Warning
This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the
View
instead as it provides a nicer user experience.New in version 2.0.
- Parameters
interaction (
Interaction
) – The interaction data.
Members¶
- discord.on_member_join(member)¶
Called when a
Member
joins aGuild
.This requires
Intents.members
to be enabled.- Parameters
member (
Member
) – The member who joined.
- discord.on_member_remove(member)¶
Called when a
Member
leaves aGuild
.If the guild or member could not be found in the internal cache this event will not be called, you may use
on_raw_member_remove()
instead.This requires
Intents.members
to be enabled.- Parameters
member (
Member
) – The member who left.
- discord.on_raw_member_remove(payload)¶
Called when a
Member
leaves aGuild
.Unlike
on_member_remove()
this is called regardless of the guild or member being in the internal cache.This requires
Intents.members
to be enabled.New in version 2.0.
- Parameters
payload (
RawMemberRemoveEvent
) – The raw event payload data.
- discord.on_member_update(before, after)¶
Called when a
Member
updates their profile.This is called when one or more of the following things change:
nickname
roles
pending
timeout
guild avatar
flags
Due to a Discord limitation, this event is not dispatched when a member’s timeout expires.
This requires
Intents.members
to be enabled.
- discord.on_user_update(before, after)¶
Called when a
User
updates their profile.This is called when one or more of the following things change:
avatar
username
discriminator
This requires
Intents.members
to be enabled.
- discord.on_member_ban(guild, user)¶
Called when a user gets banned from a
Guild
.This requires
Intents.moderation
to be enabled.
- discord.on_member_unban(guild, user)¶
Called when a
User
gets unbanned from aGuild
.This requires
Intents.moderation
to be enabled.
- discord.on_presence_update(before, after)¶
Called when a
Member
updates their presence.This is called when one or more of the following things change:
status
activity
This requires
Intents.presences
andIntents.members
to be enabled.New in version 2.0.
Messages¶
- discord.on_message(message)¶
Called when a
Message
is created and sent.This requires
Intents.messages
to be enabled.Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that
Bot
does not have this problem.- Parameters
message (
Message
) – The current message.
- discord.on_message_edit(before, after)¶
Called when a
Message
receives an update event. If the message is not found in the internal message cache, then these events will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.If this occurs increase the
max_messages
parameter or use theon_raw_message_edit()
event instead.The following non-exhaustive cases trigger this event:
A message has been pinned or unpinned.
The message content has been changed.
The message has received an embed.
For performance reasons, the embed server does not do this in a “consistent” manner.
The message’s embeds were suppressed or unsuppressed.
A call message has received an update to its participants or ending time.
This requires
Intents.messages
to be enabled.
- discord.on_message_delete(message)¶
Called when a message is deleted. If the message is not found in the internal message cache, then this event will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the
max_messages
parameter or use theon_raw_message_delete()
event instead.This requires
Intents.messages
to be enabled.- Parameters
message (
Message
) – The deleted message.
- discord.on_bulk_message_delete(messages)¶
Called when messages are bulk deleted. If none of the messages deleted are found in the internal message cache, then this event will not be called. If individual messages were not found in the internal message cache, this event will still be called, but the messages not found will not be included in the messages list. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the
max_messages
parameter or use theon_raw_bulk_message_delete()
event instead.This requires
Intents.messages
to be enabled.- Parameters
messages (List[
Message
]) – The messages that have been deleted.
- discord.on_raw_message_edit(payload)¶
Called when a message is edited. Unlike
on_message_edit()
, this is called regardless of the state of the internal message cache.If the message is found in the message cache, it can be accessed via
RawMessageUpdateEvent.cached_message
. The cached message represents the message before it has been edited. For example, if the content of a message is modified and triggers theon_raw_message_edit()
coroutine, theRawMessageUpdateEvent.cached_message
will return aMessage
object that represents the message before the content was modified.Due to the inherently raw nature of this event, the data parameter coincides with the raw data given by the gateway.
Since the data payload can be partial, care must be taken when accessing stuff in the dictionary. One example of a common case of partial data is when the
'content'
key is inaccessible. This denotes an “embed” only edit, which is an edit in which only the embeds are updated by the Discord embed server.This requires
Intents.messages
to be enabled.- Parameters
payload (
RawMessageUpdateEvent
) – The raw event payload data.
- discord.on_raw_message_delete(payload)¶
Called when a message is deleted. Unlike
on_message_delete()
, this is called regardless of the message being in the internal message cache or not.If the message is found in the message cache, it can be accessed via
RawMessageDeleteEvent.cached_message
This requires
Intents.messages
to be enabled.- Parameters
payload (
RawMessageDeleteEvent
) – The raw event payload data.
- discord.on_raw_bulk_message_delete(payload)¶
Called when a bulk delete is triggered. Unlike
on_bulk_message_delete()
, this is called regardless of the messages being in the internal message cache or not.If the messages are found in the message cache, they can be accessed via
RawBulkMessageDeleteEvent.cached_messages
This requires
Intents.messages
to be enabled.- Parameters
payload (
RawBulkMessageDeleteEvent
) – The raw event payload data.
Polls¶
- discord.on_poll_vote_add(user, answer)¶
- discord.on_poll_vote_remove(user, answer)¶
Called when a
Poll
gains or loses a vote. If theuser
oranswer
’s poll parent message are not cached then this event will not be called.This requires
Intents.message_content
andIntents.polls
to be enabled.Note
If the poll allows multiple answers and the user removes or adds multiple votes, this event will be called as many times as votes that are added or removed.
New in version 2.4.
- Parameters
user (Union[
User
,Member
]) – The user that performed the action.answer (
PollAnswer
) – The answer the user voted or removed their vote from.
- discord.on_raw_poll_vote_add(payload)¶
- discord.on_raw_poll_vote_remove(payload)¶
Called when a
Poll
gains or loses a vote. Unlikeon_poll_vote_add()
andon_poll_vote_remove()
this is called regardless of the state of the internal user and message cache.This requires
Intents.message_content
andIntents.polls
to be enabled.Note
If the poll allows multiple answers and the user removes or adds multiple votes, this event will be called as many times as votes that are added or removed.
New in version 2.4.
- Parameters
payload (
RawPollVoteActionEvent
) – The raw event payload data.
Reactions¶
- discord.on_reaction_add(reaction, user)¶
Called when a message has a reaction added to it. Similar to
on_message_edit()
, if the message is not found in the internal message cache, then this event will not be called. Consider usingon_raw_reaction_add()
instead.Note
To get the
Message
being reacted, access it viaReaction.message
.This requires
Intents.reactions
to be enabled.Note
This doesn’t require
Intents.members
within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider usingon_raw_reaction_add()
if you need this and do not otherwise want to enable the members intent.Warning
This event does not have a way of differentiating whether a reaction is a burst reaction (also known as “super reaction”) or not. If you need this, consider using
on_raw_reaction_add()
instead.
- discord.on_reaction_remove(reaction, user)¶
Called when a message has a reaction removed from it. Similar to on_message_edit, if the message is not found in the internal message cache, then this event will not be called.
Note
To get the message being reacted, access it via
Reaction.message
.This requires both
Intents.reactions
andIntents.members
to be enabled.Note
Consider using
on_raw_reaction_remove()
if you need this and do not want to enable the members intent.Warning
This event does not have a way of differentiating whether a reaction is a burst reaction (also known as “super reaction”) or not. If you need this, consider using
on_raw_reaction_remove()
instead.
- discord.on_reaction_clear(message, reactions)¶
Called when a message has all its reactions removed from it. Similar to
on_message_edit()
, if the message is not found in the internal message cache, then this event will not be called. Consider usingon_raw_reaction_clear()
instead.This requires
Intents.reactions
to be enabled.
- discord.on_reaction_clear_emoji(reaction)¶
Called when a message has a specific reaction removed from it. Similar to
on_message_edit()
, if the message is not found in the internal message cache, then this event will not be called. Consider usingon_raw_reaction_clear_emoji()
instead.This requires
Intents.reactions
to be enabled.New in version 1.3.
- Parameters
reaction (
Reaction
) – The reaction that got cleared.
- discord.on_raw_reaction_add(payload)¶
Called when a message has a reaction added. Unlike
on_reaction_add()
, this is called regardless of the state of the internal message cache.This requires
Intents.reactions
to be enabled.- Parameters
payload (
RawReactionActionEvent
) – The raw event payload data.
- discord.on_raw_reaction_remove(payload)¶
Called when a message has a reaction removed. Unlike
on_reaction_remove()
, this is called regardless of the state of the internal message cache.This requires
Intents.reactions
to be enabled.- Parameters
payload (
RawReactionActionEvent
) – The raw event payload data.
- discord.on_raw_reaction_clear(payload)¶
Called when a message has all its reactions removed. Unlike
on_reaction_clear()
, this is called regardless of the state of the internal message cache.This requires
Intents.reactions
to be enabled.- Parameters
payload (
RawReactionClearEvent
) – The raw event payload data.
- discord.on_raw_reaction_clear_emoji(payload)¶
Called when a message has a specific reaction removed from it. Unlike
on_reaction_clear_emoji()
this is called regardless of the state of the internal message cache.This requires
Intents.reactions
to be enabled.New in version 1.3.
- Parameters
payload (
RawReactionClearEmojiEvent
) – The raw event payload data.
Roles¶
- discord.on_guild_role_create(role)¶
- discord.on_guild_role_delete(role)¶
Called when a
Guild
creates or deletes a newRole
.To get the guild it belongs to, use
Role.guild
.This requires
Intents.guilds
to be enabled.- Parameters
role (
Role
) – The role that was created or deleted.
- discord.on_guild_role_update(before, after)¶
Called when a
Role
is changed guild-wide.This requires
Intents.guilds
to be enabled.
Scheduled Events¶
- discord.on_scheduled_event_create(event)¶
- discord.on_scheduled_event_delete(event)¶
Called when a
ScheduledEvent
is created or deleted.This requires
Intents.guild_scheduled_events
to be enabled.New in version 2.0.
- Parameters
event (
ScheduledEvent
) – The scheduled event that was created or deleted.
- discord.on_scheduled_event_update(before, after)¶
Called when a
ScheduledEvent
is updated.This requires
Intents.guild_scheduled_events
to be enabled.The following, but not limited to, examples illustrate when this event is called:
The scheduled start/end times are changed.
The channel is changed.
The description is changed.
The status is changed.
The image is changed.
New in version 2.0.
- Parameters
before (
ScheduledEvent
) – The scheduled event before the update.after (
ScheduledEvent
) – The scheduled event after the update.
- discord.on_scheduled_event_user_add(event, user)¶
- discord.on_scheduled_event_user_remove(event, user)¶
Called when a user is added or removed from a
ScheduledEvent
.This requires
Intents.guild_scheduled_events
to be enabled.New in version 2.0.
- Parameters
event (
ScheduledEvent
) – The scheduled event that the user was added or removed from.user (
User
) – The user that was added or removed.
Stages¶
- discord.on_stage_instance_create(stage_instance)¶
- discord.on_stage_instance_delete(stage_instance)¶
Called when a
StageInstance
is created or deleted for aStageChannel
.New in version 2.0.
- Parameters
stage_instance (
StageInstance
) – The stage instance that was created or deleted.
- discord.on_stage_instance_update(before, after)¶
Called when a
StageInstance
is updated.The following, but not limited to, examples illustrate when this event is called:
The topic is changed.
The privacy level is changed.
New in version 2.0.
- Parameters
before (
StageInstance
) – The stage instance before the update.after (
StageInstance
) – The stage instance after the update.
Threads¶
- discord.on_thread_create(thread)¶
Called whenever a thread is created.
Note that you can get the guild from
Thread.guild
.This requires
Intents.guilds
to be enabled.New in version 2.0.
- Parameters
thread (
Thread
) – The thread that was created.
- discord.on_thread_join(thread)¶
Called whenever a thread is joined.
Note that you can get the guild from
Thread.guild
.This requires
Intents.guilds
to be enabled.New in version 2.0.
- Parameters
thread (
Thread
) – The thread that got joined.
- discord.on_thread_update(before, after)¶
Called whenever a thread is updated. If the thread could not be found in the internal cache this event will not be called. Threads will not be in the cache if they are archived.
If you need this information use
on_raw_thread_update()
instead.This requires
Intents.guilds
to be enabled.New in version 2.0.
- discord.on_thread_remove(thread)¶
Called whenever a thread is removed. This is different from a thread being deleted.
Note that you can get the guild from
Thread.guild
.This requires
Intents.guilds
to be enabled.Warning
Due to technical limitations, this event might not be called as soon as one expects. Since the library tracks thread membership locally, the API only sends updated thread membership status upon being synced by joining a thread.
New in version 2.0.
- Parameters
thread (
Thread
) – The thread that got removed.
- discord.on_thread_delete(thread)¶
Called whenever a thread is deleted. If the thread could not be found in the internal cache this event will not be called. Threads will not be in the cache if they are archived.
If you need this information use
on_raw_thread_delete()
instead.Note that you can get the guild from
Thread.guild
.This requires
Intents.guilds
to be enabled.New in version 2.0.
- Parameters
thread (
Thread
) – The thread that got deleted.
- discord.on_raw_thread_update(payload)¶
Called whenever a thread is updated. Unlike
on_thread_update()
this is called regardless of the thread being in the internal thread cache or not.This requires
Intents.guilds
to be enabled.New in version 2.0.
- Parameters
payload (
RawThreadUpdateEvent
) – The raw event payload data.
- discord.on_raw_thread_delete(payload)¶
Called whenever a thread is deleted. Unlike
on_thread_delete()
this is called regardless of the thread being in the internal thread cache or not.This requires
Intents.guilds
to be enabled.New in version 2.0.
- Parameters
payload (
RawThreadDeleteEvent
) – The raw event payload data.
- discord.on_thread_member_join(member)¶
- discord.on_thread_member_remove(member)¶
Called when a
ThreadMember
leaves or joins aThread
.You can get the thread a member belongs in by accessing
ThreadMember.thread
.This requires
Intents.members
to be enabled.New in version 2.0.
- Parameters
member (
ThreadMember
) – The member who joined or left.
- discord.on_raw_thread_member_remove(payload)¶
Called when a
ThreadMember
leaves aThread
. Unlikeon_thread_member_remove()
this is called regardless of the member being in the internal thread’s members cache or not.This requires
Intents.members
to be enabled.New in version 2.0.
- Parameters
payload (
RawThreadMembersUpdate
) – The raw event payload data.
Voice¶
- discord.on_voice_state_update(member, before, after)¶
Called when a
Member
changes theirVoiceState
.The following, but not limited to, examples illustrate when this event is called:
A member joins a voice or stage channel.
A member leaves a voice or stage channel.
A member is muted or deafened by their own accord.
A member is muted or deafened by a guild administrator.
This requires
Intents.voice_states
to be enabled.- Parameters
member (
Member
) – The member whose voice states changed.before (
VoiceState
) – The voice state prior to the changes.after (
VoiceState
) – The voice state after the changes.
Utility Functions¶
- discord.utils.find(predicate, iterable, /)¶
A helper to return the first element found in the sequence that meets the predicate. For example:
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
would find the first
Member
whose name is ‘Mighty’ and return it. If an entry is not found, thenNone
is returned.This is different from
filter()
due to the fact it stops the moment it finds a valid entry.Changed in version 2.0: Both parameters are now positional-only.
Changed in version 2.0: The
iterable
parameter supports asynchronous iterables.- Parameters
predicate – A function that returns a boolean-like result.
iterable (Union[
collections.abc.Iterable
,collections.abc.AsyncIterable
]) – The iterable to search through. Using acollections.abc.AsyncIterable
, makes this function return a coroutine.
- discord.utils.get(iterable, /, **attrs)¶
A helper that returns the first element in the iterable that meets all the traits passed in
attrs
. This is an alternative forfind()
.When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by
x.y
) then pass inx__y
as the keyword argument.If nothing is found that matches the attributes passed, then
None
is returned.Changed in version 2.0: The
iterable
parameter is now positional-only.Changed in version 2.0: The
iterable
parameter supports asynchronous iterables.Examples
Basic usage:
member = discord.utils.get(message.guild.members, name='Foo')
Multiple attribute matching:
channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)
Nested attribute matching:
channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')
Async iterables:
msg = await discord.utils.get(channel.history(), author__name='Dave')
- Parameters
iterable (Union[
collections.abc.Iterable
,collections.abc.AsyncIterable
]) – The iterable to search through. Using acollections.abc.AsyncIterable
, makes this function return a coroutine.**attrs – Keyword arguments that denote attributes to search with.
- discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)¶
A helper function to setup logging.
This is superficially similar to
logging.basicConfig()
but uses different defaults and a colour formatter if the stream can display colour.This is used by the
Client
to set up logging iflog_handler
is notNone
.New in version 2.0.
- Parameters
handler (
logging.Handler
) –The log handler to use for the library’s logger.
The default log handler if not provided is
logging.StreamHandler
.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). If colour is not available then a simple logging formatter is provided.level (
int
) – The default log level for the library’s logger. Defaults tologging.INFO
.root (
bool
) – Whether to set up the root logger rather than the library logger. Unlike the default forClient
, this defaults toTrue
.
- await discord.utils.maybe_coroutine(f, *args, **kwargs)¶
This function is a coroutine.
A helper function that will await the result of a function if it’s a coroutine or return the result if it’s not.
This is useful for functions that may or may not be coroutines.
New in version 2.2.
- Parameters
f (Callable[..., Any]) – The function or coroutine to call.
*args – The arguments to pass to the function.
**kwargs – The keyword arguments to pass to the function.
- Returns
The result of the function or coroutine.
- Return type
Any
- discord.utils.snowflake_time(id, /)¶
Returns the creation time of the given snowflake.
Changed in version 2.0: The
id
parameter is now positional-only.- Parameters
id (
int
) – The snowflake ID.- Returns
An aware datetime in UTC representing the creation time of the snowflake.
- Return type
- discord.utils.time_snowflake(dt, /, *, high=False)¶
Returns a numeric snowflake pretending to be created at the given date.
When using as the lower end of a range, use
time_snowflake(dt, high=False) - 1
to be inclusive,high=True
to be exclusive.When using as the higher end of a range, use
time_snowflake(dt, high=True) + 1
to be inclusive,high=False
to be exclusive.Changed in version 2.0: The
high
parameter is now keyword-only and thedt
parameter is now positional-only.- Parameters
dt (
datetime.datetime
) – A datetime object to convert to a snowflake. If naive, the timezone is assumed to be local time.high (
bool
) – Whether or not to set the lower 22 bit to high or low.
- Returns
The snowflake representing the time given.
- Return type
- discord.utils.oauth_url(client_id, *, permissions=..., guild=..., redirect_uri=..., scopes=..., disable_guild_select=False, state=...)¶
A helper function that returns the OAuth2 URL for inviting the bot into guilds.
Changed in version 2.0:
permissions
,guild
,redirect_uri
,scopes
andstate
parameters are now keyword-only.- Parameters
permissions (
Permissions
) – The permissions you’re requesting. If not given then you won’t be requesting any permissions.guild (
Snowflake
) – The guild to pre-select in the authorization screen, if available.redirect_uri (
str
) – An optional valid redirect URI.scopes (Iterable[
str
]) –An optional valid list of scopes. Defaults to
('bot', 'applications.commands')
.New in version 1.7.
disable_guild_select (
bool
) –Whether to disallow the user from changing the guild dropdown.
New in version 2.0.
state (
str
) –The state to return after the authorization.
New in version 2.0.
- Returns
The OAuth2 URL for inviting the bot into guilds.
- Return type
- discord.utils.remove_markdown(text, *, ignore_links=True)¶
A helper function that removes markdown characters.
New in version 1.7.
Note
This function is not markdown aware and may remove meaning from the original text. For example, if the input contains
10 * 5
then it will be converted into10 5
.- Parameters
- Returns
The text with the markdown special characters removed.
- Return type
- discord.utils.escape_markdown(text, *, as_needed=False, ignore_links=True)¶
A helper function that escapes Discord’s markdown.
- Parameters
text (
str
) – The text to escape markdown from.as_needed (
bool
) – Whether to escape the markdown characters as needed. This means that it does not escape extraneous characters if it’s not necessary, e.g.**hello**
is escaped into\*\*hello**
instead of\*\*hello\*\*
. Note however that this can open you up to some clever syntax abuse. Defaults toFalse
.ignore_links (
bool
) – Whether to leave links alone when escaping markdown. For example, if a URL in the text contains characters such as_
then it will be left alone. This option is not supported withas_needed
. Defaults toTrue
.
- Returns
The text with the markdown special characters escaped with a slash.
- Return type
- discord.utils.escape_mentions(text)¶
A helper function that escapes everyone, here, role, and user mentions.
Note
This does not include channel mentions.
Note
For more granular control over what mentions should be escaped within messages, refer to the
AllowedMentions
class.
- class discord.ResolvedInvite¶
A data class which represents a resolved invite returned from
discord.utils.resolve_invite()
.
- discord.utils.resolve_invite(invite)¶
Resolves an invite from a
Invite
, URL or code.Changed in version 2.0: Now returns a
ResolvedInvite
instead of astr
.- Parameters
- Returns
A data class containing the invite code and the event ID.
- Return type
- discord.utils.resolve_template(code)¶
Resolves a template code from a
Template
, URL or code.New in version 1.4.
- await discord.utils.sleep_until(when, result=None)¶
This function is a coroutine.
Sleep until a specified time.
If the time supplied is in the past this function will yield instantly.
New in version 1.3.
- Parameters
when (
datetime.datetime
) – The timestamp in which to sleep until. If the datetime is naive then it is assumed to be local time.result (Any) – If provided is returned to the caller when the coroutine completes.
- discord.utils.utcnow()¶
A helper function to return an aware UTC datetime representing the current time.
This should be preferred to
datetime.datetime.utcnow()
since it is an aware datetime, compared to the naive datetime in the standard library.New in version 2.0.
- Returns
The current aware datetime in UTC.
- Return type
- discord.utils.format_dt(dt, /, style=None)¶
A helper function to format a
datetime.datetime
for presentation within Discord.This allows for a locale-independent way of presenting data using Discord specific Markdown.
Style
Example Output
Description
t
22:57
Short Time
T
22:57:58
Long Time
d
17/05/2016
Short Date
D
17 May 2016
Long Date
f (default)
17 May 2016 22:57
Short Date Time
F
Tuesday, 17 May 2016 22:57
Long Date Time
R
5 years ago
Relative Time
Note that the exact output depends on the user’s locale setting in the client. The example output presented is using the
en-GB
locale.New in version 2.0.
- Parameters
dt (
datetime.datetime
) – The datetime to format.style (
str
) – The style to format the datetime with.
- Returns
The formatted string.
- Return type
- discord.utils.as_chunks(iterator, max_size)¶
A helper function that collects an iterator into chunks of a given size.
New in version 2.0.
- Parameters
iterator (Union[
collections.abc.Iterable
,collections.abc.AsyncIterable
]) – The iterator to chunk, can be sync or async.max_size (
int
) – The maximum chunk size.
Warning
The last chunk collected may not be as large as
max_size
.- Returns
A new iterator which yields chunks of a given size.
- Return type
Union[
Iterator
,AsyncIterator
]
- discord.utils.MISSING¶
A type safe sentinel used in the library to represent something as missing. Used to distinguish from
None
values.New in version 2.0.
Enumerations¶
The API provides some enumerations for certain types of strings to avoid the API from being stringly typed in case the strings change in the future.
All enumerations are subclasses of an internal class which mimics the behaviour
of enum.Enum
.
- class discord.ChannelType¶
Specifies the type of channel.
- text¶
A text channel.
- voice¶
A voice channel.
- private¶
A private text channel. Also called a direct message.
- group¶
A private group text channel.
- category¶
A category channel.
- news¶
A guild news channel.
- stage_voice¶
A guild stage voice channel.
New in version 1.7.
- news_thread¶
A news thread
New in version 2.0.
- public_thread¶
A public thread
New in version 2.0.
- private_thread¶
A private thread
New in version 2.0.
- forum¶
A forum channel.
New in version 2.0.
- media¶
A media channel.
New in version 2.4.
- class discord.MessageType¶
Specifies the type of
Message
. This is used to denote if a message is to be interpreted as a system message or a regular message.- x == y
Checks if two messages are equal.
- x != y
Checks if two messages are not equal.
- default¶
The default message type. This is the same as regular messages.
- recipient_add¶
The system message when a user is added to a group private message or a thread.
- recipient_remove¶
The system message when a user is removed from a group private message or a thread.
- call¶
The system message denoting call state, e.g. missed call, started call, etc.
- channel_name_change¶
The system message denoting that a channel’s name has been changed.
- channel_icon_change¶
The system message denoting that a channel’s icon has been changed.
- pins_add¶
The system message denoting that a pinned message has been added to a channel.
- new_member¶
The system message denoting that a new member has joined a Guild.
The system message denoting that a member has “nitro boosted” a guild.
The system message denoting that a member has “nitro boosted” a guild and it achieved level 1.
The system message denoting that a member has “nitro boosted” a guild and it achieved level 2.
The system message denoting that a member has “nitro boosted” a guild and it achieved level 3.
- channel_follow_add¶
The system message denoting that an announcement channel has been followed.
New in version 1.3.
- guild_stream¶
The system message denoting that a member is streaming in the guild.
New in version 1.7.
- guild_discovery_disqualified¶
The system message denoting that the guild is no longer eligible for Server Discovery.
New in version 1.7.
- guild_discovery_requalified¶
The system message denoting that the guild has become eligible again for Server Discovery.
New in version 1.7.
- guild_discovery_grace_period_initial_warning¶
The system message denoting that the guild has failed to meet the Server Discovery requirements for one week.
New in version 1.7.
- guild_discovery_grace_period_final_warning¶
The system message denoting that the guild has failed to meet the Server Discovery requirements for 3 weeks in a row.
New in version 1.7.
- thread_created¶
The system message denoting that a thread has been created. This is only sent if the thread has been created from an older message. The period of time required for a message to be considered old cannot be relied upon and is up to Discord.
New in version 2.0.
- reply¶
The system message denoting that the author is replying to a message.
New in version 2.0.
- chat_input_command¶
The system message denoting that a slash command was executed.
New in version 2.0.
- guild_invite_reminder¶
The system message sent as a reminder to invite people to the guild.
New in version 2.0.
- thread_starter_message¶
The system message denoting the message in the thread that is the one that started the thread’s conversation topic.
New in version 2.0.
The system message denoting that a context menu command was executed.
New in version 2.0.
- auto_moderation_action¶
The system message sent when an AutoMod rule is triggered. This is only sent if the rule is configured to sent an alert when triggered.
New in version 2.0.
- role_subscription_purchase¶
The system message sent when a user purchases or renews a role subscription.
New in version 2.2.
The system message sent when a user is given an advertisement to purchase a premium tier for an application during an interaction.
New in version 2.2.
- stage_start¶
The system message sent when the stage starts.
New in version 2.2.
- stage_end¶
The system message sent when the stage ends.
New in version 2.2.
- stage_speaker¶
The system message sent when the stage speaker changes.
New in version 2.2.
- stage_raise_hand¶
The system message sent when a user is requesting to speak by raising their hands.
New in version 2.2.
- stage_topic¶
The system message sent when the stage topic changes.
New in version 2.2.
The system message sent when an application’s premium subscription is purchased for the guild.
New in version 2.2.
- guild_incident_alert_mode_enabled¶
The system message sent when security actions is enabled.
New in version 2.4.
- guild_incident_alert_mode_disabled¶
The system message sent when security actions is disabled.
New in version 2.4.
- guild_incident_report_raid¶
The system message sent when a raid is reported.
New in version 2.4.
- guild_incident_report_false_alarm¶
The system message sent when a false alarm is reported.
New in version 2.4.
- class discord.UserFlags¶
Represents Discord User flags.
- staff¶
The user is a Discord Employee.
- partner¶
The user is a Discord Partner.
- hypesquad¶
The user is a HypeSquad Events member.
- bug_hunter¶
The user is a Bug Hunter.
- mfa_sms¶
The user has SMS recovery for Multi Factor Authentication enabled.
The user has dismissed the Discord Nitro promotion.
- hypesquad_bravery¶
The user is a HypeSquad Bravery member.
- hypesquad_brilliance¶
The user is a HypeSquad Brilliance member.
- hypesquad_balance¶
The user is a HypeSquad Balance member.
- early_supporter¶
The user is an Early Supporter.
- team_user¶
The user is a Team User.
- system¶
The user is a system user (i.e. represents Discord officially).
- has_unread_urgent_messages¶
The user has an unread system message.
- bug_hunter_level_2¶
The user is a Bug Hunter Level 2.
- verified_bot¶
The user is a Verified Bot.
- verified_bot_developer¶
The user is an Early Verified Bot Developer.
- discord_certified_moderator¶
The user is a Moderator Programs Alumni.
- bot_http_interactions¶
The user is a bot that only uses HTTP interactions and is shown in the online member list.
New in version 2.0.
- spammer¶
The user is flagged as a spammer by Discord.
New in version 2.0.
- active_developer¶
The user is an active developer.
New in version 2.1.
- class discord.ActivityType¶
Specifies the type of
Activity
. This is used to check how to interpret the activity itself.- unknown¶
An unknown activity type. This should generally not happen.
- playing¶
A “Playing” activity type.
- streaming¶
A “Streaming” activity type.
- listening¶
A “Listening” activity type.
- watching¶
A “Watching” activity type.
- custom¶
A custom activity type.
- competing¶
A competing activity type.
New in version 1.5.
- class discord.VerificationLevel¶
Specifies a
Guild
's verification level, which is the criteria in which a member must meet before being able to send messages to the guild.New in version 2.0.
- x == y
Checks if two verification levels are equal.
- x != y
Checks if two verification levels are not equal.
- x > y
Checks if a verification level is higher than another.
- x < y
Checks if a verification level is lower than another.
- x >= y
Checks if a verification level is higher or equal to another.
- x <= y
Checks if a verification level is lower or equal to another.
- none¶
No criteria set.
- low¶
Member must have a verified email on their Discord account.
- medium¶
Member must have a verified email and be registered on Discord for more than five minutes.
- high¶
Member must have a verified email, be registered on Discord for more than five minutes, and be a member of the guild itself for more than ten minutes.
- highest¶
Member must have a verified phone on their Discord account.
- class discord.NotificationLevel¶
Specifies whether a
Guild
has notifications on for all messages or mentions only by default.New in version 2.0.
- x == y
Checks if two notification levels are equal.
- x != y
Checks if two notification levels are not equal.
- x > y
Checks if a notification level is higher than another.
- x < y
Checks if a notification level is lower than another.
- x >= y
Checks if a notification level is higher or equal to another.
- x <= y
Checks if a notification level is lower or equal to another.
- all_messages¶
Members receive notifications for every message regardless of them being mentioned.
- only_mentions¶
Members receive notifications for messages they are mentioned in.
- class discord.ContentFilter¶
Specifies a
Guild
's explicit content filter, which is the machine learning algorithms that Discord uses to detect if an image contains pornography or otherwise explicit content.New in version 2.0.
- x == y
Checks if two content filter levels are equal.
- x != y
Checks if two content filter levels are not equal.
- x > y
Checks if a content filter level is higher than another.
- x < y
Checks if a content filter level is lower than another.
- x >= y
Checks if a content filter level is higher or equal to another.
- x <= y
Checks if a content filter level is lower or equal to another.
- disabled¶
The guild does not have the content filter enabled.
- no_role¶
The guild has the content filter enabled for members without a role.
- all_members¶
The guild has the content filter enabled for every member.
- class discord.Status¶
Specifies a
Member
‘s status.- online¶
The member is online.
- offline¶
The member is offline.
- idle¶
The member is idle.
- dnd¶
The member is “Do Not Disturb”.
- invisible¶
The member is “invisible”. In reality, this is only used when sending a presence a la
Client.change_presence()
. When you receive a user’s presence this will beoffline
instead.
- class discord.AuditLogAction¶
Represents the type of action being done for a
AuditLogEntry
, which is retrievable viaGuild.audit_logs()
.- guild_update¶
The guild has updated. Things that trigger this include:
Changing the guild vanity URL
Changing the guild invite splash
Changing the guild AFK channel or timeout
Changing the guild voice server region
Changing the guild icon, banner, or discovery splash
Changing the guild moderation settings
Changing things related to the guild widget
When this is the action, the type of
target
is theGuild
.Possible attributes for
AuditLogDiff
:
- channel_create¶
A new channel was created.
When this is the action, the type of
target
is either aabc.GuildChannel
orObject
with an ID.A more filled out object in the
Object
case can be found by usingafter
.Possible attributes for
AuditLogDiff
:
- channel_update¶
A channel was updated. Things that trigger this include:
The channel name or topic was changed
The channel bitrate was changed
When this is the action, the type of
target
is theabc.GuildChannel
orObject
with an ID.A more filled out object in the
Object
case can be found by usingafter
orbefore
.Possible attributes for
AuditLogDiff
:
- channel_delete¶
A channel was deleted.
When this is the action, the type of
target
is anObject
with an ID.A more filled out object can be found by using the
before
object.Possible attributes for
AuditLogDiff
:
- overwrite_create¶
A channel permission overwrite was created.
When this is the action, the type of
target
is theabc.GuildChannel
orObject
with an ID.When this is the action, the type of
extra
is either aRole
orMember
. If the object is not found then it is aObject
with an ID being filled, a name, and atype
attribute set to either'role'
or'member'
to help dictate what type of ID it is.Possible attributes for
AuditLogDiff
:
- overwrite_update¶
A channel permission overwrite was changed, this is typically when the permission values change.
See
overwrite_create
for more information on how thetarget
andextra
fields are set.Possible attributes for
AuditLogDiff
:
- overwrite_delete¶
A channel permission overwrite was deleted.
See
overwrite_create
for more information on how thetarget
andextra
fields are set.Possible attributes for
AuditLogDiff
:
- kick¶
A member was kicked.
When this is the action, the type of
target
is theUser
orObject
who got kicked.When this is the action, the type of
extra
is set to an unspecified proxy object with one attribute:integration_type
: An optional string that denotes the type of integration that did the action.
When this is the action,
changes
is empty.
- member_prune¶
A member prune was triggered.
When this is the action, the type of
target
is set toNone
.When this is the action, the type of
extra
is set to an unspecified proxy object with two attributes:delete_member_days
: An integer specifying how far the prune was.members_removed
: An integer specifying how many members were removed.
When this is the action,
changes
is empty.
- ban¶
A member was banned.
When this is the action, the type of
target
is theUser
orObject
who got banned.When this is the action,
changes
is empty.
- unban¶
A member was unbanned.
When this is the action, the type of
target
is theUser
orObject
who got unbanned.When this is the action,
changes
is empty.
- member_update¶
A member has updated. This triggers in the following situations:
A nickname was changed
They were server muted or deafened (or it was undo’d)
When this is the action, the type of
target
is theMember
,User
, orObject
who got updated.Possible attributes for
AuditLogDiff
:
- member_role_update¶
A member’s role has been updated. This triggers when a member either gains a role or loses a role.
When this is the action, the type of
target
is theMember
,User
, orObject
who got the role.When this is the action, the type of
extra
is set to an unspecified proxy object with one attribute:integration_type
: An optional string that denotes the type of integration that did the action.
Possible attributes for
AuditLogDiff
:
- member_move¶
A member’s voice channel has been updated. This triggers when a member is moved to a different voice channel.
When this is the action, the type of
extra
is set to an unspecified proxy object with two attributes:channel
: ATextChannel
orObject
with the channel ID where the members were moved.count
: An integer specifying how many members were moved.
New in version 1.3.
- member_disconnect¶
A member’s voice state has changed. This triggers when a member is force disconnected from voice.
When this is the action, the type of
extra
is set to an unspecified proxy object with one attribute:count
: An integer specifying how many members were disconnected.
New in version 1.3.
- bot_add¶
A bot was added to the guild.
When this is the action, the type of
target
is theMember
,User
, orObject
which was added to the guild.New in version 1.3.
- role_create¶
A new role was created.
When this is the action, the type of
target
is theRole
or aObject
with the ID.Possible attributes for
AuditLogDiff
:
- role_update¶
A role was updated. This triggers in the following situations:
The name has changed
The permissions have changed
The colour has changed
The role icon (or unicode emoji) has changed
Its hoist/mentionable state has changed
When this is the action, the type of
target
is theRole
or aObject
with the ID.Possible attributes for
AuditLogDiff
:
- role_delete¶
A role was deleted.
When this is the action, the type of
target
is theRole
or aObject
with the ID.Possible attributes for
AuditLogDiff
:
- invite_create¶
An invite was created.
When this is the action, the type of
target
is theInvite
that was created.Possible attributes for
AuditLogDiff
:
- invite_update¶
An invite was updated.
When this is the action, the type of
target
is theInvite
that was updated.
- invite_delete¶
An invite was deleted.
When this is the action, the type of
target
is theInvite
that was deleted.Possible attributes for
AuditLogDiff
:
- webhook_create¶
A webhook was created.
When this is the action, the type of
target
is theObject
with the webhook ID.Possible attributes for
AuditLogDiff
:
- webhook_update¶
A webhook was updated. This trigger in the following situations:
The webhook name changed
The webhook channel changed
When this is the action, the type of
target
is theObject
with the webhook ID.Possible attributes for
AuditLogDiff
:
- webhook_delete¶
A webhook was deleted.
When this is the action, the type of
target
is theObject
with the webhook ID.Possible attributes for
AuditLogDiff
:
- emoji_create¶
An emoji was created.
When this is the action, the type of
target
is theEmoji
orObject
with the emoji ID.Possible attributes for
AuditLogDiff
:
- emoji_update¶
An emoji was updated. This triggers when the name has changed.
When this is the action, the type of
target
is theEmoji
orObject
with the emoji ID.Possible attributes for
AuditLogDiff
:
- emoji_delete¶
An emoji was deleted.
When this is the action, the type of
target
is theObject
with the emoji ID.Possible attributes for
AuditLogDiff
:
- message_delete¶
A message was deleted by a moderator. Note that this only triggers if the message was deleted by someone other than the author.
When this is the action, the type of
target
is theMember
,User
, orObject
who had their message deleted.When this is the action, the type of
extra
is set to an unspecified proxy object with two attributes:count
: An integer specifying how many messages were deleted.channel
: ATextChannel
orObject
with the channel ID where the message got deleted.
- message_bulk_delete¶
Messages were bulk deleted by a moderator.
When this is the action, the type of
target
is theTextChannel
orObject
with the ID of the channel that was purged.When this is the action, the type of
extra
is set to an unspecified proxy object with one attribute:count
: An integer specifying how many messages were deleted.
New in version 1.3.
- message_pin¶
A message was pinned in a channel.
When this is the action, the type of
target
is theMember
,User
, orObject
who had their message pinned.When this is the action, the type of
extra
is set to an unspecified proxy object with two attributes:channel
: ATextChannel
orObject
with the channel ID where the message was pinned.message_id
: the ID of the message which was pinned.
New in version 1.3.
- message_unpin¶
A message was unpinned in a channel.
When this is the action, the type of
target
is theMember
,User
, orObject
who had their message unpinned.When this is the action, the type of
extra
is set to an unspecified proxy object with two attributes:channel
: ATextChannel
orObject
with the channel ID where the message was unpinned.message_id
: the ID of the message which was unpinned.
New in version 1.3.
- integration_create¶
A guild integration was created.
When this is the action, the type of
target
is aPartialIntegration
orObject
with the integration ID of the integration which was created.New in version 1.3.
- integration_update¶
A guild integration was updated.
When this is the action, the type of
target
is aPartialIntegration
orObject
with the integration ID of the integration which was updated.New in version 1.3.
- integration_delete¶
A guild integration was deleted.
When this is the action, the type of
target
is aPartialIntegration
orObject
with the integration ID of the integration which was deleted.New in version 1.3.
- stage_instance_create¶
A stage instance was started.
When this is the action, the type of
target
is theStageInstance
orObject
with the ID of the stage instance which was created.Possible attributes for
AuditLogDiff
:New in version 2.0.
- stage_instance_update¶
A stage instance was updated.
When this is the action, the type of
target
is theStageInstance
orObject
with the ID of the stage instance which was updated.Possible attributes for
AuditLogDiff
:New in version 2.0.
- stage_instance_delete¶
A stage instance was ended.
New in version 2.0.
- sticker_create¶
A sticker was created.
When this is the action, the type of
target
is theGuildSticker
orObject
with the ID of the sticker which was created.Possible attributes for
AuditLogDiff
:New in version 2.0.
- sticker_update¶
A sticker was updated.
When this is the action, the type of
target
is theGuildSticker
orObject
with the ID of the sticker which was updated.Possible attributes for
AuditLogDiff
:New in version 2.0.
- sticker_delete¶
A sticker was deleted.
When this is the action, the type of
target
is theGuildSticker
orObject
with the ID of the sticker which was updated.Possible attributes for
AuditLogDiff
:New in version 2.0.
- scheduled_event_create¶
A scheduled event was created.
When this is the action, the type of
target
is theScheduledEvent
orObject
with the ID of the event which was created.Possible attributes for
AuditLogDiff
: -name
-channel
-description
-privacy_level
-status
-entity_type
-cover_image
New in version 2.0.
- scheduled_event_update¶
A scheduled event was created.
When this is the action, the type of
target
is theScheduledEvent
orObject
with the ID of the event which was updated.Possible attributes for
AuditLogDiff
: -name
-channel
-description
-privacy_level
-status
-entity_type
-cover_image
New in version 2.0.
- scheduled_event_delete¶
A scheduled event was created.
When this is the action, the type of
target
is theScheduledEvent
orObject
with the ID of the event which was deleted.Possible attributes for
AuditLogDiff
: -name
-channel
-description
-privacy_level
-status
-entity_type
-cover_image
New in version 2.0.
- thread_create¶
A thread was created.
When this is the action, the type of
target
is theThread
orObject
with the ID of the thread which was created.Possible attributes for
AuditLogDiff
:New in version 2.0.
- thread_update¶
A thread was updated.
When this is the action, the type of
target
is theThread
orObject
with the ID of the thread which was updated.Possible attributes for
AuditLogDiff
:New in version 2.0.
- thread_delete¶
A thread was deleted.
When this is the action, the type of
target
is theThread
orObject
with the ID of the thread which was deleted.Possible attributes for
AuditLogDiff
:New in version 2.0.
- app_command_permission_update¶
An application command or integrations application command permissions were updated.
When this is the action, the type of
target
is aPartialIntegration
for an integrations general permissions,AppCommand
for a specific commands permissions, orObject
with the ID of the command or integration which was updated.When this is the action, the type of
extra
is set to anPartialIntegration
orObject
with the ID of application that command or integration belongs to.Possible attributes for
AuditLogDiff
:New in version 2.0.
- automod_rule_create¶
An automod rule was created.
When this is the action, the type of
target
is aAutoModRule
orObject
with the ID of the automod rule that was created.Possible attributes for
AuditLogDiff
:New in version 2.0.
- automod_rule_update¶
An automod rule was updated.
When this is the action, the type of
target
is aAutoModRule
orObject
with the ID of the automod rule that was created.Possible attributes for
AuditLogDiff
:New in version 2.0.
- automod_rule_delete¶
An automod rule was deleted.
When this is the action, the type of
target
is aAutoModRule
orObject
with the ID of the automod rule that was created.Possible attributes for
AuditLogDiff
:New in version 2.0.
- automod_block_message¶
An automod rule blocked a message from being sent.
When this is the action, the type of
target
is aMember
with the ID of the person who triggered the automod rule.When this is the action, the type of
extra
is set to an unspecified proxy object with 3 attributes:automod_rule_name
: The name of the automod rule that was triggered.automod_rule_trigger_type
: AAutoModRuleTriggerType
representation of the rule type that was triggered.channel
: The channel in which the automod rule was triggered.
When this is the action,
AuditLogEntry.changes
is empty.New in version 2.0.
- automod_flag_message¶
An automod rule flagged a message.
When this is the action, the type of
target
is aMember
with the ID of the person who triggered the automod rule.When this is the action, the type of
extra
is set to an unspecified proxy object with 3 attributes:automod_rule_name
: The name of the automod rule that was triggered.automod_rule_trigger_type
: AAutoModRuleTriggerType
representation of the rule type that was triggered.channel
: The channel in which the automod rule was triggered.
When this is the action,
AuditLogEntry.changes
is empty.New in version 2.1.
- automod_timeout_member¶
An automod rule timed-out a member.
When this is the action, the type of
target
is aMember
with the ID of the person who triggered the automod rule.When this is the action, the type of
extra
is set to an unspecified proxy object with 3 attributes:automod_rule_name
: The name of the automod rule that was triggered.automod_rule_trigger_type
: AAutoModRuleTriggerType
representation of the rule type that was triggered.channel
: The channel in which the automod rule was triggered.
When this is the action,
AuditLogEntry.changes
is empty.New in version 2.1.
- creator_monetization_request_created¶
A request to monetize the server was created.
New in version 2.4.
- creator_monetization_terms_accepted¶
The terms and conditions for creator monetization were accepted.
New in version 2.4.
- class discord.AuditLogActionCategory¶
Represents the category that the
AuditLogAction
belongs to.This can be retrieved via
AuditLogEntry.category
.- create¶
The action is the creation of something.
- delete¶
The action is the deletion of something.
- update¶
The action is the update of something.
- class discord.TeamMembershipState¶
Represents the membership state of a team member retrieved through
Client.application_info()
.New in version 1.3.
- invited¶
Represents an invited member.
- accepted¶
Represents a member currently in the team.
- class discord.TeamMemberRole¶
Represents the type of role of a team member retrieved through
Client.application_info()
.New in version 2.4.
- admin¶
The team member is an admin. This allows them to invite members to the team, access credentials, edit the application, and do most things the owner can do. However they cannot do destructive actions.
- developer¶
The team member is a developer. This allows them to access information, like the client secret or public key. They can also configure interaction endpoints or reset the bot token. Developers cannot invite anyone to the team nor can they do destructive actions.
- read_only¶
The team member is a read-only member. This allows them to access information, but not edit anything.
- class discord.WebhookType¶
Represents the type of webhook that can be received.
New in version 1.3.
- incoming¶
Represents a webhook that can post messages to channels with a token.
- channel_follower¶
Represents a webhook that is internally managed by Discord, used for following channels.
- application¶
Represents a webhook that is used for interactions or applications.
New in version 2.0.
- class discord.ExpireBehaviour¶
Represents the behaviour the
Integration
should perform when a user’s subscription has finished.There is an alias for this called
ExpireBehavior
.New in version 1.4.
- remove_role¶
This will remove the
StreamIntegration.role
from the user when their subscription is finished.
- kick¶
This will kick the user when their subscription is finished.
- class discord.DefaultAvatar¶
Represents the default avatar of a Discord
User
- blurple¶
Represents the default avatar with the colour blurple. See also
Colour.blurple
- grey¶
Represents the default avatar with the colour grey. See also
Colour.greyple
- green¶
Represents the default avatar with the colour green. See also
Colour.green
- orange¶
Represents the default avatar with the colour orange. See also
Colour.orange
- red¶
Represents the default avatar with the colour red. See also
Colour.red
- pink¶
Represents the default avatar with the colour pink. See also
Colour.pink
New in version 2.3.
- class discord.StickerType¶
Represents the type of sticker.
New in version 2.0.
- standard¶
Represents a standard sticker that all Nitro users can use.
- guild¶
Represents a custom sticker created in a guild.
- class discord.StickerFormatType¶
Represents the type of sticker images.
New in version 1.6.
- png¶
Represents a sticker with a png image.
- apng¶
Represents a sticker with an apng image.
- lottie¶
Represents a sticker with a lottie image.
- gif¶
Represents a sticker with a gif image.
New in version 2.2.
- class discord.InviteTarget¶
Represents the invite type for voice channel invites.
New in version 2.0.
- unknown¶
The invite doesn’t target anyone or anything.
- stream¶
A stream invite that targets a user.
- embedded_application¶
A stream invite that targets an embedded application.
- class discord.VideoQualityMode¶
Represents the camera video quality mode for voice channel participants.
New in version 2.0.
- auto¶
Represents auto camera video quality.
- full¶
Represents full camera video quality.
- class discord.PrivacyLevel¶
Represents the privacy level of a stage instance or scheduled event.
New in version 2.0.
- guild_only¶
The stage instance or scheduled event is only accessible within the guild.
- class discord.NSFWLevel¶
Represents the NSFW level of a guild.
New in version 2.0.
- x == y
Checks if two NSFW levels are equal.
- x != y
Checks if two NSFW levels are not equal.
- x > y
Checks if a NSFW level is higher than another.
- x < y
Checks if a NSFW level is lower than another.
- x >= y
Checks if a NSFW level is higher or equal to another.
- x <= y
Checks if a NSFW level is lower or equal to another.
- default¶
The guild has not been categorised yet.
- explicit¶
The guild contains NSFW content.
- safe¶
The guild does not contain any NSFW content.
- age_restricted¶
The guild may contain NSFW content.
- class discord.Locale¶
Supported locales by Discord. Mainly used for application command localisation.
New in version 2.0.
- american_english¶
The
en-US
locale.
- british_english¶
The
en-GB
locale.
- bulgarian¶
The
bg
locale.
- chinese¶
The
zh-CN
locale.
- taiwan_chinese¶
The
zh-TW
locale.
- croatian¶
The
hr
locale.
- czech¶
The
cs
locale.
- indonesian¶
The
id
locale.New in version 2.2.
- danish¶
The
da
locale.
- dutch¶
The
nl
locale.
- finnish¶
The
fi
locale.
- french¶
The
fr
locale.
- german¶
The
de
locale.
- greek¶
The
el
locale.
- hindi¶
The
hi
locale.
- hungarian¶
The
hu
locale.
- italian¶
The
it
locale.
- japanese¶
The
ja
locale.
- korean¶
The
ko
locale.
- latin_american_spanish¶
The
es-419
locale.New in version 2.4.
- lithuanian¶
The
lt
locale.
- norwegian¶
The
no
locale.
- polish¶
The
pl
locale.
- brazil_portuguese¶
The
pt-BR
locale.
- romanian¶
The
ro
locale.
- russian¶
The
ru
locale.
- spain_spanish¶
The
es-ES
locale.
- swedish¶
The
sv-SE
locale.
- thai¶
The
th
locale.
- turkish¶
The
tr
locale.
- ukrainian¶
The
uk
locale.
- vietnamese¶
The
vi
locale.
- class discord.MFALevel¶
Represents the Multi-Factor Authentication requirement level of a guild.
New in version 2.0.
- x == y
Checks if two MFA levels are equal.
- x != y
Checks if two MFA levels are not equal.
- x > y
Checks if a MFA level is higher than another.
- x < y
Checks if a MFA level is lower than another.
- x >= y
Checks if a MFA level is higher or equal to another.
- x <= y
Checks if a MFA level is lower or equal to another.
- disabled¶
The guild has no MFA requirement.
- require_2fa¶
The guild requires 2 factor authentication.
- class discord.EntityType¶
Represents the type of entity that a scheduled event is for.
New in version 2.0.
- stage_instance¶
The scheduled event will occur in a stage instance.
- voice¶
The scheduled event will occur in a voice channel.
- external¶
The scheduled event will occur externally.
- class discord.EventStatus¶
Represents the status of an event.
New in version 2.0.
- scheduled¶
The event is scheduled.
- active¶
The event is active.
- completed¶
The event has ended.
- cancelled¶
The event has been cancelled.
- class discord.AutoModRuleTriggerType¶
Represents the trigger type of an automod rule.
New in version 2.0.
- keyword¶
The rule will trigger when a keyword is mentioned.
- harmful_link¶
The rule will trigger when a harmful link is posted.
- spam¶
The rule will trigger when a spam message is posted.
- keyword_preset¶
The rule will trigger when something triggers based on the set keyword preset types.
- mention_spam¶
The rule will trigger when combined number of role and user mentions is greater than the set limit.
- member_profile¶
The rule will trigger when a user’s profile contains a keyword.
New in version 2.4.
- class discord.AutoModRuleEventType¶
Represents the event type of an automod rule.
New in version 2.0.
- message_send¶
The rule will trigger when a message is sent.
- member_update¶
The rule will trigger when a member’s profile is updated.
New in version 2.4.
- class discord.AutoModRuleActionType¶
Represents the action type of an automod rule.
New in version 2.0.
- block_message¶
The rule will block a message from being sent.
- send_alert_message¶
The rule will send an alert message to a predefined channel.
- timeout¶
The rule will timeout a user.
- class discord.ForumLayoutType¶
Represents how a forum’s posts are layed out in the client.
New in version 2.2.
- not_set¶
No default has been set, so it is up to the client to know how to lay it out.
- list_view¶
Displays posts as a list.
- gallery_view¶
Displays posts as a collection of tiles.
- class discord.ForumOrderType¶
Represents how a forum’s posts are sorted in the client.
New in version 2.3.
- latest_activity¶
Sort forum posts by activity.
- creation_date¶
Sort forum posts by creation time (from most recent to oldest).
- class discord.SelectDefaultValueType¶
Represents the default value of a select menu.
New in version 2.4.
- user¶
The underlying type of the ID is a user.
- role¶
The underlying type of the ID is a role.
- channel¶
The underlying type of the ID is a channel or thread.
- class discord.SKUType¶
Represents the type of a SKU.
New in version 2.4.
- durable¶
The SKU is a durable one-time purchase.
- consumable¶
The SKU is a consumable one-time purchase.
- subscription¶
The SKU is a recurring subscription.
- subscription_group¶
The SKU is a system-generated group which is created for each
SKUType.subscription
.
- class discord.EntitlementType¶
Represents the type of an entitlement.
New in version 2.4.
- purchase¶
The entitlement was purchased by the user.
The entitlement is for a nitro subscription.
- developer_gift¶
The entitlement was gifted by the developer.
- test_mode_purchase¶
The entitlement was purchased by a developer in application test mode.
- free_purchase¶
The entitlement was granted, when the SKU was free.
- user_gift¶
The entitlement was gifted by a another user.
The entitlement was claimed for free by a nitro subscriber.
- application_subscription¶
The entitlement was purchased as an app subscription.
- class discord.EntitlementOwnerType¶
Represents the type of an entitlement owner.
New in version 2.4.
- guild¶
The entitlement owner is a guild.
- user¶
The entitlement owner is a user.
- class discord.PollLayoutType¶
Represents how a poll answers are shown.
New in version 2.4.
- default¶
The default layout.
Audit Log Data¶
Working with Guild.audit_logs()
is a complicated process with a lot of machinery
involved. The library attempts to make it easy to use and friendly. In order to accomplish
this goal, it must make use of a couple of data classes that aid in this goal.
AuditLogEntry¶
- class discord.AuditLogEntry(*, users, integrations, app_commands, automod_rules, webhooks, data, guild)¶
Represents an Audit Log entry.
You retrieve these via
Guild.audit_logs()
.- x == y
Checks if two entries are equal.
- x != y
Checks if two entries are not equal.
- hash(x)
Returns the entry’s hash.
Changed in version 1.7: Audit log entries are now comparable and hashable.
- action¶
The action that was done.
- Type
- user¶
The user who initiated this action. Usually a
Member
, unless gone then it’s aUser
.- Type
Optional[
abc.User
]
- target¶
The target that got changed. The exact type of this depends on the action being done.
- Type
Any
- extra¶
Extra information that this entry has that might be useful. For most actions, this is
None
. However in some cases it contains extra information. SeeAuditLogAction
for which actions have this field filled out.- Type
Any
- created_at¶
Returns the entry’s creation time in UTC.
- Type
- category¶
The category of the action, if applicable.
- Type
Optional[
AuditLogActionCategory
]
- changes¶
The list of changes this entry has.
- Type
- before¶
The target’s prior state.
- Type
- after¶
The target’s subsequent state.
- Type
AuditLogChanges¶
- class discord.AuditLogChanges¶
An audit log change set.
- before¶
The old value. The attribute has the type of
AuditLogDiff
.Depending on the
AuditLogActionCategory
retrieved bycategory
, the data retrieved by this attribute differs:
- after¶
The new value. The attribute has the type of
AuditLogDiff
.Depending on the
AuditLogActionCategory
retrieved bycategory
, the data retrieved by this attribute differs:
AuditLogDiff¶
- actions
- afk_channel
- afk_timeout
- allow
- app_command_permissions
- applied_tags
- archived
- auto_archive_duration
- available
- available_tags
- avatar
- banner
- bitrate
- channel
- code
- color
- colour
- cover_image
- deaf
- default_auto_archive_duration
- default_notifications
- default_reaction_emoji
- default_thread_slowmode_delay
- deny
- description
- discovery_splash
- emoji
- enable_emoticons
- enabled
- entity_type
- event_type
- exempt_channels
- exempt_roles
- expire_behavior
- expire_behaviour
- expire_grace_period
- explicit_content_filter
- flags
- format_type
- guild
- hoist
- icon
- id
- invitable
- inviter
- locked
- max_age
- max_uses
- mentionable
- mfa_level
- mute
- name
- nick
- nsfw
- overwrites
- owner
- permissions
- position
- preferred_locale
- premium_progress_bar_enabled
- privacy_level
- prune_delete_days
- public_updates_channel
- roles
- rtc_region
- rules_channel
- slowmode_delay
- splash
- status
- system_channel
- system_channel_flags
- temporary
- timed_out_until
- topic
- trigger
- trigger_type
- type
- unicode_emoji
- user_limit
- uses
- vanity_url_code
- verification_level
- video_quality_mode
- widget_channel
- widget_enabled
- class discord.AuditLogDiff¶
Represents an audit log “change” object. A change object has dynamic attributes that depend on the type of action being done. Certain actions map to certain attributes being set.
Note that accessing an attribute that does not match the specified action will lead to an attribute error.
To get a list of attributes that have been set, you can iterate over them. To see a list of all possible attributes that could be set based on the action being done, check the documentation for
AuditLogAction
, otherwise check the documentation below for all attributes that are possible.- iter(diff)
Returns an iterator over (attribute, value) tuple of this diff.
- icon¶
A guild’s or role’s icon. See also
Guild.icon
orRole.icon
.- Type
- splash¶
The guild’s invite splash. See also
Guild.splash
.- Type
- discovery_splash¶
The guild’s discovery splash. See also
Guild.discovery_splash
.- Type
- banner¶
The guild’s banner. See also
Guild.banner
.- Type
- owner¶
The guild’s owner. See also
Guild.owner
- afk_channel¶
The guild’s AFK channel.
If this could not be found, then it falls back to a
Object
with the ID being set.See
Guild.afk_channel
.- Type
Union[
VoiceChannel
,Object
]
- system_channel¶
The guild’s system channel.
If this could not be found, then it falls back to a
Object
with the ID being set.See
Guild.system_channel
.- Type
Union[
TextChannel
,Object
]
- rules_channel¶
The guild’s rules channel.
If this could not be found then it falls back to a
Object
with the ID being set.See
Guild.rules_channel
.- Type
Union[
TextChannel
,Object
]
- public_updates_channel¶
The guild’s public updates channel.
If this could not be found then it falls back to a
Object
with the ID being set.See
Guild.public_updates_channel
.- Type
Union[
TextChannel
,Object
]
- afk_timeout¶
The guild’s AFK timeout. See
Guild.afk_timeout
.- Type
- mfa_level¶
The guild’s MFA level. See
Guild.mfa_level
.- Type
- widget_channel¶
The widget’s channel.
If this could not be found then it falls back to a
Object
with the ID being set.- Type
Union[
TextChannel
,Object
]
- verification_level¶
The guild’s verification level.
See also
Guild.verification_level
.- Type
- default_notifications¶
The guild’s default notification level.
See also
Guild.default_notifications
.- Type
- explicit_content_filter¶
The guild’s content filter.
See also
Guild.explicit_content_filter
.- Type
- vanity_url_code¶
The guild’s vanity URL.
See also
Guild.vanity_invite()
andGuild.edit()
.- Type
- position¶
The position of a
Role
orabc.GuildChannel
.- Type
- type¶
The type of channel, sticker, webhook or integration.
- Type
Union[
ChannelType
,StickerType
,WebhookType
,str
]
- topic¶
The topic of a
TextChannel
orStageChannel
.See also
TextChannel.topic
orStageChannel.topic
.- Type
- bitrate¶
The bitrate of a
VoiceChannel
.See also
VoiceChannel.bitrate
.- Type
- overwrites¶
A list of permission overwrite tuples that represents a target and a
PermissionOverwrite
for said target.The first element is the object being targeted, which can either be a
Member
orUser
orRole
. If this object is not found then it is aObject
with an ID being filled and atype
attribute set to either'role'
or'member'
to help decide what type of ID it is.- Type
List[Tuple[target,
PermissionOverwrite
]]
- privacy_level¶
The privacy level of the stage instance or scheduled event
- Type
- roles¶
A list of roles being added or removed from a member.
If a role is not found then it is a
Object
with the ID and name being filled in.
- nick¶
The nickname of a member.
See also
Member.nick
- Type
Optional[
str
]
- deaf¶
Whether the member is being server deafened.
See also
VoiceState.deaf
.- Type
- mute¶
Whether the member is being server muted.
See also
VoiceState.mute
.- Type
- permissions¶
The permissions of a role.
See also
Role.permissions
.- Type
- colour¶
- color¶
The colour of a role.
See also
Role.colour
- Type
- hoist¶
Whether the role is being hoisted or not.
See also
Role.hoist
- Type
- mentionable¶
Whether the role is mentionable or not.
See also
Role.mentionable
- Type
- code¶
The invite’s code.
See also
Invite.code
- Type
- channel¶
A guild channel.
If the channel is not found then it is a
Object
with the ID being set. In some cases the channel name is also set.- Type
Union[
abc.GuildChannel
,Object
]
- inviter¶
The user who created the invite.
See also
Invite.inviter
.- Type
Optional[
User
]
- max_uses¶
The invite’s max uses.
See also
Invite.max_uses
.- Type
- uses¶
The invite’s current uses.
See also
Invite.uses
.- Type
- max_age¶
The invite’s max age in seconds.
See also
Invite.max_age
.- Type
- temporary¶
If the invite is a temporary invite.
See also
Invite.temporary
.- Type
- avatar¶
The avatar of a member.
See also
User.avatar
.- Type
- slowmode_delay¶
The number of seconds members have to wait before sending another message in the channel.
See also
TextChannel.slowmode_delay
.- Type
- rtc_region¶
The region for the voice channel’s voice communication. A value of
None
indicates automatic voice region detection.See also
VoiceChannel.rtc_region
.- Type
- video_quality_mode¶
The camera video quality for the voice channel’s participants.
See also
VoiceChannel.video_quality_mode
.- Type
- format_type¶
The format type of a sticker being changed.
See also
GuildSticker.format
- Type
- emoji¶
The name of the emoji that represents a sticker being changed.
See also
GuildSticker.emoji
.- Type
- unicode_emoji¶
The unicode emoji that is used as an icon for the role being changed.
See also
Role.unicode_emoji
.- Type
- description¶
The description of a guild, a sticker, or a scheduled event.
See also
Guild.description
,GuildSticker.description
, orScheduledEvent.description
.- Type
- available¶
The availability of a sticker being changed.
See also
GuildSticker.available
- Type
- auto_archive_duration¶
The thread’s auto archive duration being changed.
See also
Thread.auto_archive_duration
- Type
- default_auto_archive_duration¶
The default auto archive duration for newly created threads being changed.
- Type
- timed_out_until¶
Whether the user is timed out, and if so until when.
- Type
Optional[
datetime.datetime
]
- enable_emoticons¶
Integration emoticons were enabled or disabled.
See also
StreamIntegration.enable_emoticons
- Type
- expire_behaviour¶
- expire_behavior¶
The behaviour of expiring subscribers changed.
See also
StreamIntegration.expire_behaviour
- Type
- expire_grace_period¶
The grace period before expiring subscribers changed.
See also
StreamIntegration.expire_grace_period
- Type
- preferred_locale¶
The preferred locale for the guild changed.
See also
Guild.preferred_locale
- Type
- prune_delete_days¶
The number of days after which inactive and role-unassigned members are kicked has been changed.
- Type
- status¶
The status of the scheduled event.
- Type
- entity_type¶
The type of entity this scheduled event is for.
- Type
- cover_image¶
The scheduled event’s cover image.
See also
ScheduledEvent.cover_image
.- Type
- app_command_permissions¶
List of permissions for the app command.
- Type
List[
AppCommandPermissions
]
- event_type¶
The event type for triggering the automod rule.
- Type
- trigger_type¶
The trigger type for the automod rule.
- trigger¶
The trigger for the automod rule.
Note
The
type
of the trigger may be incorrect. Some attributes such askeyword_filter
,regex_patterns
, andallow_list
will only have the added or removed values.- Type
- actions¶
The actions to take when an automod rule is triggered.
- Type
List[AutoModRuleAction]
- exempt_roles¶
The list of roles that are exempt from the automod rule.
- exempt_channels¶
The list of channels or threads that are exempt from the automod rule.
- Type
List[
abc.GuildChannel
,Thread
,Object
]
The guild’s display setting to show boost progress bar.
- Type
- system_channel_flags¶
The guild’s system channel settings.
See also
Guild.system_channel_flags
- Type
- user_limit¶
The channel’s limit for number of members that can be in a voice or stage channel.
See also
VoiceChannel.user_limit
andStageChannel.user_limit
- Type
- flags¶
The channel flags associated with this thread or forum post.
See also
ForumChannel.flags
andThread.flags
- Type
- default_thread_slowmode_delay¶
The default slowmode delay for threads created in this text channel or forum.
See also
TextChannel.default_thread_slowmode_delay
andForumChannel.default_thread_slowmode_delay
- Type
- applied_tags¶
The applied tags of a forum post.
See also
Thread.applied_tags
- available_tags¶
The available tags of a forum.
See also
ForumChannel.available_tags
- Type
Sequence[
ForumTag
]
- default_reaction_emoji¶
The default_reaction_emoji for forum posts.
See also
ForumChannel.default_reaction_emoji
- Type
Optional[
PartialEmoji
]
Webhook Support¶
discord.py offers support for creating, editing, and executing webhooks through the Webhook
class.
Webhook¶
- clsWebhook.from_url
- clsWebhook.partial
- asyncdelete
- asyncdelete_message
- asyncedit
- asyncedit_message
- asyncfetch
- asyncfetch_message
- defis_authenticated
- defis_partial
- asyncsend
- class discord.Webhook¶
Represents an asynchronous Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as
Guild.webhooks()
,TextChannel.webhooks()
,VoiceChannel.webhooks()
andForumChannel.webhooks()
. The ones received by the library will automatically be bound using the library’s internal HTTP session.The second form involves creating a webhook object manually using the
from_url()
orpartial()
classmethods.For example, creating a webhook from a URL and using aiohttp:
from discord import Webhook import aiohttp async def foo(): async with aiohttp.ClientSession() as session: webhook = Webhook.from_url('url-here', session=session) await webhook.send('Hello World', username='Foo')
For a synchronous counterpart, see
SyncWebhook
.- x == y
Checks if two webhooks are equal.
- x != y
Checks if two webhooks are not equal.
- hash(x)
Returns the webhooks’s hash.
Changed in version 1.4: Webhooks are now comparable and hashable.
- type¶
The type of the webhook.
New in version 1.3.
- Type
- token¶
The authentication token of the webhook. If this is
None
then the webhook cannot be used to make requests.- Type
Optional[
str
]
- user¶
The user this webhook was created by. If the webhook was received without authentication then this will be
None
.- Type
Optional[
abc.User
]
- source_guild¶
The guild of the channel that this webhook is following. Only given if
type
isWebhookType.channel_follower
.New in version 2.0.
- Type
Optional[
PartialWebhookGuild
]
- source_channel¶
The channel that this webhook is following. Only given if
type
isWebhookType.channel_follower
.New in version 2.0.
- Type
Optional[
PartialWebhookChannel
]
- classmethod partial(id, token, *, session=..., client=..., bot_token=None)¶
Creates a partial
Webhook
.- Parameters
id (
int
) – The ID of the webhook.token (
str
) – The authentication token of the webhook.session (
aiohttp.ClientSession
) –The session to use to send requests with. Note that the library does not manage the session and will not close it.
New in version 2.0.
client (
Client
) –The client to initialise this webhook with. This allows it to attach the client’s internal state. If
session
is not given while this is given then the client’s internal session will be used.New in version 2.2.
bot_token (Optional[
str
]) –The bot authentication token for authenticated requests involving the webhook.
New in version 2.0.
- Raises
TypeError – Neither
session
norclient
were given.- Returns
A partial
Webhook
. A partial webhook is just a webhook object with an ID and a token.- Return type
- classmethod from_url(url, *, session=..., client=..., bot_token=None)¶
Creates a partial
Webhook
from a webhook URL.Changed in version 2.0: This function will now raise
ValueError
instead ofInvalidArgument
.- Parameters
url (
str
) – The URL of the webhook.session (
aiohttp.ClientSession
) –The session to use to send requests with. Note that the library does not manage the session and will not close it.
New in version 2.0.
client (
Client
) –The client to initialise this webhook with. This allows it to attach the client’s internal state. If
session
is not given while this is given then the client’s internal session will be used.New in version 2.2.
bot_token (Optional[
str
]) –The bot authentication token for authenticated requests involving the webhook.
New in version 2.0.
- Raises
ValueError – The URL is invalid.
TypeError – Neither
session
norclient
were given.
- Returns
A partial
Webhook
. A partial webhook is just a webhook object with an ID and a token.- Return type
- await fetch(*, prefer_auth=True)¶
This function is a coroutine.
Fetches the current webhook.
This could be used to get a full webhook from a partial webhook.
New in version 2.0.
Note
When fetching with an unauthenticated webhook, i.e.
is_authenticated()
returnsFalse
, then the returned webhook does not contain any user information.- Parameters
prefer_auth (
bool
) – Whether to use the bot token over the webhook token if available. Defaults toTrue
.- Raises
HTTPException – Could not fetch the webhook
NotFound – Could not find the webhook by this ID
ValueError – This webhook does not have a token associated with it.
- Returns
The fetched webhook.
- Return type
- await delete(*, reason=None, prefer_auth=True)¶
This function is a coroutine.
Deletes this Webhook.
- Parameters
- Raises
HTTPException – Deleting the webhook failed.
NotFound – This webhook does not exist.
Forbidden – You do not have permissions to delete this webhook.
ValueError – This webhook does not have a token associated with it.
- await edit(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)¶
This function is a coroutine.
Edits this Webhook.
Changed in version 2.0: This function will now raise
ValueError
instead ofInvalidArgument
.- Parameters
name (Optional[
str
]) – The webhook’s new default name.avatar (Optional[
bytes
]) – A bytes-like object representing the webhook’s new default avatar.channel (Optional[
abc.Snowflake
]) –The webhook’s new channel. This requires an authenticated webhook.
New in version 2.0.
reason (Optional[
str
]) –The reason for editing this webhook. Shows up on the audit log.
New in version 1.4.
prefer_auth (
bool
) –Whether to use the bot token over the webhook token if available. Defaults to
True
.New in version 2.0.
- Raises
HTTPException – Editing the webhook failed.
NotFound – This webhook does not exist.
ValueError – This webhook does not have a token associated with it or it tried editing a channel without authentication.
- property avatar¶
Returns an
Asset
for the avatar the webhook has.If the webhook does not have a traditional avatar,
None
is returned. If you want the avatar that a webhook has displayed, considerdisplay_avatar
.- Type
Optional[
Asset
]
- property channel¶
The channel this webhook belongs to.
If this is a partial webhook, then this will always return
None
.- Type
Optional[Union[
ForumChannel
,VoiceChannel
,TextChannel
]]
- property created_at¶
Returns the webhook’s creation time in UTC.
- Type
- property default_avatar¶
Returns the default avatar. This is always the blurple avatar.
New in version 2.0.
- Type
- property display_avatar¶
Returns the webhook’s display avatar.
This is either webhook’s default avatar or uploaded avatar.
New in version 2.0.
- Type
- property guild¶
The guild this webhook belongs to.
If this is a partial webhook, then this will always return
None
.- Type
Optional[
Guild
]
- is_authenticated()¶
bool
: Whether the webhook is authenticated with a bot token.New in version 2.0.
- await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., thread_name=..., wait=False, suppress_embeds=False, silent=False, applied_tags=..., poll=...)¶
This function is a coroutine.
Sends a message using the webhook.
The content must be a type that can convert to a string through
str(content)
.To upload a single file, the
file
parameter should be used with a singleFile
object.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type. You cannot mix theembed
parameter with theembeds
parameter, which must be alist
ofEmbed
objects to send.Changed in version 2.0: This function will now raise
ValueError
instead ofInvalidArgument
.- Parameters
content (
str
) – The content of the message to send.wait (
bool
) – Whether the server should wait before sending a response. This essentially means that the return type of this function changes fromNone
to aWebhookMessage
if set toTrue
. If the type of webhook isWebhookType.application
then this is always set toTrue
.username (
str
) – The username to send with this message. If no username is provided then the default username for the webhook is used.avatar_url (
str
) – The avatar URL to send with this message. If no avatar URL is provided then the default avatar for the webhook is used. If this is not a string then it is explicitly cast usingstr
.tts (
bool
) – Indicates if the message should be sent using text-to-speech.ephemeral (
bool
) –Indicates if the message should only be visible to the user. This is only available to
WebhookType.application
webhooks. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes.New in version 2.0.
file (
File
) – The file to upload. This cannot be mixed withfiles
parameter.files (List[
File
]) – A list of files to send with the content. This cannot be mixed with thefile
parameter.embed (
Embed
) – The rich embed for the content to send. This cannot be mixed withembeds
parameter.embeds (List[
Embed
]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with theembed
parameter.allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message.
New in version 1.4.
view (
discord.ui.View
) –The view to send with the message. You can only send a view if this webhook is not partial and has state attached. A webhook has state attached if the webhook is managed by the library.
New in version 2.0.
thread (
Snowflake
) –The thread to send this webhook to.
New in version 2.0.
thread_name (
str
) –The thread name to create with this webhook if the webhook belongs to a
ForumChannel
. Note that this is mutually exclusive with thethread
parameter, as this will create a new thread with the given name.New in version 2.0.
suppress_embeds (
bool
) –Whether to suppress embeds for the message. This sends the message without any embeds if set to
True
.New in version 2.0.
silent (
bool
) –Whether to suppress push and desktop notifications for the message. This will increment the mention counter in the UI, but will not actually send a notification.
New in version 2.2.
applied_tags (List[
ForumTag
]) –Tags to apply to the thread if the webhook belongs to a
ForumChannel
.New in version 2.4.
poll (
Poll
) –The poll to send with this message.
Warning
When sending a Poll via webhook, you cannot manually end it.
New in version 2.4.
- Raises
HTTPException – Sending the message failed.
NotFound – This webhook was not found.
Forbidden – The authorization token for the webhook is incorrect.
TypeError – You specified both
embed
andembeds
orfile
andfiles
orthread
andthread_name
.ValueError – The length of
embeds
was invalid, there was no token associated with this webhook orephemeral
was passed with the improper webhook type or there was no state attached with this webhook when giving it a view.
- Returns
If
wait
isTrue
then the message that was sent, otherwiseNone
.- Return type
Optional[
WebhookMessage
]
- await fetch_message(id, /, *, thread=...)¶
This function is a coroutine.
Retrieves a single
WebhookMessage
owned by this webhook.New in version 2.0.
- Parameters
- Raises
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
ValueError – There was no token associated with this webhook.
- Returns
The message asked for.
- Return type
- await edit_message(message_id, *, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None, thread=...)¶
This function is a coroutine.
Edits a message owned by this webhook.
This is a lower level interface to
WebhookMessage.edit()
in case you only have an ID.New in version 1.6.
Changed in version 2.0: The edit is no longer in-place, instead the newly edited message is returned.
Changed in version 2.0: This function will now raise
ValueError
instead ofInvalidArgument
.- Parameters
message_id (
int
) – The message ID to edit.content (Optional[
str
]) – The content to edit the message with orNone
to clear it.embeds (List[
Embed
]) – A list of embeds to edit the message with.embed (Optional[
Embed
]) – The embed to edit the message with.None
suppresses the embeds. This should not be mixed with theembeds
parameter.attachments (List[Union[
Attachment
,File
]]) –A list of attachments to keep in the message as well as new files to upload. If
[]
is passed then all attachments are removed.New in version 2.0.
allowed_mentions (
AllowedMentions
) – Controls the mentions being processed in this message. Seeabc.Messageable.send()
for more information.view (Optional[
View
]) –The updated view to update this message with. If
None
is passed then the view is removed. The webhook must have state attached, similar tosend()
.New in version 2.0.
thread (
Snowflake
) –The thread the webhook message belongs to.
New in version 2.0.
- Raises
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
TypeError – You specified both
embed
andembeds
ValueError – The length of
embeds
was invalid, there was no token associated with this webhook or the webhook had no state.
- Returns
The newly edited webhook message.
- Return type
- await delete_message(message_id, /, *, thread=...)¶
This function is a coroutine.
Deletes a message owned by this webhook.
This is a lower level interface to
WebhookMessage.delete()
in case you only have an ID.New in version 1.6.
Changed in version 2.0:
message_id
parameter is now positional-only.Changed in version 2.0: This function will now raise
ValueError
instead ofInvalidArgument
.- Parameters
- Raises
HTTPException – Deleting the message failed.
Forbidden – Deleted a message that is not yours.
ValueError – This webhook does not have a token associated with it.