API Reference¶
The following section outlines the API of discord.py-self.
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-self.
Clients¶
Client¶
- activities
- activity
- allowed_mentions
- blocked
- cached_messages
- client_activities
- client_status
- connections
- country_code
- emojis
- friends
- guilds
- initial_activities
- initial_activity
- initial_status
- latency
- notification_settings
- pending_payments
- preferred_voice_regions
- private_channels
- raw_status
- relationships
- required_action
- sessions
- settings
- status
- stickers
- tracking_settings
- user
- users
- voice_client
- voice_clients
- ws
- asyncaccept_invite
- asyncactivity_statistics
- asyncapplications
- asyncauthorize_connection
- asyncbefore_identify_hook
- asyncchange_presence
- asyncchange_voice_state
- defclear
- asyncclose
- asyncconnect
- asynccreate_application
- asynccreate_connection
- asynccreate_dm
- asynccreate_group
- asynccreate_guild
- asynccreate_payment_source
- asynccreate_subscription
- asynccreate_team
- asyncdelete_invite
- asyncdelete_recent_mention
- asyncdetectable_applications
- asyncedit_legacy_settings
- asyncemail_settings
- asyncentitlements
- @event
- asyncfetch_application
- asyncfetch_channel
- asyncfetch_connections
- asyncfetch_country_code
- asyncfetch_entitlements
- asyncfetch_eula
- asyncfetch_gift
- asyncfetch_guild
- asyncfetch_guild_preview
- asyncfetch_guilds
- asyncfetch_invite
- asyncfetch_live_build_ids
- asyncfetch_note
- asyncfetch_partial_application
- asyncfetch_payment
- asyncfetch_payment_source
- asyncfetch_preferred_voice_regions
- asyncfetch_price_tier
- asyncfetch_primary_store_listing
- asyncfetch_primary_store_listings
- asyncfetch_private_channels
- asyncfetch_public_application
- asyncfetch_public_applications
- asyncfetch_published_store_listing
- asyncfetch_published_store_listings
- asyncfetch_relationships
- asyncfetch_settings
- asyncfetch_sku
- asyncfetch_sku_subscription_plans
- asyncfetch_skus_subscription_plans
- asyncfetch_stage_instance
- asyncfetch_sticker
- asyncfetch_sticker_pack
- asyncfetch_store_listing
- asyncfetch_subscription
- asyncfetch_team
- asyncfetch_template
- asyncfetch_tracking_settings
- asyncfetch_user
- asyncfetch_user_profile
- asyncfetch_webhook
- asyncfetch_widget
- defget_all_channels
- defget_all_members
- defget_channel
- defget_emoji
- defget_guild
- defget_partial_messageable
- defget_relationship
- defget_stage_instance
- defget_sticker
- defget_user
- asyncgiftable_entitlements
- asyncguild_affinities
- asyncinvites
- defis_closed
- defis_on_mobile
- defis_ready
- defis_ws_ratelimited
- asyncjoin_active_developer_program
- asyncjoin_guild
- asyncleave_active_developer_program
- asyncleave_guild
- asynclegacy_settings
- asynclibrary
- asynclogin
- asyncnotes
- asyncon_error
- asyncpayment_sources
- async forpayments
- asyncpremium_entitlements
- asyncpremium_guild_subscription_cooldown
- asyncpremium_guild_subscription_slots
- asyncpremium_guild_subscriptions
- asyncpremium_subscription_plans
- asyncpremium_usage
- asyncpreview_subscription
- asyncprice_tiers
- asyncpricing_promotion
- asyncpromotions
- async forrecent_mentions
- asyncrelationship_activity_statistics
- asyncrevoke_invites
- defrun
- asyncsearch_companies
- asyncsend_friend_request
- asyncsetup_hook
- asyncstart
- asyncsticker_packs
- asyncsubscriptions
- asyncteams
- asynctrial_offer
- asyncuser_affinities
- asyncwait_for
- asyncwait_until_ready
- class discord.Client(**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 inNonedisables 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.member_cache_flags (
MemberCacheFlags) –Allows for finer control over how the library caches members. If not given, defaults to cache as much as possible.
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.New in version 1.5.
request_guilds (
bool) –Whether to request guilds at startup. Defaults to True.
New in version 2.0.
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.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 isFalsethen your system clock is used to calculate how long to sleep for. If this is set toFalseit 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 isFalsethen 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.
sync_presence (
bool) –Whether to keep presences up-to-date across clients. The default behavior is
True(what the client does).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.
captcha_handler (Optional[
CaptchaHandler]) –A class that solves captcha challenges.
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
RateLimitedwill 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.0seconds.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,
TypeErroris raised.Example
@client.event async def on_ready(): print('Ready!')
Changed in version 2.0:
coroparameter 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.
Noneif not logged in.- Type
Optional[
ClientUser]
- property required_action¶
The required action for the current user. A required action is something Discord requires you to do to continue using your account.
New in version 2.0.
- Type
Optional[
RequiredActionType]
- property stickers¶
The stickers that the connected client has.
New in version 2.0.
- Type
Sequence[
GuildSticker]
- property sessions¶
The gateway sessions that the current user is connected in with.
When connected, this includes a representation of the library’s session and an “all” session representing the user’s overall presence.
New in version 2.0.
- Type
Sequence[
Session]
- property cached_messages¶
Read-only list of messages the connected client has cached.
New in version 1.1.
- Type
Sequence[
Message]
- property connections¶
The connections that the connected client has.
These connections don’t have the
Connection.metadataattribute populated.New in version 2.0.
Note
Due to a Discord limitation, removed connections may not be removed from this cache.
- Type
Sequence[
Connection]
- property private_channels¶
The private channels that the connected client is participating on.
- Type
Sequence[
abc.PrivateChannel]
- property relationships¶
Returns all the relationships that the connected client has.
New in version 2.0.
- Type
Sequence[
Relationship]
- property friends¶
Returns all the users that the connected client is friends with.
New in version 2.0.
- Type
List[
Relationship]
- property blocked¶
Returns all the users that the connected client has blocked.
New in version 2.0.
- Type
List[
Relationship]
- get_relationship(user_id, /)¶
Retrieves the
Relationship, if applicable.New in version 2.0.
- Parameters
user_id (
int) – The user ID to check if we have a relationship with them.- Returns
The relationship, if available.
- Return type
Optional[
Relationship]
- property settings¶
Returns the user’s settings.
New in version 2.0.
- Type
Optional[
UserSettings]
- property tracking_settings¶
Returns your tracking consents, if available.
New in version 2.0.
- Type
Optional[
TrackingSettings]
- property voice_clients¶
Represents a list of voice connections.
These are usually
VoiceClientinstances.- Type
List[
VoiceProtocol]
- property country_code¶
The country code of the client.
Noneif not connected.New in version 2.0.
- Type
Optional[
str]
- property preferred_voice_regions¶
Geo-ordered list of voice regions the connected client can use.
New in version 2.0.
- Type
List[
str]
- property pending_payments¶
The pending payments that the connected client has.
New in version 2.0.
- Type
Sequence[
Payment]
- 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_methodparameter is now positional-only and instead of writing tosys.stderrit logs instead.
- await before_identify_hook(*, 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 does nothing.
New in version 1.4.
- Parameters
initial (
bool) – Whether this IDENTIFY is the first initial IDENTIFY.
- await setup_hook()¶
This function is a coroutine.
A coroutine to be called to setup the client, by default this is blank.
To perform asynchronous setup after the user 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().Warning
Logging on with a user token is unfortunately against the Discord Terms of Service and doing so might potentially get your account banned. Use this at your own risk.
- Parameters
token (
str) – The authentication token.- 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 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 client can be considered “re-opened”, i.e.
is_closed()andis_ready()both returnFalsealong with the bot’s internal cache cleared.
- await start(token, *, reconnect=True)¶
This function is a coroutine.
A shorthand coroutine for
login()+connect().- Parameters
- 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
Noneto thelog_handlerparameter.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.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 bad tokens).log_handler (Optional[
logging.Handler]) –The log handler to use for the library’s logger. If this is
Nonethen the library will not set up anything logging related. Logging will still work ifNoneis passed, though it is your responsibility to set it up.The default log handler if not provided 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_handlerparameter 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 toTruethen the root logger is set up as well.Defaults to
False.New in version 2.0.
- property voice_client¶
Returns the
VoiceProtocolassociated with private calls, if any.- Type
Optional[
VoiceProtocol]
- property notification_settings¶
Returns the notification settings for private channels.
If not found, an instance is created with defaults applied. This follows Discord behaviour.
New in version 2.0.
- Type
- property initial_activity¶
The primary activity set upon logging in.
Note
The client may be setting multiple activities, these can be accessed under
initial_activities.- Type
Optional[
BaseActivity]
- property initial_activities¶
The activities set upon logging in.
- Type
List[
BaseActivity]
- is_on_mobile()¶
bool: A helper function that determines if the user is active on a mobile device.New in version 2.0.
- property activities¶
Returns the activities the client is currently doing.
New in version 2.0.
Note
Due to a Discord API limitation, this may be
Noneif the user is listening to a song on Spotify with a title longer than 128 characters. See GH-1738 for more information.- Type
Tuple[Union[
BaseActivity,Spotify]]
- property activity¶
Returns the primary activity the client is currently doing. Could be
Noneif no activity is being done.New in version 2.0.
Note
Due to a Discord API limitation, this may be
Noneif the user is listening to a song on Spotify with a title longer than 128 characters. See GH-1738 for more information.Note
The client may have multiple activities, these can be accessed under
activities.- Type
Optional[Union[
BaseActivity,Spotify]]
- property client_activities¶
Returns the activities the client is currently doing through this library, if applicable.
New in version 2.0.
- Type
Tuple[Union[
BaseActivity,Spotify]]
- 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:
idparameter is now positional-only.- Parameters
id (
int) – The ID to search for.- Returns
The returned channel or
Noneif 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()andguildproperties 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
Noneif not found.- Return type
Optional[
StageInstance]
- get_guild(id, /)¶
Returns a guild with the given ID.
Changed in version 2.0:
idparameter is now positional-only.
- get_user(id, /)¶
Returns a user with the given ID.
Changed in version 2.0:
idparameter is now positional-only.
- get_emoji(id, /)¶
Returns an emoji with the given ID.
Changed in version 2.0:
idparameter 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(). orsticker_packs().- Returns
The sticker or
Noneif not found.- Return type
Optional[
GuildSticker]
- for ... in get_all_channels()¶
A generator that retrieves every
abc.GuildChannelthe 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.GuildChanneldoes 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
Memberthe 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
timeoutparameter is passed ontoasyncio.wait_for(). By default, it does not timeout. Note that this does propagate theasyncio.TimeoutErrorfor you in case of timeout and is provided for ease of use.In case the event returns multiple arguments, a
tuplecontaining 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:
eventparameter 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
tupleof multiple arguments that mirrors the parameters passed in the event reference.- Return type
Any
- await change_presence(*, activity=None, activities=None, status=None, afk=False, edit_settings=True)¶
This function is a coroutine.
Changes the client’s presence.
Changed in version 2.0: Edits are no longer in place. Added option to update settings.
Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.Example
game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game)
- Parameters
activity (Optional[
BaseActivity]) – The activity being done.Noneif no activity is done.activities (Optional[List[
BaseActivity]]) – A list of the activities being done.Noneif no activities are done. Cannot be sent withactivity.status (Optional[
Status]) – Indicates what status to change to. IfNone, thenStatus.onlineis used.afk (
bool) – Indicates if you are going AFK. This allows the Discord client to know how to handle push notifications better for you in case you are actually idle and not lying.edit_settings (
bool) – Whether to update the settings with the new status and/or custom activity. This will broadcast the change and cause all connected (official) clients to change presence as well. Required for setting/editingexpires_atfor custom activities. It’s not recommended to change this, as setting it toFalsecauses undefined behavior.
- Raises
TypeError – The
activityparameter is not the proper type. Bothactivityandactivitieswere passed.
- await change_voice_state(*, channel, self_mute=False, self_deaf=False, self_video=False, preferred_region=...)¶
This function is a coroutine.
Changes client’s private channel voice state.
New in version 2.0.
- Parameters
channel (Optional[
Snowflake]) – Channel the client wants to join (must be a private channel). UseNoneto disconnect.self_mute (
bool) – Indicates if the client should be self-muted.self_deaf (
bool) – Indicates if the client should be self-deafened.self_video (
bool) – Indicates if the client is using video. Untested & unconfirmed (do not use).preferred_region (Optional[
str]) – The preferred region to connect to.
- await fetch_guilds(*, with_counts=True)¶
This function is a coroutine.
Retrieves all your guilds.
Note
This method is an API call. For general usage, consider
guildsinstead.- Parameters
with_counts (
bool) – Whether to fillGuild.approximate_member_countandGuild.approximate_presence_count.- Raises
HTTPException – Getting the guilds failed.
- Returns
A list of all your guilds.
- Return type
List[
UserGuild]
- await fetch_template(code)¶
This function is a coroutine.
Gets a
Templatefrom 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
Guildfrom an ID.Note
Using this, you will not receive
Guild.channelsandGuild.members.Note
This method is an API call. For general usage, consider
get_guild()instead.Changed in version 2.0:
guild_idparameter 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 in
Guild.approximate_member_countandGuild.approximate_presence_count.New in version 2.0.
- Raises
Forbidden – You do not have access to the guild.
HTTPException – Getting the guild failed.
- Returns
The guild from the ID.
- Return type
- await fetch_guild_preview(guild_id, /)¶
This function is a coroutine.
Retrieves a public
Guildpreview from an ID.New in version 2.0.
- Raises
NotFound – Guild with given ID does not exist/is not public.
HTTPException – Retrieving 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.Changed in version 2.0:
nameandiconparameters are now keyword-only. Theregionparameter has been removed.Changed in version 2.0: This function will now raise
ValueErrorinstead 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 join_guild(guild_id, /, lurking=False)¶
This function is a coroutine.
Joins a discoverable
Guild.- Parameters
- Raises
NotFound – Guild with given ID does not exist/have discovery enabled.
HTTPException – Joining the guild failed.
- Returns
The guild that was joined.
- Return type
- await leave_guild(guild, /, lurking=...)¶
This function is a coroutine.
Leaves a guild. Equivalent to
Guild.leave().New in version 2.0.
- Parameters
- Raises
HTTPException – Leaving the guild failed.
- await fetch_stage_instance(channel_id, /)¶
This function is a coroutine.
Gets a
StageInstancefor 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 invites()¶
This function is a coroutine.
Gets a list of the user’s friend
Invites.New in version 2.0.
- Raises
HTTPException – Getting the invites failed.
- Returns
The list of invites.
- Return type
List[
Invite]
- await fetch_invite(url, /, *, with_counts=True, with_expiration=True, scheduled_event_id=None)¶
This function is a coroutine.
Gets an
Invitefrom 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
Invitewill bePartialInviteGuildandPartialInviteChannelrespectively.Changed in version 2.0:
urlparameter is now positional-only.- 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_countandInvite.approximate_presence_countfields.with_expiration (
bool) –Whether to include the expiration date of the invite. This fills the
Invite.expires_atfield.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_idparameter when using this parameter.New in version 2.0.
- Raises
ValueError – The url contains an
event_id, butscheduled_event_idhas 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 accept_invite(url, /)¶
This function is a coroutine.
Uses an invite. Either joins a guild, joins a group DM, or adds a friend.
New in version 2.0.
- Parameters
url (Union[
Invite,str]) – The Discord invite ID, URL (must be a discord.gg URL), orInvite.- Raises
HTTPException – Using the invite failed.
- Returns
The accepted invite.
- Return type
- await delete_invite(invite, /)¶
This function is a coroutine.
Revokes an
Invite, URL, or ID to an invite.You must have
manage_channelsin the associated guild to do this.Changed in version 2.0:
inviteparameter is now positional-only.Changed in version 2.0: The function now returns the deleted invite.
- await revoke_invites()¶
This function is a coroutine.
Revokes all of the user’s friend
Invites.New in version 2.0.
- Raises
HTTPException – Revoking the invites failed.
- Returns
The revoked invites.
- Return type
List[
Invite]
- await fetch_widget(guild_id, /)¶
This function is a coroutine.
Gets a
Widgetfrom a guild ID.Note
The guild must have the widget enabled to get this information.
Changed in version 2.0:
guild_idparameter 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 fetch_user(user_id, /)¶
This function is a coroutine.
Retrieves a
discord.Userbased 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 member cache enabled, consider
get_user()instead.Warning
This API route is not well-used by the Discord client and may increase your chances at getting detected. Consider
fetch_user_profile()if you share a guild/relationship with the user.Changed in version 2.0:
user_idparameter 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_user_profile(user_id, /, *, with_mutual_guilds=True, with_mutual_friends_count=False, with_mutual_friends=True)¶
This function is a coroutine.
Retrieves a
UserProfilebased on their user ID.You must share a guild, be friends with this user, or have an incoming friend request from them to get this information (unless the user is a bot).
Changed in version 2.0:
user_idparameter is now positional-only.- Parameters
user_id (
int) – The ID of the user to fetch their profile for.with_mutual_guilds (
bool) –Whether to fetch mutual guilds. This fills in
UserProfile.mutual_guilds.New in version 2.0.
with_mutual_friends_count (
bool) –Whether to fetch the number of mutual friends. This fills in
UserProfile.mutual_friends_count.New in version 2.0.
with_mutual_friends (
bool) –Whether to fetch mutual friends. This fills in
UserProfile.mutual_friendsandUserProfile.mutual_friends_count, but requires an extra API call.New in version 2.0.
- Raises
NotFound – A user with this ID does not exist.
Forbidden – You do not have a mutual with this user, and and the user is not a bot.
HTTPException – Fetching the profile failed.
- Returns
The profile of the user.
- Return type
- await fetch_channel(channel_id, /)¶
This function is a coroutine.
Retrieves a
abc.GuildChannel,abc.PrivateChannel, orThreadwith 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_idparameter 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
Webhookwith the specified ID.Changed in version 2.0:
webhook_idparameter 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
Stickerwith 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 sticker_packs()¶
This function is a coroutine.
Retrieves all available default sticker packs.
New in version 2.0.
- Raises
HTTPException – Retrieving the sticker packs failed.
- Returns
All available sticker packs.
- Return type
List[
StickerPack]
- await fetch_sticker_pack(pack_id, /)¶
This function is a coroutine.
Retrieves a sticker pack with the specified ID.
New in version 2.0.
- Raises
NotFound – A sticker pack with that ID was not found.
HTTPException – Retrieving the sticker packs failed.
- Returns
The sticker pack you requested.
- Return type
- await notes()¶
This function is a coroutine.
Retrieves a list of
Noteobjects representing all your notes.New in version 1.9.
- Raises
HTTPException – Retrieving the notes failed.
- Returns
All your notes.
- Return type
List[
Note]
- await fetch_note(user_id, /)¶
This function is a coroutine.
Retrieves a
Notefor the specified user ID.New in version 1.9.
Changed in version 2.0:
user_idparameter is now positional-only.- Parameters
user_id (
int) – The ID of the user to fetch the note for.- Raises
HTTPException – Retrieving the note failed.
- Returns
The note you requested.
- Return type
- await fetch_connections()¶
This function is a coroutine.
Retrieves all of your connections.
New in version 2.0.
- Raises
HTTPException – Retrieving your connections failed.
- Returns
All your connections.
- Return type
List[
Connection]
- await authorize_connection(type, two_way_link_type=None, two_way_user_code=None, continuation=False)¶
This function is a coroutine.
Retrieves a URL to authorize a connection with a third-party service.
New in version 2.0.
- Parameters
type (
ConnectionType) – The type of connection to authorize.two_way_link_type (Optional[
ClientType]) – The type of two-way link to use, if any.two_way_user_code (Optional[
str]) – The device code to use for two-way linking, if any.continuation (
bool) – Whether this is a continuation of a previous authorization.
- Raises
HTTPException – Authorizing the connection failed.
- Returns
The URL to redirect the user to.
- Return type
- await create_connection(type, code, state, *, two_way_link_code=None, insecure=True, friend_sync=...)¶
This function is a coroutine.
Creates a new connection.
This is a low-level method that requires data obtained from other APIs.
New in version 2.0.
- Parameters
type (
ConnectionType) – The type of connection to add.code (
str) – The authorization code for the connection.state (
str) – The state used to authorize the connection.two_way_link_code (Optional[
str]) – The code to use for two-way linking, if any.insecure (
bool) – Whether the authorization is insecure.friend_sync (
bool) –Whether friends are synced over the connection.
Defaults to
TrueforConnectionType.facebookandConnectionType.contacts, elseFalse.
- Raises
HTTPException – Creating the connection failed.
- await fetch_private_channels()¶
This function is a coroutine.
Retrieves all your private channels.
New in version 2.0.
Note
This method is an API call. For general usage, consider
private_channelsinstead.- Raises
HTTPException – Retrieving your private channels failed.
- Returns
All your private channels.
- Return type
List[
abc.PrivateChannel]
- await fetch_settings()¶
This function is a coroutine.
Retrieves your user settings.
New in version 2.0.
Note
This method is an API call. For general usage, consider
settingsinstead.- Raises
HTTPException – Retrieving your settings failed.
- Returns
The current settings for your account.
- Return type
- await legacy_settings()¶
This function is a coroutine.
Retrieves your legacy user settings.
New in version 2.0.
Deprecated since version 2.0.
Note
This method is no longer the recommended way to fetch your settings. Use
fetch_settings()instead.Note
This method is an API call. For general usage, consider
settingsinstead.- Raises
HTTPException – Retrieving your settings failed.
- Returns
The current settings for your account.
- Return type
- await email_settings()¶
This function is a coroutine.
Retrieves your email settings.
New in version 2.0.
- Raises
HTTPException – Getting the email settings failed.
- Returns
The email settings.
- Return type
- await fetch_tracking_settings()¶
This function is a coroutine.
Retrieves your Discord tracking consents.
New in version 2.0.
- Raises
HTTPException – Retrieving the tracking settings failed.
- Returns
The tracking settings.
- Return type
- await edit_legacy_settings(**kwargs)¶
This function is a coroutine.
Edits the client user’s settings.
Changed in version 2.0: The edit is no longer in-place, instead the newly edited settings are returned.
Deprecated since version 2.0.
- Parameters
activity_restricted_guilds (List[
Snowflake]) –A list of guilds that your current activity will not be shown in.
New in version 2.0.
activity_joining_restricted_guilds (List[
Snowflake]) –A list of guilds that will not be able to join your current activity.
New in version 2.0.
afk_timeout (
int) – How long (in seconds) the user needs to be AFK until Discord sends push notifications to mobile device (30-600).allow_accessibility_detection (
bool) – Whether to allow Discord to track screen reader usage.animate_emojis (
bool) – Whether to animate emojis in the chat.animate_stickers (
StickerAnimationOptions) – Whether to animate stickers in the chat.contact_sync_enabled (
bool) – Whether to enable the contact sync on Discord mobile.convert_emoticons (
bool) – Whether to automatically convert emoticons into emojis (e.g. :) -> 😃).default_guilds_restricted (
bool) – Whether to automatically disable DMs between you and members of new guilds you join.detect_platform_accounts (
bool) – Whether to automatically detect accounts from services like Steam and Blizzard when you open the Discord client.developer_mode (
bool) – Whether to enable developer mode.disable_games_tab (
bool) – Whether to disable the showing of the Games tab.enable_tts_command (
bool) – Whether to allow TTS messages to be played/sent.explicit_content_filter (
UserContentFilter) – The filter for explicit content in all messages.friend_source_flags (
FriendSourceFlags) – Who can add you as a friend.friend_discovery_flags (
FriendDiscoveryFlags) – How you get recommended friends.gif_auto_play (
bool) – Whether to automatically play GIFs that are in the chat.guild_positions (List[
Snowflake]) – A list of guilds in order of the guild/guild icons that are on the left hand side of the UI.inline_attachment_media (
bool) – Whether to display attachments when they are uploaded in chat.inline_embed_media (
bool) – Whether to display videos and images from links posted in chat.locale (
Locale) – The RFC 3066 language identifier of the locale to use for the language of the Discord client.message_display_compact (
bool) – Whether to use the compact Discord display mode.native_phone_integration_enabled (
bool) – Whether to enable the new Discord mobile phone number friend requesting features.passwordless (
bool) – Whether to enable passwordless login.render_embeds (
bool) – Whether to render embeds that are sent in the chat.render_reactions (
bool) – Whether to render reactions that are added to messages.restricted_guilds (List[
Snowflake]) – A list of guilds that you will not receive DMs from.show_current_game (
bool) – Whether to display the game that you are currently playing.stream_notifications_enabled (
bool) – Whether stream notifications for friends will be received.theme (
Theme) – The overall theme of the Discord UI.timezone_offset (
int) – The timezone offset to use.view_nsfw_commands (
bool) –Whether to show NSFW application commands in DMs.
New in version 2.0.
view_nsfw_guilds (
bool) –Whether to show NSFW guilds on iOS.
New in version 2.0.
- Raises
HTTPException – Editing the settings failed.
- Returns
The client user’s updated settings.
- Return type
- await fetch_relationships()¶
This function is a coroutine.
Retrieves all your relationships.
New in version 2.0.
Note
This method is an API call. For general usage, consider
relationshipsinstead.- Raises
HTTPException – Retrieving your relationships failed.
- Returns
All your relationships.
- Return type
List[
Relationship]
- await fetch_country_code()¶
This function is a coroutine.
Retrieves the country code of the client.
New in version 2.0.
- Raises
HTTPException – Retrieving the country code failed.
- Returns
The country code of the client.
- Return type
- await fetch_preferred_voice_regions()¶
This function is a coroutine.
Retrieves the preferred voice regions of the client.
New in version 2.0.
- Raises
HTTPException – Retrieving the preferred voice regions failed.
- Returns
The preferred voice regions of the client.
- Return type
List[
str]
- await create_dm(user, /)¶
This function is a coroutine.
Creates a
DMChannelwith this user.This should be rarely called, as this is done transparently for most people.
New in version 2.0.
- await create_group(*recipients)¶
This function is a coroutine.
Creates a group direct message with the recipients provided. These recipients must be have a relationship of type
RelationshipType.friend.New in version 2.0.
- Parameters
*recipients (
Snowflake) – An argumentlistofdiscord.Userto have in your group.- Raises
HTTPException – Failed to create the group direct message.
- Returns
The new group channel.
- Return type
- await send_friend_request(*args)¶
This function is a coroutine.
Sends a friend request to another user.
This function can be used in multiple ways.
New in version 2.0.
# Passing a user object: await client.send_friend_request(user) # Passing a stringified user: await client.send_friend_request('Jake#0001') # Passing a username and discriminator: await client.send_friend_request('Jake', '0001')
- Parameters
user (Union[
discord.User,str]) – The user to send the friend request to.username (
str) – The username of the user to send the friend request to.discriminator (
str) – The discriminator of the user to send the friend request to.
- Raises
Forbidden – Not allowed to send a friend request to this user.
HTTPException – Sending the friend request failed.
TypeError – More than 2 parameters or less than 1 parameter was passed.
- await applications(*, with_team_applications=True)¶
This function is a coroutine.
Retrieves all applications owned by you.
New in version 2.0.
- Parameters
with_team_applications (
bool) – Whether to include applications owned by teams you’re a part of.- Raises
HTTPException – Retrieving the applications failed.
- Returns
The applications you own.
- Return type
List[
Application]
- await detectable_applications()¶
This function is a coroutine.
Retrieves the list of applications detectable by the Discord client.
New in version 2.0.
- Raises
HTTPException – Retrieving the applications failed.
- Returns
The applications detectable by the Discord client.
- Return type
List[
PartialApplication]
- await fetch_application(application_id, /)¶
This function is a coroutine.
Retrieves the application with the given ID.
The application must be owned by you or a team you are a part of.
New in version 2.0.
- Parameters
application_id (
int) – The ID of the application to fetch.- Raises
NotFound – The application was not found.
Forbidden – You do not own the application.
HTTPException – Retrieving the application failed.
- Returns
The retrieved application.
- Return type
- await fetch_partial_application(application_id, /)¶
This function is a coroutine.
Retrieves the partial application with the given ID.
New in version 2.0.
- Parameters
application_id (
int) – The ID of the partial application to fetch.- Raises
NotFound – The partial application was not found.
HTTPException – Retrieving the partial application failed.
- Returns
The retrieved application.
- Return type
- await fetch_public_application(application_id, /, *, with_guild=False)¶
This function is a coroutine.
Retrieves the public application with the given ID.
New in version 2.0.
- Parameters
- Raises
NotFound – The public application was not found.
HTTPException – Retrieving the public application failed.
- Returns
The retrieved application.
- Return type
- await fetch_public_applications(*application_ids)¶
This function is a coroutine.
Retrieves a list of public applications. Only found applications are returned.
New in version 2.0.
- Parameters
*application_ids (
int) – The IDs of the public applications to fetch.- Raises
HTTPException – Retrieving the applications failed.
- Returns
The public applications.
- Return type
List[
PartialApplication]
- await teams(*, with_payout_account_status=False)¶
This function is a coroutine.
Retrieves all the teams you’re a part of.
New in version 2.0.
- Parameters
with_payout_account_status (
bool) – Whether to return the payout account status of the teams.- Raises
HTTPException – Retrieving the teams failed.
- Returns
The teams you’re a part of.
- Return type
List[
Team]
- await fetch_team(team_id, /)¶
This function is a coroutine.
Retrieves the team with the given ID.
You must be a part of the team.
New in version 2.0.
- Parameters
id (
int) – The ID of the team to fetch.- Raises
NotFound – The team was not found.
Forbidden – You are not a part of the team.
HTTPException – Retrieving the team failed.
- Returns
The retrieved team.
- Return type
- await create_application(name, /, *, team=None)¶
This function is a coroutine.
Creates an application.
New in version 2.0.
- Parameters
- Raises
HTTPException – Failed to create the application.
- Returns
The newly-created application.
- Return type
- await create_team(name, /)¶
This function is a coroutine.
Creates a team.
New in version 2.0.
- Parameters
name (
str) – The name of the team.- Raises
HTTPException – Failed to create the team.
- Returns
The newly-created team.
- Return type
- await search_companies(query, /)¶
This function is a coroutine.
Query your created companies.
New in version 2.0.
- Parameters
query (
str) – The query to search for.- Raises
HTTPException – Searching failed.
- Returns
The companies found.
- Return type
List[
Company]
- await activity_statistics()¶
This function is a coroutine.
Retrieves the available activity usage statistics for your owned applications.
New in version 2.0.
- Raises
HTTPException – Retrieving the statistics failed.
- Returns
The activity statistics.
- Return type
- await relationship_activity_statistics()¶
This function is a coroutine.
Retrieves the available activity usage statistics for your relationships’ owned applications.
New in version 2.0.
- Raises
HTTPException – Retrieving the statistics failed.
- Returns
The activity statistics.
- Return type
- await payment_sources()¶
This function is a coroutine.
Retrieves all the payment sources for your account.
New in version 2.0.
- Raises
HTTPException – Retrieving the payment sources failed.
- Returns
The payment sources.
- Return type
List[
PaymentSource]
- await fetch_payment_source(source_id, /)¶
This function is a coroutine.
Retrieves the payment source with the given ID.
New in version 2.0.
- Parameters
source_id (
int) – The ID of the payment source to fetch.- Raises
NotFound – The payment source was not found.
HTTPException – Retrieving the payment source failed.
- Returns
The retrieved payment source.
- Return type
- await create_payment_source(*, token, payment_gateway, billing_address, billing_address_token=..., return_url=None, bank=None)¶
This function is a coroutine.
Creates a payment source.
This is a low-level method that requires data obtained from other APIs.
New in version 2.0.
- Parameters
token (
str) – The payment source token.payment_gateway (
PaymentGateway) – The payment gateway to use.billing_address (
BillingAddress) – The billing address to use.billing_address_token (Optional[
str]) – The billing address token. If not provided, the library will fetch it for you. Not required for all payment gateways.return_url (Optional[
str]) – The URL to return to after the payment source is created.bank (Optional[
str]) – The bank information for the payment source. Not required for most payment gateways.
- Raises
HTTPException – Creating the payment source failed.
- Returns
The newly-created payment source.
- Return type
- await subscriptions(limit=None, with_inactive=False)¶
This function is a coroutine.
Retrieves all the subscriptions on your account.
New in version 2.0.
- Parameters
- Raises
HTTPException – Retrieving the subscriptions failed.
- Returns
Your account’s subscriptions.
- Return type
List[
Subscription]
This function is a coroutine.
Retrieves all the premium guild subscriptions (boosts) on your account.
New in version 2.0.
- Raises
HTTPException – Retrieving the subscriptions failed.
- Returns
Your account’s premium guild subscriptions.
- Return type
List[
PremiumGuildSubscription]
This function is a coroutine.
Retrieves all the premium guild subscription (boost) slots available on your account.
New in version 2.0.
- Raises
HTTPException – Retrieving the subscriptions failed.
- Returns
Your account’s premium guild subscription slots.
- Return type
This function is a coroutine.
Retrieves the cooldown for your premium guild subscriptions (boosts).
New in version 2.0.
- Raises
HTTPException – Retrieving the cooldown failed.
- Returns
Your account’s premium guild subscription cooldown.
- Return type
- await fetch_subscription(subscription_id, /)¶
This function is a coroutine.
Retrieves the subscription with the given ID.
New in version 2.0.
- Parameters
subscription_id (
int) – The ID of the subscription to fetch.- Raises
NotFound – The subscription was not found.
HTTPException – Retrieving the subscription failed.
- Returns
The retrieved subscription.
- Return type
- await preview_subscription(items, *, payment_source=None, currency='usd', trial=None, apply_entitlements=True, renewal=False, code=None, metadata=None, guild=None)¶
This function is a coroutine.
Preview an invoice for the subscription with the given parameters.
All parameters are optional and default to the current subscription values.
New in version 2.0.
- Parameters
items (List[
SubscriptionItem]) – The items the previewed subscription should have.payment_source (Optional[
PaymentSource]) – The payment source the previewed subscription should be paid with.currency (
str) – The currency the previewed subscription should be paid in.trial (Optional[
SubscriptionTrial]) – The trial plan the previewed subscription should be on.apply_entitlements (
bool) – Whether to apply entitlements (credits) to the previewed subscription.renewal (
bool) – Whether the previewed subscription should be a renewal.code (Optional[
str]) – Unknown.metadata (Optional[
Metadata]) – Extra metadata about the subscription.guild (Optional[
Guild]) – The guild the previewed subscription’s entitlements should be applied to.
- Raises
HTTPException – Failed to preview the invoice.
- Returns
The previewed invoice.
- Return type
- await create_subscription(items, payment_source, currency='usd', *, trial=None, payment_source_token=None, purchase_token=None, return_url=None, gateway_checkout_context=None, code=None, metadata=None, guild=None)¶
This function is a coroutine.
Creates a new subscription.
New in version 2.0.
- Parameters
items (List[
SubscriptionItem]) – The items in the subscription.payment_source (
PaymentSource) – The payment source to pay with.currency (
str) – The currency to pay with.trial (Optional[
SubscriptionTrial]) – The trial to apply to the subscription.payment_source_token (Optional[
str]) – The token used to authorize with the payment source.purchase_token (Optional[
str]) – The purchase token to use.return_url (Optional[
str]) – The URL to return to after the payment is complete.gateway_checkout_context (Optional[
str]) – The current checkout context.code (Optional[
str]) – Unknown.metadata (Optional[
Metadata]) – Extra metadata about the subscription.guild (Optional[
Guild]) – The guild the subscription’s entitlements should be applied to.
- Raises
HTTPException – Creating the subscription failed.
- Returns
The newly-created subscription.
- Return type
- async for ... in payments(*, limit=100, before=None, after=None, oldest_first=None)¶
Returns an asynchronous iterator that enables receiving your payments.
New in version 2.0.
Examples
Usage
counter = 0 async for payment in client.payments(limit=200): if payment.is_purchased_externally(): counter += 1
Flattening into a list:
payments = [payment async for payment in client.payments(limit=123)] # payments is now a list of Payment...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of payments to retrieve. IfNone, retrieves every payment you have made. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve payments before this date or payment. 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 messages after this date or payment. 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.oldest_first (Optional[
bool]) – If set toTrue, return payments in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises
HTTPException – The request to get payments failed.
- Yields
Payment– The payment made.
- await fetch_payment(payment_id)¶
This function is a coroutine.
Retrieves the payment with the given ID.
New in version 2.0.
- Parameters
payment_id (
int) – The ID of the payment to fetch.- Raises
HTTPException – Fetching the payment failed.
- Returns
The retrieved payment.
- Return type
- await promotions(claimed=False)¶
This function is a coroutine.
Retrieves all the promotions available for your account.
New in version 2.0.
- Parameters
claimed (
bool) – Whether to only retrieve claimed promotions. These will havePromotion.claimed_atandPromotion.codeset.- Raises
HTTPException – Retrieving the promotions failed.
- Returns
The promotions available for you.
- Return type
List[
Promotion]
- await trial_offer()¶
This function is a coroutine.
Retrieves the current trial offer for your account.
New in version 2.0.
- Raises
NotFound – You do not have a trial offer.
HTTPException – Retrieving the trial offer failed.
- Returns
The trial offer for your account.
- Return type
- await pricing_promotion()¶
This function is a coroutine.
Retrieves the current localized pricing promotion for your account, if any.
This also updates your current country code.
New in version 2.0.
- Raises
HTTPException – Retrieving the pricing promotion failed.
- Returns
The pricing promotion for your account, if any.
- Return type
Optional[
PricingPromotion]
- await library()¶
This function is a coroutine.
Retrieves the applications in your library.
New in version 2.0.
- Raises
HTTPException – Retrieving the library failed.
- Returns
The applications in your library.
- Return type
List[
LibraryApplication]
- await entitlements(*, with_sku=True, with_application=True, entitlement_type=None)¶
This function is a coroutine.
Retrieves all the entitlements for your account.
New in version 2.0.
- Parameters
with_sku (
bool) – Whether to include the SKU information in the returned entitlements.with_application (
bool) – Whether to include the application in the returned entitlements’ SKUs. The premium subscription application is always returned.entitlement_type (Optional[
EntitlementType]) – The type of entitlement to retrieve. IfNonethen all entitlements are returned.
- Raises
HTTPException – Retrieving the entitlements failed.
- Returns
The entitlements for your account.
- Return type
List[
Entitlement]
- await giftable_entitlements()¶
This function is a coroutine.
Retrieves the giftable entitlements for your account.
These are entitlements you are able to gift to other users.
New in version 2.0.
- Raises
HTTPException – Retrieving the giftable entitlements failed.
- Returns
The giftable entitlements for your account.
- Return type
List[
Entitlement]
This function is a coroutine.
Retrieves the entitlements this account has granted for the premium application.
These are the entitlements used for premium subscriptions, referred to as “Nitro Credits”.
New in version 2.0.
- Parameters
exclude_consumed (
bool) – Whether to exclude consumed entitlements.- Raises
HTTPException – Fetching the entitlements failed.
- Returns
The entitlements retrieved.
- Return type
List[
Entitlement]
- await fetch_entitlements(application_id, /, *, exclude_consumed=True)¶
This function is a coroutine.
Retrieves the entitlements this account has granted for the given application.
- Parameters
- Raises
HTTPException – Fetching the entitlements failed.
- Returns
The entitlements retrieved.
- Return type
List[
Entitlement]
- await fetch_gift(code, *, with_application=False, with_subscription_plan=True)¶
This function is a coroutine.
Retrieves a gift with the given code.
New in version 2.0.
- Parameters
- Raises
NotFound – The gift does not exist.
HTTPException – Retrieving the gift failed.
- Returns
The retrieved gift.
- Return type
- await fetch_sku(sku_id, /, *, localize=True)¶
This function is a coroutine.
Retrieves a SKU with the given ID.
New in version 2.0.
- Parameters
- Raises
NotFound – The SKU does not exist.
Forbidden – You do not have access to the SKU.
HTTPException – Retrieving the SKU failed.
- Returns
The retrieved SKU.
- Return type
- await fetch_store_listing(listing_id, /, *, localize=True)¶
This function is a coroutine.
Retrieves a store listing with the given ID.
New in version 2.0.
- Parameters
- Raises
NotFound – The listing does not exist.
Forbidden – You do not have access to the listing.
HTTPException – Retrieving the listing failed.
- Returns
The store listing.
- Return type
- await fetch_published_store_listing(sku_id, /, *, localize=True)¶
This function is a coroutine.
Retrieves a published store listing with the given SKU ID.
New in version 2.0.
- Parameters
- Raises
NotFound – The listing does not exist or is not public.
HTTPException – Retrieving the listing failed.
- Returns
The store listing.
- Return type
- await fetch_published_store_listings(application_id, /, localize=True)¶
This function is a coroutine.
Retrieves all published store listings for the given application ID.
New in version 2.0.
- Parameters
- Raises
HTTPException – Retrieving the listings failed.
- Returns
The store listings.
- Return type
List[
StoreListing]
- await fetch_primary_store_listing(application_id, /, *, localize=True)¶
This function is a coroutine.
Retrieves the primary store listing for the given application ID.
This is the public store listing of the primary SKU.
New in version 2.0.
- Parameters
- Raises
NotFound – The application does not exist or have a primary SKU.
HTTPException – Retrieving the store listing failed.
- Returns
The retrieved store listing.
- Return type
- await fetch_primary_store_listings(*application_ids, localize=True)¶
This function is a coroutine.
Retrieves the primary store listings for the given application IDs.
This is the public store listing of the primary SKU.
New in version 2.0.
- Parameters
- Raises
HTTPException – Retrieving the store listings failed.
- Returns
The retrieved store listings.
- Return type
List[
StoreListing]
This function is a coroutine.
Retrieves all premium subscription plans.
New in version 2.0.
- Raises
HTTPException – Retrieving the premium subscription plans failed.
- Returns
The premium subscription plans.
- Return type
List[
SubscriptionPlan]
- await fetch_sku_subscription_plans(sku_id, /, *, country_code=..., payment_source=..., with_unpublished=False)¶
This function is a coroutine.
Retrieves all subscription plans for the given SKU ID.
New in version 2.0.
- Parameters
sku_id (
int) – The ID of the SKU to retrieve the subscription plans for.country_code (
str) – The country code to retrieve the subscription plan prices for. Defaults to the country code of the current user.payment_source (
PaymentSource) – The specific payment source to retrieve the subscription plan prices for. Defaults to all payment sources of the current user.with_unpublished (
bool) –Whether to include unpublished subscription plans.
If
True, then you require access to the application.
- Raises
HTTPException – Retrieving the subscription plans failed.
- Returns
The subscription plans.
- Return type
List[
SubscriptionPlan]
- await fetch_skus_subscription_plans(*sku_ids, country_code=..., payment_source=..., with_unpublished=False)¶
This function is a coroutine.
Retrieves all subscription plans for the given SKU IDs.
New in version 2.0.
- Parameters
*sku_ids (
int) – A list of SKU IDs to retrieve the subscription plans for.country_code (
str) – The country code to retrieve the subscription plan prices for. Defaults to the country code of the current user.payment_source (
PaymentSource) – The specific payment source to retrieve the subscription plan prices for. Defaults to all payment sources of the current user.with_unpublished (
bool) –Whether to include unpublished subscription plans.
If
True, then you require access to the application(s).
- Raises
HTTPException – Retrieving the subscription plans failed.
- Returns
The subscription plans.
- Return type
List[
SubscriptionPlan]
- await fetch_eula(eula_id, /)¶
This function is a coroutine.
Retrieves a EULA with the given ID.
New in version 2.0.
- Parameters
eula_id (
int) – The ID of the EULA to retrieve.- Raises
NotFound – The EULA does not exist.
HTTPException – Retrieving the EULA failed.
- Returns
The retrieved EULA.
- Return type
- await fetch_live_build_ids(*branch_ids)¶
This function is a coroutine.
Retrieves the live build IDs for the given branch IDs.
New in version 2.0.
- Parameters
*branch_ids (
int) – A list of branch IDs to retrieve the live build IDs for.- Raises
HTTPException – Retrieving the live build IDs failed.
- Returns
A mapping of found branch IDs to their live build ID, if any.
- Return type
- await price_tiers()¶
This function is a coroutine.
Retrieves all price tiers.
New in version 2.0.
- Raises
HTTPException – Retrieving the price tiers failed.
- Returns
The price tiers.
- Return type
List[
int]
- await fetch_price_tier(price_tier, /)¶
This function is a coroutine.
Retrieves a mapping of currency to price for the given price tier.
New in version 2.0.
- Parameters
price_tier (
int) – The price tier to retrieve.- Raises
NotFound – The price tier does not exist.
HTTPException – Retrieving the price tier failed.
- Returns
The retrieved price tier mapping.
- Return type
This function is a coroutine.
Retrieves the usage of the premium perks on your account.
New in version 2.0.
- Raises
HTTPException – Retrieving the premium usage failed.
- Returns
The premium usage.
- Return type
- async for ... in recent_mentions(*, limit=25, before=..., guild=..., roles=True, everyone=True)¶
Returns an asynchronous iterator that enables receiving your recent mentions.
New in version 2.0.
Examples
Usage
counter = 0 async for message in client.recent_mentions(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in client.recent_mentions(limit=123)] # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every recent mention received in the past week. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. 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.guild (
Guild) – The guild to retrieve recent mentions from. If not provided, then the mentions are retrieved from all guilds.roles (
bool) – Whether to include role mentions.everyone (
bool) – Whether to include @everyone or @here mentions.
- Raises
HTTPException – The request to get recent message history failed.
- Yields
Message– The message with the message data parsed.
- await delete_recent_mention(message)¶
This function is a coroutine.
Acknowledges a message the current user has been mentioned in.
New in version 2.0.
- Parameters
message (
abc.Snowflake) – The message to delete.- Raises
HTTPException – Deleting the recent mention failed.
- await user_affinities()¶
This function is a coroutine.
Retrieves the user affinities for the current user.
User affinities are the users you interact with most frecently.
New in version 2.0.
- Raises
HTTPException – Retrieving the user affinities failed.
- Returns
The user affinities.
- Return type
List[
UserAffinity]
- await guild_affinities()¶
This function is a coroutine.
Retrieves the guild affinities for the current user.
Guild affinities are the guilds you interact with most frecently.
New in version 2.0.
- Raises
HTTPException – Retrieving the guild affinities failed.
- Returns
The guild affinities.
- Return type
List[
GuildAffinity]
- await join_active_developer_program(*, application, channel)¶
This function is a coroutine.
Joins the current user to the active developer program.
New in version 2.0.
- Parameters
application (
Application) – The application to join the active developer program with.channel (
TextChannel) – The channel to add the developer program webhook to.
- Raises
HTTPException – Joining the active developer program failed.
- Returns
The created webhook ID.
- Return type
- await leave_active_developer_program()¶
This function is a coroutine.
Leaves the current user from the active developer program. This does not remove the created webhook.
New in version 2.0.
- Raises
HTTPException – Leaving the active developer program failed.
CaptchaHandler¶
- asyncfetch_token
- asyncprefetch_token
- asyncstartup
- class discord.CaptchaHandler¶
A class that represents a captcha handler.
This class allows you to implement a protocol to solve captchas required by Discord. This is an abstract class. The library provides no concrete implementation.
These classes are passed to
Client.- await startup()¶
This function is a coroutine.
An abstract method that is called by the library at startup.
This is meant to provide an async startup method for the handler. This isn’t guaranteed to be run once.
The default implementation does nothing.
- await prefetch_token(proxy, proxy_auth, /)¶
This function is a coroutine.
An abstract method that is called a bit before a captcha token is required. Not guaranteed to be called.
It’s meant to signal the handler to begin preparing for the fetching of a token, if applicable. Keep in mind that Discord has multiple captcha sitekeys.
The default implementation does nothing.
- Parameters
proxy (Optional[
str]) – The current proxy of the client.proxy_auth (Optional[
aiohttp.BasicAuth]) – The proxy’s auth.
- await fetch_token(data, proxy, proxy_auth, /)¶
This function is a coroutine.
An abstract method that is called to fetch a captcha token.
If there is no token available, it should wait until one is generated before returning.
- Parameters
data (Dict[
str,Any]) – The raw error from Discord containing the captcha info.proxy (Optional[
str]) – The current proxy of the client.proxy_auth (Optional[
aiohttp.BasicAuth]) – The proxy’s auth.
- Returns
A captcha token.
- Return 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 defined with async def.
AutoMod¶
- discord.on_automod_rule_create(rule)¶
Called when a
AutoModRuleis created. You must havemanage_guildto receive this.New in version 2.0.
- Parameters
rule (
AutoModRule) – The rule that was created.
- discord.on_automod_rule_update(rule)¶
Called when a
AutoModRuleis updated. You must havemanage_guildto receive this.New in version 2.0.
- Parameters
rule (
AutoModRule) – The rule that was updated.
- discord.on_automod_rule_delete(rule)¶
Called when a
AutoModRuleis deleted. You must havemanage_guildto receive this.New in version 2.0.
- Parameters
rule (
AutoModRule) – The rule that was deleted.
- discord.on_automod_action(execution)¶
Called when a
AutoModActionis created/performed. You must havemanage_guildto receive this.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.- 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.
- 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.
- 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_delete(channel)¶
- discord.on_private_channel_create(channel)¶
Called whenever a private channel is deleted or created.
- Parameters
channel (
abc.PrivateChannel) – The private channel that got created or deleted.
- discord.on_private_channel_update(before, after)¶
Called whenever a private channel is updated. e.g. changed name or topic.
- Parameters
before (
abc.PrivateChannel) – The updated private channel’s old info.after (
abc.PrivateChannel) – The updated private 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_group_join(channel, user)¶
- discord.on_group_remove(channel, user)¶
Called when someone joins or leaves a
GroupChannel.- Parameters
channel (
GroupChannel) – The group that the user joined or left.user (
User) – The user that joined or left.
- discord.on_typing(channel, user, when)¶
Called when someone begins typing a message.
The
channelparameter can be aabc.Messageableinstance. Which could either beTextChannel,GroupChannel, orDMChannel.If the
channelis aTextChannelthen theuserparameter is aMember, otherwise it is aUser.- Parameters
channel (
abc.Messageable) – The location where the typing originated from.when (
datetime.datetime) – When the typing started as an aware datetime in UTC.
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.
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_errorwill 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_eventssetting 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_eventssetting in theClient.Note
This is only for the messages sent from the client WebSocket. The voice WebSocket will not trigger this event.
Gateway¶
- discord.on_ready()¶
Called when the client is done preparing the data received from Discord. Usually after login is successful and the
Client.guildsand 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.
Client¶
- discord.on_settings_update(before, after)¶
Called when your
UserSettingsupdates, for example:Changed theme
Changed custom activity
Changed locale
etc
New in version 2.0.
- Parameters
before (
UserSettings) – The settings prior to being updated.after (
UserSettings) – The settings after being updated.
- discord.on_guild_settings_update(before, after)¶
Called when a
GuildGuildSettingsupdates, for example:Muted guild or channel
Changed notification settings
etc
Note that you can get the guild from
GuildSettings.guild.New in version 2.0.
- Parameters
before (
GuildSettings) – The guild settings prior to being updated.after (
GuildSettings) – The guild settings after being updated.
- discord.on_required_action_update(action)¶
Called when Discord requires you to do something to continue using your account.
New in version 2.0.
- Parameters
action (Optional[
RequiredActionType]) – The action required. IfNone, then no further action is required.
Billing¶
- discord.on_payment_sources_update()¶
Called when your payment sources are updated.
New in version 2.0.
- discord.on_subscriptions_update()¶
Called when your subscriptions are updated.
New in version 2.0.
- discord.on_payment_client_add(purchase_token_hash, expires_at)¶
Called when a payment client is added to your account.
New in version 2.0.
- Parameters
purchase_token_hash (
str) – The purchase token hash.expires_at (
datetime.datetime) – When the payment client expires.
- discord.on_payment_update(payment)¶
Called when a payment is created or updated.
New in version 2.0.
- Parameters
payment (
Payment) – The payment that was updated.
Called when a premium guild subscription (boost) slot is added to your account.
New in version 2.0.
- Parameters
slot (
PremiumGuildSubscriptionSlot) – The slot that was added.
Called when a premium guild subscription (boost) slot is updated.
New in version 2.0.
- Parameters
slot (
PremiumGuildSubscriptionSlot) – The slot that was updated.
- discord.on_billing_popup_bridge_callback(payment_source_type, path, query, state)¶
Called when a billing popup bridge callback is received.
New in version 2.0.
- Parameters
payment_source_type (
PaymentSourceType) – The payment source type.path (
str) – The path of the callback.query (
str) – The query of the callback.state (
str) – The state of the callback.
Entitlements¶
- discord.on_library_application_update(application)¶
Called when a library entry is updated.
New in version 2.0.
- Parameters
application (
LibraryApplication) – The library entry that was updated.
- discord.on_achievement_update(achievement, percent_complete)¶
Called when an achievement is updated.
New in version 2.0.
- Parameters
achievement (
Achievement) – The achievement that was updated.percent_complete (
int) – The percentage of the acheivement completed.
- discord.on_entitlement_create(entitlement)¶
Called when an entitlement is added to your account.
New in version 2.0.
- Parameters
entitlement (
Entitlement) – The entitlement that was added.
- discord.on_entitlement_update(entitlement)¶
Called when an entitlement is updated.
New in version 2.0.
- Parameters
entitlement (
Entitlement) – The entitlement that was updated.
- discord.on_entitlement_delete(entitlement)¶
Called when an entitlement is removed from your account.
New in version 2.0.
- Parameters
entitlement (
Entitlement) – The entitlement that was removed.
Connections¶
- discord.on_connections_update()¶
Called when your account’s connections are updated. This may not be accompanied by an
on_connection_create()oron_connection_update()event.New in version 2.0.
- discord.on_connection_create(connection)¶
Called when a connection is added to your account.
New in version 2.0.
- Parameters
connection (
Connection) – The connection that was added.
- discord.on_connection_update(before, after)¶
Called when a connection is updated on your account.
Note
Due to a Discord limitation, this is also called when a connection is removed.
New in version 2.0.
- Parameters
before (
Connection) – The connection prior to being updated.after (
Connection) – The connection after being updated.
Relationships¶
- discord.on_relationship_add(relationship)¶
- discord.on_relationship_remove(relationship)¶
Called when a
Relationshipis added or removed from theClientUser.- Parameters
relationship (
Relationship) – The relationship that was added or removed.
- discord.on_relationship_update(before, after)¶
Called when a
Relationshipis updated, e.g. when you block a friend or a friendship is accepted.- Parameters
before (
Relationship) – The previous relationship.after (
Relationship) – The updated relationship.
Notes¶
Calls¶
- discord.on_call_create(call)¶
- discord.on_call_delete(call)¶
Called when a call is created in a
abc.PrivateChannel.- Parameters
call (Union[
PrivateCall,GroupCall]) – The call that was created or deleted.
- discord.on_call_update(before, after)¶
Called when a
PrivateCallorGroupCallis updated, e.g. when a member is added or another person is rung.- Parameters
before (
Relationship) – The previous call.after (
Relationship) – The updated call.
Guilds¶
- discord.on_guild_available(guild)¶
Called when a guild becomes available or unavailable. The guild must have existed in the
Client.guildscache.- Parameters
guild – The
Guildthat has changed availability.
- discord.on_guild_join(guild)¶
Called when a
Guildis either created by theClientor when theClientjoins a guild.- Parameters
guild (
Guild) – The guild that was joined.
- discord.on_guild_remove(guild)¶
Called when a
Guildis 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
Clientmust have been part of the guild to begin with. (i.e. it is part ofClient.guilds)- Parameters
guild (
Guild) – The guild that got removed.
- discord.on_guild_update(before, after)¶
Called when a
Guildupdates, for example:Changed name
Changed AFK channel
Changed AFK timeout
etc
- discord.on_guild_emojis_update(guild, before, after)¶
- discord.on_guild_stickers_update(guild, before, after)¶
Called when a
Guildupdates its stickers.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_application_command_counts_update(guild, before, after)¶
Called when a
Guild's application command counts are updated.New in version 2.0.
- Parameters
guild (
Guild) – The guild who got their application command counts updated.before (
ApplicationCommandCounts) – A namedtuple of application command counts before the update.after (
ApplicationCommandCounts) – A namedtuple of application command counts after the update.
- discord.on_audit_log_entry_create(entry)¶
Called when a
Guildgets a new audit log entry. You must haveview_audit_logto receive this.New in version 2.0.
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.targetattribute will usually be adiscord.Objectand theAuditLogEntry.userattribute will depend on user and member cache.To get the user ID of entry,
AuditLogEntry.user_idcan be used instead.- Parameters
entry (
AuditLogEntry) – The audit log entry that was created.
- discord.on_invite_create(invite)¶
Called when an
Inviteis created. You must havemanage_channelsto receive this.New in version 1.3.
Note
There is a rare possibility that the
Invite.guildandInvite.channelattributes will be ofObjectrather than the respective models.- Parameters
invite (
Invite) – The invite that was created.
- discord.on_invite_delete(invite)¶
Called when an
Inviteis deleted. You must havemanage_channelsto receive this.New in version 1.3.
Note
There is a rare possibility that the
Invite.guildandInvite.channelattributes will be ofObjectrather 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.- Parameters
invite (
Invite) – The invite that was deleted.
Integrations¶
- discord.on_integration_create(integration)¶
Called when an integration is created.
New in version 2.0.
- Parameters
integration (
Integration) – The integration that was created.
- discord.on_integration_update(integration)¶
Called when an integration is updated.
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.
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.
- Parameters
channel (
abc.GuildChannel) – The channel that had its webhooks updated.
- discord.on_raw_integration_delete(payload)¶
Called when an integration is deleted.
New in version 2.0.
- Parameters
payload (
RawIntegrationDeleteEvent) – The raw event payload data.
Interactions¶
- discord.on_interaction(interaction)¶
Called when an interaction happens.
This currently happens when an application command or component is used.
New in version 2.0.
- Parameters
interaction (
Interaction) – The interaction data.
- discord.on_interaction_finish(interaction)¶
Called when an interaction’s result is finalized.
New in version 2.0.
- Parameters
interaction (
Interaction) – The interaction data withInteraction.successfulfilled.
Members¶
- discord.on_member_join(member)¶
- discord.on_member_remove(member)¶
Called when a
Memberjoin or leaves aGuild.- Parameters
member (
Member) – The member who joined or left.
- discord.on_member_update(before, after)¶
Called when a
Memberupdates 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.
- discord.on_user_update(before, after)¶
Called when a
Userupdates their profile.This is called when one or more of the following things change:
avatar
username
discriminator
- discord.on_member_unban(guild, user)¶
- discord.on_presence_update(before, after)¶
Called when a
MemberorRelationshipupdates their presence.This is called when one or more of the following things change:
status
activity
New in version 2.0.
- Parameters
before (Union[
Member,Relationship]) – The updated member or friend’s old info.after (Union[
Member,Relationship]) – The updated member or friend’s updated info.
Messages¶
- discord.on_message(message)¶
Called when a
Messageis created and sent.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
Botdoes not have this problem.- Parameters
message (
Message) – The current message.
- discord.on_message_edit(before, after)¶
Called when a
Messagereceives 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_messagesparameter 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.
- 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_messagesparameter or use theon_raw_message_delete()event instead.- 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_messagesparameter or use theon_raw_bulk_message_delete()event instead.- 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_messagewill return aMessageobject 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.- 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- 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- Parameters
payload (
RawBulkMessageDeleteEvent) – The raw event payload data.
- discord.on_recent_mention_delete(message)¶
Called when a message you were mentioned in in the last week is acknowledged and deleted. If the message is not found in the internal message cache, then this event will not be called.
New in version 2.0.
- Parameters
message (
Message) – The message that was deleted.
- discord.on_raw_recent_mention_delete(message_id)¶
Called when a message you were mentioned in in the last week is acknowledged and deleted. Unlike
on_recent_mention_delete(), this is called regardless of the message being in the internal message cache or not.New in version 2.0.
- Parameters
message_id (
int) – The ID of the message that was deleted.
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
Messagebeing reacted, access it viaReaction.message.
- 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.Note
Consider using
on_raw_reaction_remove()if you need this and do not have a complete member cache.
- 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.
- 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.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.- 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.- 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.- 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.New in version 1.3.
- Parameters
payload (
RawReactionClearEmojiEvent) – The raw event payload data.
Roles¶
Scheduled Events¶
- discord.on_scheduled_event_create(event)¶
- discord.on_scheduled_event_delete(event)¶
Called when a
ScheduledEventis created or deleted.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
ScheduledEventis updated.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.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
StageInstanceis 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
StageInstanceis 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.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.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.
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.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.New in version 2.0.
- Parameters
thread (
Thread) – The thread that got deleted.
- 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.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
ThreadMemberleaves or joins aThread.You can get the thread a member belongs in by accessing
ThreadMember.thread.New in version 2.0.
- Parameters
member (
ThreadMember) – The member who joined or left.
- discord.on_raw_thread_member_remove(payload)¶
Called when a
ThreadMemberleaves aThread. Unlikeon_thread_member_remove()this is called regardless of the member being in the internal thread’s members cache or not.New in version 2.0.
- Parameters
payload – The raw event payload data.
Voice¶
- discord.on_voice_state_update(member, before, after)¶
Called when a
Memberchanges 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.
- 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
Memberwhose name is ‘Mighty’ and return it. If an entry is not found, thenNoneis 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
iterableparameter 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__yas the keyword argument.If nothing is found that matches the attributes passed, then
Noneis returned.Changed in version 2.0: The
iterableparameter is now positional-only.Changed in version 2.0: The
iterableparameter 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
Clientto set up logging iflog_handleris 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.0.
- 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
idparameter 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) - 1to be inclusive,high=Trueto be exclusive.When using as the higher end of a range, use
time_snowflake(dt, high=True) + 1to be inclusive,high=Falseto be exclusive.Changed in version 2.0: The
highparameter is now keyword-only and thedtparameter 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 a bot into guilds.
Changed in version 2.0:
permissions,guild,redirect_uri,scopesandstateparameters 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 * 5then 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
AllowedMentionsclass.
- 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
ResolvedInviteinstead 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.datetimefor 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-GBlocale.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.set_target(items, *, channel=..., message=..., user=...)¶
A helper function to set the target for a list of items.
This is used to set the target for a list of application commands.
Suppresses all AttributeErrors so you can pass multiple types of commands and not worry about which elements support which parameter.
- Parameters
items (Iterable[
abc.ApplicationCommand]) – A list of items to set the target for.channel (Optional[
abc.Messageable]) – The channel to target.message (Optional[
Message]) – The message to target.user (Optional[
Snowflake]) – The user to target.
- discord.utils.MISSING¶
A type safe sentinel used in the library to represent something as missing. Used to distinguish from
Nonevalues.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.
- 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.0.
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.0.
- stage_start¶
The system message sent when the stage starts.
New in version 2.0.
- stage_end¶
The system message sent when the stage ends.
New in version 2.0.
- stage_speaker¶
The system message sent when the stage speaker changes.
New in version 2.0.
- stage_raise_hand¶
The system message sent when a user is requesting to speak by raising their hands.
New in version 2.0.
- stage_topic¶
The system message sent when the stage topic changes.
New in version 2.0.
The system message sent when an application’s premium subscription is purchased for the guild.
New in version 2.0.
- class discord.InviteType¶
Specifies the type of
Invite.- guild¶
A guild invite.
- group_dm¶
A group DM invite.
- friend¶
A friend invite.
- 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.
- bug_hunter_level_1¶
The user is a Bug Hunter.
New in version 2.0.
- 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.
- partner_or_verification_application¶
The user has a partner or verification application.
- system¶
The user is a system user (i.e. represents Discord officially).
New in version 2.0.
- has_unread_urgent_messages¶
The user has an unread system message.
- bug_hunter_level_2¶
The user is a Bug Hunter Level 2.
- underage_deleted¶
The user has been flagged for deletion for being underage.
New in version 2.0.
- 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 Discord Certified Moderator.
- 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.
The user bought premium but has it manually disabled.
New in version 2.0.
- quarantined¶
The user is quarantined.
New in version 2.0.
- active_developer¶
The user is an active developer.
New in version 2.0.
- 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.HypeSquadHouse¶
Specifies the HypeSquad house a user belongs to.
- bravery¶
The “Bravery” house.
- brilliance¶
The “Brilliance” house.
- balance¶
The “Balance” house.
- 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
Guildhas 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.HighlightLevel¶
Specifies whether a
Guildhas highlights included in notifications.New in version 2.0.
- default¶
The highlight level is set to Discord default. This seems to always be enabled, which makes the purpose of this enum unclear.
- disabled¶
Members do not receive additional notifications for highlights.
- enabled¶
Members receive additional notifications for highlights.
- 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 beofflineinstead.
- 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
targetis theGuild.Possible attributes for
AuditLogDiff:
- channel_create¶
A new channel was created.
When this is the action, the type of
targetis either aabc.GuildChannelorObjectwith an ID.A more filled out object in the
Objectcase 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
targetis theabc.GuildChannelorObjectwith an ID.A more filled out object in the
Objectcase can be found by usingafterorbefore.Possible attributes for
AuditLogDiff:
- channel_delete¶
A channel was deleted.
When this is the action, the type of
targetis anObjectwith an ID.A more filled out object can be found by using the
beforeobject.Possible attributes for
AuditLogDiff:
- overwrite_create¶
A channel permission overwrite was created.
When this is the action, the type of
targetis theabc.GuildChannelorObjectwith an ID.When this is the action, the type of
extrais either aRoleorMember. If the object is not found then it is aObjectwith an ID being filled, a name, and atypeattribute 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_createfor more information on how thetargetandextrafields are set.Possible attributes for
AuditLogDiff:
- overwrite_delete¶
A channel permission overwrite was deleted.
See
overwrite_createfor more information on how thetargetandextrafields are set.Possible attributes for
AuditLogDiff:
- kick¶
A member was kicked.
When this is the action, the type of
targetis theUserorObjectwho got kicked.When this is the action,
changesis empty.
- member_prune¶
A member prune was triggered.
When this is the action, the type of
targetis set toNone.When this is the action, the type of
extrais 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,
changesis empty.
- ban¶
A member was banned.
When this is the action, the type of
targetis theUserorObjectwho got banned.When this is the action,
changesis empty.
- unban¶
A member was unbanned.
When this is the action, the type of
targetis theUserorObjectwho got unbanned.When this is the action,
changesis 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
targetis theMember,User, orObjectwho 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
targetis theMember,User, orObjectwho got the role.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
extrais set to an unspecified proxy object with two attributes:channel: ATextChannelorObjectwith 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
extrais 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
targetis theMember,User, orObjectwhich 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
targetis theRoleor aObjectwith 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
targetis theRoleor aObjectwith the ID.Possible attributes for
AuditLogDiff:
- role_delete¶
A role was deleted.
When this is the action, the type of
targetis theRoleor aObjectwith the ID.Possible attributes for
AuditLogDiff:
- invite_create¶
An invite was created.
When this is the action, the type of
targetis theInvitethat was created.Possible attributes for
AuditLogDiff:
- invite_update¶
An invite was updated.
When this is the action, the type of
targetis theInvitethat was updated.
- invite_delete¶
An invite was deleted.
When this is the action, the type of
targetis theInvitethat was deleted.Possible attributes for
AuditLogDiff:
- webhook_create¶
A webhook was created.
When this is the action, the type of
targetis theObjectwith 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
targetis theObjectwith the webhook ID.Possible attributes for
AuditLogDiff:
- webhook_delete¶
A webhook was deleted.
When this is the action, the type of
targetis theObjectwith the webhook ID.Possible attributes for
AuditLogDiff:
- emoji_create¶
An emoji was created.
When this is the action, the type of
targetis theEmojiorObjectwith 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
targetis theEmojiorObjectwith the emoji ID.Possible attributes for
AuditLogDiff:
- emoji_delete¶
An emoji was deleted.
When this is the action, the type of
targetis theObjectwith 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
targetis theMember,User, orObjectwho had their message deleted.When this is the action, the type of
extrais set to an unspecified proxy object with two attributes:count: An integer specifying how many messages were deleted.channel: ATextChannelorObjectwith 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
targetis theTextChannelorObjectwith the ID of the channel that was purged.When this is the action, the type of
extrais 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
targetis theMember,User, orObjectwho had their message pinned.When this is the action, the type of
extrais set to an unspecified proxy object with two attributes:channel: ATextChannelorObjectwith 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
targetis theMember,User, orObjectwho had their message unpinned.When this is the action, the type of
extrais set to an unspecified proxy object with two attributes:channel: ATextChannelorObjectwith 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
targetis theObjectwith 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
targetis theObjectwith 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
targetis theObjectwith 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
targetis theStageInstanceorObjectwith 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
targetis theStageInstanceorObjectwith 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
targetis theGuildStickerorObjectwith 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
targetis theGuildStickerorObjectwith 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
targetis theGuildStickerorObjectwith 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
targetis theScheduledEventorObjectwith the ID of the event which was created.Possible attributes for
AuditLogDiff: -name-channel-description-privacy_level-status-entity_type-cover_imageNew in version 2.0.
- scheduled_event_update¶
A scheduled event was created.
When this is the action, the type of
targetis theScheduledEventorObjectwith the ID of the event which was updated.Possible attributes for
AuditLogDiff: -name-channel-description-privacy_level-status-entity_type-cover_imageNew in version 2.0.
- scheduled_event_delete¶
A scheduled event was created.
When this is the action, the type of
targetis theScheduledEventorObjectwith the ID of the event which was deleted.Possible attributes for
AuditLogDiff: -name-channel-description-privacy_level-status-entity_type-cover_imageNew in version 2.0.
- thread_create¶
A thread was created.
When this is the action, the type of
targetis theThreadorObjectwith 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
targetis theThreadorObjectwith 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
targetis theThreadorObjectwith the ID of the thread which was deleted.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
targetis aAutoModRuleorObjectwith 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
targetis aAutoModRuleorObjectwith 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
targetis aAutoModRuleorObjectwith 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
targetis aMemberwith the ID of the person who triggered the automod rule.When this is the action, the type of
extrais set to an unspecified proxy object with 3 attributes:automod_rule_name: The name of the automod rule that was triggered.automod_rule_trigger: AAutoModRuleTriggerTyperepresentation of the rule type that was triggered.channel: The channel in which the automod rule was triggered.
When this is the action,
AuditLogEntry.changesis empty.New in version 2.0.
- automod_flag_message¶
An automod rule flagged a message.
When this is the action, the type of
targetis aMemberwith the ID of the person who triggered the automod rule.When this is the action, the type of
extrais set to an unspecified proxy object with 3 attributes:automod_rule_name: The name of the automod rule that was triggered.automod_rule_trigger: AAutoModRuleTriggerTyperepresentation of the rule type that was triggered.channel: The channel in which the automod rule was triggered.
When this is the action,
AuditLogEntry.changesis empty.New in version 2.0.
- automod_timeout_member¶
An automod rule timed-out a member.
When this is the action, the type of
targetis aMemberwith the ID of the person who triggered the automod rule.When this is the action, the type of
extrais set to an unspecified proxy object with 3 attributes:automod_rule_name: The name of the automod rule that was triggered.automod_rule_trigger: AAutoModRuleTriggerTyperepresentation of the rule type that was triggered.channel: The channel in which the automod rule was triggered.
When this is the action,
AuditLogEntry.changesis empty.New in version 2.0.
- class discord.AuditLogActionCategory¶
Represents the category that the
AuditLogActionbelongs 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.ApplicationType¶
Represents the type of an
Application.New in version 2.0.
- game¶
The application is a game.
- music¶
The application is music-related.
- ticketed_events¶
The application can use ticketed event.
- guild_role_subscriptions¶
The application can make custom guild role subscriptions.
- class discord.ApplicationMembershipState¶
Represents the membership state of a
TeamMemberorApplicationTester.New in version 1.3.
Changed in version 2.0: Renamed from
TeamMembershipState.New in version 2.0.
- x == y
Checks if two application states are equal.
- x != y
Checks if two application states are not equal.
- x > y
Checks if a application state is higher than another.
- x < y
Checks if a application state is lower than another.
- x >= y
Checks if a application state is higher or equal to another.
- x <= y
Checks if a application state is lower or equal to another.
- invited¶
Represents an invited user.
- accepted¶
Represents a user that has accepted the given invite.
- class discord.ApplicationVerificationState¶
Represents the verification application state of an
Application.New in version 2.0.
- x == y
Checks if two application states are equal.
- x != y
Checks if two application states are not equal.
- x > y
Checks if a application state is higher than another.
- x < y
Checks if a application state is lower than another.
- x >= y
Checks if a application state is higher or equal to another.
- x <= y
Checks if a application state is lower or equal to another.
- ineligible¶
The application is ineligible for verification.
- unsubmitted¶
The application is has not submitted a verification request.
- submitted¶
The application has submitted a verification request and is pending a response.
- succeeded¶
The application has been verified.
- class discord.StoreApplicationState¶
Represents the commerce application state of an
Application.New in version 2.0.
- x == y
Checks if two application states are equal.
- x != y
Checks if two application states are not equal.
- x > y
Checks if a application state is higher than another.
- x < y
Checks if a application state is lower than another.
- x >= y
Checks if a application state is higher or equal to another.
- x <= y
Checks if a application state is lower or equal to another.
- none¶
The application has not applied for commerce features.
- paid¶
The application has paid the commerce feature fee.
- submitted¶
The application has submitted a commerce application and is pending a response.
- approved¶
The application has been approved for commerce features.
- rejected¶
The application has not been approved for commerce features.
- blocked¶
The application has been blocked from using commerce features.
- class discord.RPCApplicationState¶
Represents the RPC application state of an
Application.New in version 2.0.
- x == y
Checks if two application states are equal.
- x != y
Checks if two application states are not equal.
- x > y
Checks if a application state is higher than another.
- x < y
Checks if a application state is lower than another.
- x >= y
Checks if a application state is higher or equal to another.
- x <= y
Checks if a application state is lower or equal to another.
- disabled¶
The application has not applied for RPC functionality and cannot use the feature.
- none¶
The application has not applied for RPC functionality and cannot use the feature.
- unsubmitted¶
The application has not submitted a RPC application.
- submitted¶
The application has submitted a RPC application and is pending a response.
- approved¶
The application has been approved for RPC funcionality.
- rejected¶
The application has not been approved for RPC funcionality.
- blocked¶
The application has been blocked from using commerce features.
- class discord.ApplicationDiscoverabilityState¶
Represents the discoverability state of an
Application.New in version 2.0.
- x == y
Checks if two application states are equal.
- x != y
Checks if two application states are not equal.
- x > y
Checks if a application state is higher than another.
- x < y
Checks if a application state is lower than another.
- x >= y
Checks if a application state is higher or equal to another.
- x <= y
Checks if a application state is lower or equal to another.
- ineligible¶
The application is ineligible for appearing on app discovery.
- not_discoverable¶
The application is not discoverable on app discovery.
- discoverable¶
The application is discoverable on app discovery.
- featureable¶
The application is featureable on app discovery.
- blocked¶
The application is blocked from appearing on app discovery.
- class discord.ApplicationBuildStatus¶
Represents the status of an
ApplicationBuild.New in version 2.0.
- created¶
The build has been created.
- uploading¶
The build is being uploaded.
- uploaded¶
The build has been uploaded.
- validating¶
The build is being validated.
- invalid¶
The build is invalid.
- corrupted¶
The build is corrupted.
- ready¶
The build is ready to be published.
- class discord.EmbeddedActivityPlatform¶
Represents an available platform for a
EmbeddedActivityConfig.New in version 2.0.
- web¶
The activity is available on web/desktop.
- ios¶
The activity is available on iOS.
- android¶
The activity is available on Android.
- class discord.EmbeddedActivityOrientation¶
Represents an orientation capability of a
EmbeddedActivityConfig.This is only used by mobile clients.
New in version 2.0.
- unlocked¶
The activity can be rotated.
- portrait¶
The activity is locked to portrait.
- landscape¶
The activity is locked to landscape.
- class discord.PayoutAccountStatus¶
Represents the status of a team payout account.
New in version 2.0.
- unsubmitted¶
The payout account application has not been submitted.
- pending¶
The payout account is pending.
- action_required¶
The payout account requires action.
- active¶
The payout account is active.
- blocked¶
The payout account is blocked.
- suspended¶
The payout account is suspended.
- class discord.PayoutStatus¶
Represents the status of a team payout.
New in version 2.0.
- open¶
The payout is open.
- paid¶
The payout has been paid out.
- pending¶
The payout is pending.
- manual¶
The payout has been manually made.
- cancelled¶
The payout has been cancelled.
- deferred¶
The payout has been deferred.
- deferred_internal¶
The payout has been deferred internally.
- processing¶
The payout is processing.
- error¶
The payout has an error.
- rejected¶
The payout has been rejected.
- risk_review¶
The payout is under risk review.
- submitted¶
The payout has been submitted.
- pending_funds¶
The payout is pending fund transfer.
- class discord.PayoutReportType¶
Represents the type of downloadable payout report.
New in version 2.0.
- by_sku¶
The payout report is by SKU.
- by_transaction¶
The payout report is by transaction.
- 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
Integrationshould 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.rolefrom 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 color blurple. See also
Colour.blurple
- grey¶
Represents the default avatar with the color grey. See also
Colour.greyple
- green¶
Represents the default avatar with the color green. See also
Colour.green
- orange¶
Represents the default avatar with the color orange. See also
Colour.orange
- red¶
Represents the default avatar with the color red. See also
Colour.red
- pink¶
Represents the default avatar with the color pink. This is not currently used in the client.
- 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.0.
- 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.
- role_subscriptions¶
A guild invite that redirects to the role subscriptions page of a guild when accepted.
New in version 2.0.
- creator_page¶
A guild invite that originates from the creator page of a guild.
New in version 2.0.
- 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.RelationshipType¶
Specifies the type of
Relationship.- friend¶
You are friends with this user.
- blocked¶
You have blocked this user.
- incoming_request¶
The user has sent you a friend request.
- outgoing_request¶
You have sent a friend request to this user.
- implicit¶
You frecently interact with this user. See
UserAffinityfor more information.New in version 2.0.
- class discord.UserContentFilter¶
Represents the options found in
Settings > Privacy & Safety > Safe Direct Messagingin the Discord client.- all_messages¶
Scan all direct messages from everyone.
- non_friends¶
Scan all direct messages that aren’t from friends.
- disabled¶
Don’t scan any direct messages.
- class discord.PremiumType¶
Represents the user’s Discord Nitro subscription type.
- nitro¶
Represents the new, full Discord Nitro.
- nitro_classic¶
Represents the classic Discord Nitro.
- nitro_basic¶
Represents the basic Discord Nitro.
New in version 2.0.
- class discord.PaymentSourceType¶
Represents the type of a payment source.
New in version 2.0.
- unknown¶
The payment source is unknown.
- credit_card¶
The payment source is a credit card.
- paypal¶
The payment source is a PayPal account.
- giropay¶
The payment source is a Giropay account.
- sofort¶
The payment source is a Sofort account.
- przelewy24¶
The payment source is a Przelewy24 account.
- sepa_debit¶
The payment source is a SEPA debit account.
- paysafecard¶
The payment source is a Paysafe card.
- gcash¶
The payment source is a GCash account.
- grabpay¶
The payment source is a GrabPay (Malaysia) account.
- momo_wallet¶
The payment source is a MoMo Wallet account.
- venmo¶
The payment source is a Venmo account.
- gopay_wallet¶
The payment source is a GoPay Wallet account.
- kakaopay¶
The payment source is a KakaoPay account.
- bancontact¶
The payment source is a Bancontact account.
- eps¶
The payment source is an EPS account.
- ideal¶
The payment source is an iDEAL account.
- class discord.PaymentGateway¶
Represents the payment gateway used for a payment source.
New in version 2.0.
- stripe¶
The payment source is a Stripe payment source.
- braintree¶
The payment source is a Braintree payment source.
- apple¶
The payment source is an Apple payment source.
- google¶
The payment source is a Google payment source.
- adyen¶
The payment source is an Adyen payment source.
- apple_pay¶
The payment source is an Apple Pay payment source (unconfirmed).
- class discord.SubscriptionType¶
Represents the type of a subscription.
New in version 2.0.
The subscription is a Discord premium (Nitro) subscription.
- guild¶
The subscription is a guild role subscription.
- application¶
The subscription is an application subscription.
- class discord.SubscriptionStatus¶
Represents the status of a subscription.
New in version 2.0.
- unpaid¶
The subscription is unpaid.
- active¶
The subscription is active.
- past_due¶
The subscription is past due.
- canceled¶
The subscription is canceled.
- ended¶
The subscription has ended.
- inactive¶
The subscription is inactive.
- account_hold¶
The subscription is on account hold.
- class discord.SubscriptionInvoiceStatus¶
Represents the status of a subscription invoice.
New in version 2.0.
- x == y
Checks if two subscription invoice statuses are equal.
- x != y
Checks if two subscription invoice statuses are not equal.
- x > y
Checks if a subscription invoice status is higher than another.
- x < y
Checks if a subscription invoice status is lower than another.
- x >= y
Checks if a subscription invoice status is higher or equal to another.
- x <= y
Checks if a subscription invoice status is lower or equal to another.
- open¶
The invoice is open.
- paid¶
The invoice is paid.
- void¶
The invoice is void.
- uncollectible¶
The invoice is uncollectible.
- class discord.SubscriptionDiscountType¶
Represents the type of a subscription discount.
New in version 2.0.
- subscription_plan¶
The discount is from an existing subscription plan’s remaining credit.
- entitlement¶
The discount is from an applied entitlement.
The discount is from a legacy premium plan promotion discount.
The discount is from a premium trial.
- class discord.SubscriptionInterval¶
Represents the interval of a subscription.
New in version 2.0.
- month¶
The subscription is billed monthly.
- year¶
The subscription is billed yearly.
- day¶
The subscription is billed daily.
- class discord.SubscriptionPlanPurchaseType¶
Represents the different types of subscription plan purchases.
New in version 2.0.
- default¶
The plan is purchased with default pricing.
- gift¶
The plan is purchased with gift pricing.
- sale¶
The plan is purchased with sale pricing.
- nitro_classic¶
The plan is purchased with Nitro Classic discounted pricing.
- nitro¶
The plan is purchased with Nitro discounted pricing.
- class discord.PaymentStatus¶
Represents the status of a payment.
New in version 2.0.
- pending¶
The payment is pending.
- completed¶
The payment has gone through.
- failed¶
The payment has failed.
- reversed¶
The payment has been reversed.
- refunded¶
The payment has been refunded.
- cancelled¶
The payment has been canceled.
- canceled¶
Alias for
PaymentStatus.cancelled.
- class discord.EntitlementType¶
Represents the type of an entitlement.
New in version 2.0.
- purchase¶
The entitlement is from a purchase.
The entitlement is a Discord premium subscription.
- developer_gift¶
The entitlement is gifted by the developer.
- test_mode_purchase¶
The entitlement is from a free test mode purchase.
- free_purchase¶
The entitlement is a free purchase.
- user_gift¶
The entitlement is gifted by a user.
The entitlement is a premium subscription perk.
- application_subscription¶
The entitlement is an application subscription.
- class discord.SKUType¶
Represents the type of a SKU.
New in version 2.0.
- durable_primary¶
Represents a primary SKU (game).
- durable¶
Represents a DLC.
- consumable¶
Represents a IAP (in-app purchase).
- bundle¶
Represents a bundle comprising the above.
- subscription¶
Represents a subscription-only SKU.
- group¶
Represents a group of SKUs.
- class discord.SKUAccessLevel¶
Represents the access level of a SKU.
New in version 2.0.
- full¶
The SKU is available to all users.
- early_access¶
The SKU is available in early access only.
- vip_access¶
The SKU is available to VIP users only.
- class discord.SKUFeature¶
Represents a feature of a SKU.
New in version 2.0.
- single_player¶
The SKU supports single player.
- online_multiplayer¶
The SKU supports online multiplayer.
- local_multiplayer¶
The SKU supports local multiplayer.
- pvp¶
The SKU supports PvP.
- local_coop¶
The SKU supports local co-op.
- cross_platform¶
The SKU supports cross-platform play.
- rich_presence¶
The SKU supports rich presence.
- discord_game_invites¶
The SKU supports Discord game invites.
- spectator_mode¶
The SKU supports spectator mode.
- controller_support¶
The SKU supports controller support.
- cloud_saves¶
The SKU supports cloud saves.
- online_coop¶
The SKU supports online co-op.
- secure_networking¶
The SKU supports secure networking.
- class discord.SKUGenre¶
Represents the genre of a SKU.
New in version 2.0.
- action¶
The SKU is an action game.
- action_adventure¶
The SKU is an action-adventure game.
- action_rpg¶
The SKU is an action RPG.
- adventure¶
The SKU is an adventure game.
- artillery¶
The SKU is an artillery game.
- baseball¶
The SKU is a baseball game.
- basketball¶
The SKU is a basketball game.
- billiards¶
The SKU is a billiards game.
- bowling¶
The SKU is a bowling game.
- boxing¶
The SKU is a boxing game.
- brawler¶
The SKU is a brawler.
- card_game¶
The SKU is a card game.
- driving_racing¶
The SKU is a driving/racing game.
- dual_joystick_shooter¶
The SKU is a dual joystick shooter.
- dungeon_crawler¶
The SKU is a dungeon crawler.
- education¶
The SKU is an education game.
- fighting¶
The SKU is a fighting game.
- fishing¶
The SKU is a fishing game.
- fitness¶
The SKU is a fitness game.
- flight_simulator¶
The SKU is a flight simulator.
- football¶
The SKU is a football game.
- four_x¶
The SKU is a 4X game.
- fps¶
The SKU is a first-person shooter.
- gambling¶
The SKU is a gambling game.
- golf¶
The SKU is a golf game.
- hack_and_slash¶
The SKU is a hack-and-slash game.
- hockey¶
The SKU is a hockey game.
- life_simulator¶
The SKU is a life simulator.
- light_gun¶
The SKU is a light gun game.
- massively_multiplayer¶
The SKU is a massively multiplayer game.
- music¶
The SKU is a music game.
- party¶
The SKU is a party game.
- pinball¶
The SKU is a pinball game.
- platformer¶
The SKU is a platformer.
- point_and_click¶
The SKU is a point-and-click game.
- puzzle¶
The SKU is a puzzle game.
- rpg¶
The SKU is an RPG.
- role_playing¶
The SKU is a role-playing game.
- rts¶
The SKU is a real-time strategy game.
- sandbox¶
The SKU is a sandbox game.
- shooter¶
The SKU is a shooter.
- shoot_em_up¶
The SKU is a shoot ‘em up game.
- simulation¶
The SKU is a simulation game.
- skateboarding_skating¶
The SKU is a skateboarding/skating game.
- snowboarding_skiing¶
The SKU is a snowboarding/skiing game.
- soccer¶
The SKU is a soccer game.
- sports¶
The SKU is a sports game.
- stealth¶
The SKU is a stealth game.
- strategy¶
The SKU is a strategy game.
- surfing_wakeboarding¶
The SKU is a surfing/wakeboarding game.
- survival¶
The SKU is a survival game.
- tennis¶
The SKU is a tennis game.
- third_person_shooter¶
The SKU is a third-person shooter.
- turn_based_strategy¶
The SKU is a turn-based strategy game.
- vehicular_combat¶
The SKU is a vehicular combat game.
- visual_novel¶
The SKU is a visual novel.
- wargame¶
The SKU is a wargame.
- wrestling¶
The SKU is a wrestling game.
- class discord.ContentRatingAgency¶
Represents the content rating agency of a SKU.
New in version 2.0.
- esrb¶
The ESRB.
- pegi¶
The PEGI system.
- class discord.ESRBRating¶
Represents the ESRB rating of a SKU.
New in version 2.0.
- everyone¶
The SKU is rated E for everyone.
- everyone_ten_plus¶
The SKU is rated E10+ for everyone ten and older.
- teen¶
The SKU is rated T for teen.
- mature¶
The SKU is rated M for mature.
- adults_only¶
The SKU is rated AO for adults only.
- rating_pending¶
The SKU is pending a rating.
- class discord.PEGIRating¶
Represents the PEGI rating of a SKU.
New in version 2.0.
- three¶
The SKU is rated 3.
- seven¶
The SKU is rated 7.
- twelve¶
The SKU is rated 12.
- sixteen¶
The SKU is rated 16.
- eighteen¶
The SKU is rated 18.
- class discord.ESRBContentDescriptor¶
Represents an ESRB rating content descriptor.
New in version 2.0.
- alcohol_reference¶
The SKU contains alcohol references.
- animated_blood¶
The SKU contains animated blood.
- blood¶
The SKU contains blood.
- blood_and_gore¶
The SKU contains blood and gore.
- cartoon_violence¶
The SKU contains cartoon violence.
- comic_mischief¶
The SKU contains comic mischief.
- crude_humor¶
The SKU contains crude humor.
- drug_reference¶
The SKU contains drug references.
- fantasy_violence¶
The SKU contains fantasy violence.
- intense_violence¶
The SKU contains intense violence.
- language¶
The SKU contains language.
- lyrics¶
The SKU contains lyrics.
- mature_humor¶
The SKU contains mature humor.
- nudity¶
The SKU contains nudity.
- partial_nudity¶
The SKU contains partial nudity.
- real_gambling¶
The SKU contains real gambling.
- sexual_content¶
The SKU contains sexual content.
- sexual_themes¶
The SKU contains sexual themes.
- sexual_violence¶
The SKU contains sexual violence.
- simulated_gambling¶
The SKU contains simulated gambling.
- strong_language¶
The SKU contains strong language.
- strong_lyrics¶
The SKU contains strong lyrics.
- strong_sexual_content¶
The SKU contains strong sexual content.
- suggestive_themes¶
The SKU contains suggestive themes.
- tobacco_reference¶
The SKU contains tobacco references.
- use_of_alcohol¶
The SKU contains use of alcohol.
- use_of_drugs¶
The SKU contains use of drugs.
- use_of_tobacco¶
The SKU contains use of tobacco.
- violence¶
The SKU contains violence.
- violent_references¶
The SKU contains violent references.
- in_game_purchases¶
The SKU provides in-game purchases.
- users_interact¶
The SKU allows users to interact.
The SKU shares your location.
- unrestricted_internet¶
The SKU has unrestricted internet access.
- mild_blood¶
The SKU contains mild blood.
- mild_cartoon_violence¶
The SKU contains mild cartoon violence.
- mild_fantasy_violence¶
The SKU contains mild fantasy violence.
- mild_language¶
The SKU contains mild language.
- mild_lyrics¶
The SKU contains mild inappropriate lyrics.
- mild_sexual_themes¶
The SKU contains mild sexual themes.
- mild_suggestive_themes¶
The SKU contains mild suggestive themes.
- mild_violence¶
The SKU contains mild violence.
- animated_violence¶
The SKU contains animated violence.
- class discord.PEGIContentDescriptor¶
Represents a PEGI rating content descriptor.
New in version 2.0.
- violence¶
The SKU contains violence.
- bad_language¶
The SKU contains bad language.
- fear¶
The SKU instills fear.
- gambling¶
The SKU contains gambling.
- sex¶
The SKU contains sexual themes.
- drugs¶
The SKU contains drug references.
- discrimination¶
The SKU contains discrimination.
- class discord.Distributor¶
Represents the distributor of a third-party SKU on Discord.
New in version 2.0.
- discord¶
The SKU is distributed by Discord.
- steam¶
The SKU is distributed by Steam.
- twitch¶
The SKU is distributed by Twitch.
- uplay¶
The SKU is distributed by Ubisoft Connect.
- battle_net¶
The SKU is distributed by Battle.net.
- origin¶
The SKU is distributed by Origin.
- gog¶
The SKU is distributed by GOG.
- epic_games¶
The SKU is distributed by Epic Games.
- google_play¶
The SKU is distributed by Google Play.
- class discord.OperatingSystem¶
Represents the operating system of a SKU’s system requirements.
New in version 2.0.
- windows¶
Represents Windows.
- mac¶
Represents macOS.
- linux¶
Represents Linux.
- class discord.StickerAnimationOptions¶
Represents the options found in
Settings > Accessibility > Stickersin the Discord client.- always¶
Always animate stickers.
- on_interaction¶
Animate stickers when they are interacted with.
- never¶
Never animate stickers.
- class discord.SpoilerRenderOptions¶
Represents the options found in
Settings > Text and Images > Show Spoiler Contentin the Discord client.New in version 2.0.
- always¶
Always render spoilers.
- on_click¶
Render spoilers when they are interacted with.
- if_moderator¶
Render spoilers if the user is a moderator.
- class discord.InboxTab¶
Represents the tabs found in the Discord inbox.
New in version 2.0.
- default¶
No inbox tab has been yet selected.
- mentions¶
The mentions tab.
- unreads¶
The unreads tab.
- todos¶
The todos tab.
- for_you¶
The for you tab.
- class discord.EmojiPickerSection¶
Represents the sections found in the Discord emoji picker. Any guild is also a valid section.
New in version 2.0.
- favorite¶
The favorite section.
- top_emojis¶
The top emojis section.
- recent¶
The recents section.
- people¶
The people emojis section.
- nature¶
The nature emojis section.
- food¶
The food emojis section.
- activity¶
The activity emojis section.
- travel¶
The travel emojis section.
- objects¶
The objects emojis section.
- symbols¶
The symbols emojis section.
- flags¶
The flags emojis section.
- class discord.StickerPickerSection¶
Represents the sections found in the Discord sticker picker. Any guild and sticker pack SKU is also a valid section.
New in version 2.0.
- favorite¶
The favorite section.
- recent¶
The recents section.
- class discord.Theme¶
Represents the theme synced across all Discord clients.
- light¶
Represents the Light theme on Discord.
- dark¶
Represents the Dark theme on Discord.
- class discord.Locale¶
Supported locales by Discord.
New in version 2.0.
- american_english¶
The
en-USlocale.
- british_english¶
The
en-GBlocale.
- bulgarian¶
The
bglocale.
- chinese¶
The
zh-CNlocale.
- taiwan_chinese¶
The
zh-TWlocale.
- croatian¶
The
hrlocale.
- czech¶
The
cslocale.
- indonesian¶
The
idlocale.New in version 2.0.
- danish¶
The
dalocale.
- dutch¶
The
nllocale.
- finnish¶
The
filocale.
- french¶
The
frlocale.
- german¶
The
delocale.
- greek¶
The
ellocale.
- hindi¶
The
hilocale.
- hungarian¶
The
hulocale.
- italian¶
The
itlocale.
- japanese¶
The
jalocale.
- korean¶
The
kolocale.
- lithuanian¶
The
ltlocale.
- norwegian¶
The
nolocale.
- polish¶
The
pllocale.
- brazil_portuguese¶
The
pt-BRlocale.
- romanian¶
The
rolocale.
- russian¶
The
rulocale.
- spain_spanish¶
The
es-ESlocale.
- swedish¶
The
sv-SElocale.
- thai¶
The
thlocale.
- turkish¶
The
trlocale.
- ukrainian¶
The
uklocale.
- vietnamese¶
The
vilocale.
- 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.RequiredActionType¶
Represents an action Discord requires the user to take.
New in version 2.0.
- update_agreements¶
The user must update their agreement of Discord’s terms of service and privacy policy. This does not limit the user from using Discord.
- complete_captcha¶
The user must complete a captcha.
- verify_email¶
The user must add and verify an email address to their account.
- reverify_email¶
The user must reverify their existing email address.
- verify_phone¶
The user must add a phone number to their account.
- reverify_phone¶
The user must reverify their existing phone number.
- reverify_email_or_verify_phone¶
The user must reverify their existing email address or add a phone number to their account.
- verify_email_or_reverify_phone¶
The user must add and verify an email address to their account or reverify their existing phone number.
- reverify_email_or_reverify_phone¶
The user must reverify their existing email address or reverify their existing phone number.
- class discord.ConnectionType¶
Represents the type of connection a user has with Discord.
New in version 2.0.
- battle_net¶
The user has a Battle.net connection.
- contacts¶
The user has a contact sync connection.
- crunchyroll¶
The user has a Crunchyroll connection.
- ebay¶
The user has an eBay connection.
- epic_games¶
The user has an Epic Games connection.
- facebook¶
The user has a Facebook connection.
- github¶
The user has a GitHub connection.
- league_of_legends¶
The user has a League of Legends connection.
- paypal¶
The user has a PayPal connection.
- playstation¶
The user has a PlayStation connection.
- reddit¶
The user has a Reddit connection.
- riot_games¶
The user has a Riot Games connection.
- samsung¶
The user has a Samsung Account connection.
- spotify¶
The user has a Spotify connection.
- skype¶
The user has a Skype connection.
- steam¶
The user has a Steam connection.
- tiktok¶
The user has a TikTok connection.
- twitch¶
The user has a Twitch connection.
- twitter¶
The user has a Twitter connection.
- youtube¶
The user has a YouTube connection.
- xbox¶
The user has an Xbox Live connection.
- class discord.ClientType¶
Represents a type of Discord client.
New in version 2.0.
- web¶
Represents the web client.
- mobile¶
Represents a mobile client.
- desktop¶
Represents a desktop client.
- unknown¶
Represents an unknown client.
- class discord.GiftStyle¶
Represents the special style of a gift.
New in version 2.0.
- snowglobe¶
The gift is a snowglobe.
- box¶
The gift is a box.
- class discord.InteractionType¶
Specifies the type of
Interaction.New in version 2.0.
- application_command¶
Represents a slash command interaction.
- component¶
Represents a component based interaction, i.e. clicking a button.
- autocomplete¶
Represents an autocomplete interaction.
- modal_submit¶
Represents submission of a modal interaction.
- class discord.ComponentType¶
Represents the component type of a component.
New in version 2.0.
- action_row¶
Represents the group component which holds different components in a row.
- button¶
Represents a button component.
- select¶
Represents a select component.
- text_input¶
Represents a text box component.
- class discord.ButtonStyle¶
Represents the style of the button component.
New in version 2.0.
- primary¶
Represents a blurple button for the primary action.
- secondary¶
Represents a grey button for the secondary action.
- success¶
Represents a green button for a successful action.
- danger¶
Represents a red button for a dangerous action.
- link¶
Represents a link button.
- class discord.TextStyle¶
Represents the style of the text box component.
New in version 2.0.
- short¶
Represents a short text box.
- paragraph¶
Represents a long form text box.
- class discord.AppCommandType¶
The type of application command.
New in version 2.0.
- chat_input¶
A slash command.
- user¶
A user context menu command.
- message¶
A message context menu command.
- class discord.AppCommandOptionType¶
The application command’s option type. This is usually the type of parameter an application command takes.
New in version 2.0.
- subcommand¶
A subcommand.
- subcommand_group¶
A subcommand group.
- string¶
A string parameter.
- integer¶
A integer parameter.
- boolean¶
A boolean parameter.
- user¶
A user parameter.
- channel¶
A channel parameter.
- role¶
A role parameter.
- mentionable¶
A mentionable parameter.
- number¶
A number parameter.
- attachment¶
An attachment parameter.
- 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.
- 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.
- 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.
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, automod_rules, 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. SeeAuditLogActionfor 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
AuditLogActionCategoryretrieved bycategory, the data retrieved by this attribute differs:
- after¶
The new value. The attribute has the type of
AuditLogDiff.Depending on the
AuditLogActionCategoryretrieved bycategory, the data retrieved by this attribute differs:
AuditLogDiff¶
- actions
- afk_channel
- afk_timeout
- allow
- archived
- auto_archive_duration
- available
- avatar
- banner
- bitrate
- channel
- code
- color
- colour
- cover_image
- deaf
- default_auto_archive_duration
- default_notifications
- 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
- 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.iconorRole.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
Objectwith 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
Objectwith 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
Objectwith 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
Objectwith 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
Objectwith 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
Roleorabc.GuildChannel.- Type
- type¶
The type of channel, sticker, webhook or integration.
- Type
Union[
ChannelType,StickerType,WebhookType,str]
- topic¶
The topic of a
TextChannelorStageChannel.See also
TextChannel.topicorStageChannel.topic.- Type
- bitrate¶
The bitrate of a
VoiceChannelorStageChannel.See also
VoiceChannel.bitrate,StageChannel.bitrate.- Type
- overwrites¶
A list of permission overwrite tuples that represents a target and a
PermissionOverwritefor said target.The first element is the object being targeted, which can either be a
MemberorUserorRole. If this object is not found then it is aObjectwith an ID being filled and atypeattribute 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
Objectwith 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
Objectwith 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
Noneindicates 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
- 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.
- 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_limitandStageChannel.user_limit- Type
- flags¶
The channel flags associated with this thread or forum post.
See also
ForumChannel.flagsandThread.flags- Type
Webhook Support¶
discord.py-self 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
Nonethen 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
typeisWebhookType.channel_follower.New in version 2.0.
- Type
Optional[
PartialWebhookGuild]
- source_channel¶
The channel that this webhook is following. Only given if
typeisWebhookType.channel_follower.New in version 2.0.
- Type
Optional[
PartialWebhookChannel]
- classmethod partial(id, token, *, session=..., client=..., user_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
sessionis not given while this is given then the client’s internal session will be used.New in version 2.0.
user_token (Optional[
str]) –The user authentication token for authenticated requests involving the webhook.
New in version 2.0.
- Raises
TypeError – Neither
sessionnorclientwere 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=..., user_token=None)¶
Creates a partial
Webhookfrom a webhook URL.Changed in version 2.0: This function will now raise
ValueErrorinstead 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
sessionis not given while this is given then the client’s internal session will be used.New in version 2.0.
user_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
sessionnorclientwere 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
ValueErrorinstead 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
Assetfor the avatar the webhook has.If the webhook does not have a traditional avatar,
Noneis 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,StageChannel,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, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., thread=..., thread_name=..., wait=False, suppress_embeds=False, silent=False)¶
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
fileparameter should be used with a singleFileobject.If the
embedparameter is provided, it must be of typeEmbedand it must be a rich embed type. You cannot mix theembedparameter with theembedsparameter, which must be alistofEmbedobjects to send.Changed in version 2.0: This function will now raise
ValueErrorinstead 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 fromNoneto aWebhookMessageif set toTrue. If the type of webhook isWebhookType.applicationthen 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.file (
File) – The file to upload. This cannot be mixed withfilesparameter.files (List[
File]) – A list of files to send with the content. This cannot be mixed with thefileparameter.embed (
Embed) – The rich embed for the content to send. This cannot be mixed withembedsparameter.embeds (List[
Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with theembedparameter.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message.
New in version 1.4.
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 thethreadparameter, 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.0.
- 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
embedandembedsorfileandfilesorthreadandthread_name.ValueError – The length of
embedswas invalid, or there was no token associated with this webhook.
- Returns
If
waitisTruethen the message that was sent, otherwiseNone.- Return type
Optional[
WebhookMessage]
- await fetch_message(id, /, *, thread=...)¶
This function is a coroutine.
Retrieves a single
WebhookMessageowned 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=..., 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
ValueErrorinstead ofInvalidArgument.- Parameters
message_id (
int) – The message ID to edit.content (Optional[
str]) – The content to edit the message with orNoneto clear it.embeds (List[
Embed]) – A list of embeds to edit the message with.embed (Optional[
Embed]) – The embed to edit the message with.Nonesuppresses the embeds. This should not be mixed with theembedsparameter.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.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
embedandembedsValueError – The length of
embedswas 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_idparameter is now positional-only.Changed in version 2.0: This function will now raise
ValueErrorinstead 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.
WebhookMessage¶
- asyncack
- asyncadd_files
- asyncadd_reaction
- asyncclear_reaction
- asyncclear_reactions
- asynccreate_thread
- asyncdelete
- asyncedit
- asyncfetch
- asyncgreet
- defis_system
- defmessage_commands
- asyncpin
- asyncpublish
- asyncremove_attachments
- asyncremove_reaction
- asyncreply
- defto_reference
- asyncunpin
- class discord.WebhookMessage¶
Represents a message sent from your webhook.
This allows you to edit or delete a message sent by your webhook.
This inherits from
discord.Messagewith changes toedit()anddelete()to work.New in version 1.6.
- await edit(content=..., embeds=..., embed=..., attachments=..., allowed_mentions=None)¶
This function is a coroutine.
Edits the message.
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
ValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content to edit the message with orNoneto clear it.embeds (List[
Embed]) – A list of embeds to edit the message with.embed (Optional[
Embed]) – The embed to edit the message with.Nonesuppresses the embeds. This should not be mixed with theembedsparameter.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.Note
New files will always appear after current attachments.
New in version 2.0.
allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. Seeabc.Messageable.send()for more information.
- Raises
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
TypeError – You specified both
embedandembedsValueError – The length of
embedswas invalid or there was no token associated with this webhook.
- Returns
The newly edited message.
- Return type
- await add_files(*files)¶
This function is a coroutine.
Adds new files to the end of the message attachments.
New in version 2.0.
- Parameters
*files (
File) – New files to add to the message.- Raises
HTTPException – Editing the message failed.
Forbidden – Tried to edit a message that isn’t yours.
- Returns
The newly edited message.
- Return type
- await remove_attachments(*attachments)¶
This function is a coroutine.
Removes attachments from the message.
New in version 2.0.
- Parameters
*attachments (
Attachment) – Attachments to remove from the message.- Raises
HTTPException – Editing the message failed.
Forbidden – Tried to edit a message that isn’t yours.
- Returns
The newly edited message.
- Return type
- await delete(*, delay=None)¶
This function is a coroutine.
Deletes the message.
- Parameters
delay (Optional[
float]) – If provided, the number of seconds to wait before deleting the message. The waiting is done in the background and deletion failures are ignored.- Raises
Forbidden – You do not have proper permissions to delete the message.
NotFound – The message was deleted already.
HTTPException – Deleting the message failed.
- await ack()¶
This function is a coroutine.
Marks this message as read.
- Raises
HTTPException – Acking failed.
- await add_reaction(emoji, /)¶
This function is a coroutine.
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild
Emoji.You must have
read_message_historyto do this. If nobody else has reacted to the message using this emoji,add_reactionsis required.Changed in version 2.0:
emojiparameter is now positional-only.Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
emoji (Union[
Emoji,Reaction,PartialEmoji,str]) – The emoji to react with.- Raises
HTTPException – Adding the reaction failed.
Forbidden – You do not have the proper permissions to react to the message.
NotFound – The emoji you specified was not found.
TypeError – The emoji parameter is invalid.
- clean_content¶
A property that returns the content in a “cleaned up” manner. This basically means that mentions are transformed into the way the client shows it. e.g.
<#id>will transform into#name.This will also transform @everyone and @here mentions into non-mentions.
Note
This does not affect markdown. If you want to escape or remove markdown then use
utils.escape_markdown()orutils.remove_markdown()respectively, along with this function.- Type
- await clear_reaction(emoji)¶
This function is a coroutine.
Clears a specific reaction from the message.
The emoji may be a unicode emoji or a custom guild
Emoji.You must have
manage_messagesto do this.New in version 1.3.
Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
emoji (Union[
Emoji,Reaction,PartialEmoji,str]) – The emoji to clear.- Raises
HTTPException – Clearing the reaction failed.
Forbidden – You do not have the proper permissions to clear the reaction.
NotFound – The emoji you specified was not found.
TypeError – The emoji parameter is invalid.
- await clear_reactions()¶
This function is a coroutine.
Removes all the reactions from the message.
You must have
manage_messagesto do this.- Raises
HTTPException – Removing the reactions failed.
Forbidden – You do not have the proper permissions to remove all the reactions.
- await create_thread(*, name, auto_archive_duration=..., slowmode_delay=None, reason=None)¶
This function is a coroutine.
Creates a public thread from this message.
You must have
create_public_threadsin order to create a public thread from a message.The channel this message belongs in must be a
TextChannel.New in version 2.0.
- Parameters
name (
str) – The name of the thread.auto_archive_duration (
int) –The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used.
Must be one of
60,1440,4320, or10080, if provided.slowmode_delay (Optional[
int]) – Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is21600. By default no slowmode rate limit if this isNone.reason (Optional[
str]) – The reason for creating a new thread. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to create a thread.
HTTPException – Creating the thread failed.
ValueError – This message does not have guild info attached.
- Returns
The created thread.
- Return type
- property created_at¶
The message’s creation time in UTC.
- Type
- property edited_at¶
An aware UTC datetime object containing the edited time of the message.
- Type
Optional[
datetime.datetime]
- await fetch()¶
This function is a coroutine.
Fetches the partial message to a full
Message.- Raises
NotFound – The message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- Returns
The full message.
- Return type
- await greet(sticker, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.greet()to reply to theMessagewith a sticker greeting.New in version 2.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
- Returns
The sticker greeting that was sent.
- Return type
- is_system()¶
bool: Whether the message is a system message.A system message is a message that is constructed entirely by the Discord API in response to something.
New in version 1.3.
- message_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the message commands available to use on the message.
Examples
Usage
async for command in message.message_commands(): print(command.name)
Flattening into a list
commands = [command async for command in message.message_commands()] # commands is now a list of MessageCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
MessageCommand– A message command.
- await pin(*, reason=None)¶
This function is a coroutine.
Pins the message.
You must have
manage_messagesto do this in a non-private channel context.- Parameters
reason (Optional[
str]) –The reason for pinning the message. Shows up on the audit log.
New in version 1.4.
- Raises
Forbidden – You do not have permissions to pin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Pinning the message failed, probably due to the channel having more than 50 pinned messages.
- await publish()¶
This function is a coroutine.
Publishes this message to the channel’s followers.
The message must have been sent in a news channel. You must have
send_messagesto do this.If the message is not your own then
manage_messagesis also needed.- Raises
Forbidden – You do not have the proper permissions to publish this message or the channel is not a news channel.
HTTPException – Publishing the message failed.
- raw_channel_mentions¶
A property that returns an array of channel IDs matched with the syntax of
<#channel_id>in the message content.- Type
List[
int]
- raw_mentions¶
A property that returns an array of user IDs matched with the syntax of
<@user_id>in the message content.This allows you to receive the user IDs of mentioned users even in a private message context.
- Type
List[
int]
- raw_role_mentions¶
A property that returns an array of role IDs matched with the syntax of
<@&role_id>in the message content.- Type
List[
int]
- await remove_reaction(emoji, member)¶
This function is a coroutine.
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild
Emoji.If the reaction is not your own (i.e.
memberparameter is not you) thenmanage_messagesis needed.The
memberparameter must represent a member and meet theabc.Snowflakeabc.Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
emoji (Union[
Emoji,Reaction,PartialEmoji,str]) – The emoji to remove.member (
abc.Snowflake) – The member for which to remove the reaction.
- Raises
HTTPException – Removing the reaction failed.
Forbidden – You do not have the proper permissions to remove the reaction.
NotFound – The member or emoji you specified was not found.
TypeError – The emoji parameter is invalid.
- await reply(content=None, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.send()to reply to theMessage.New in version 1.6.
Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate sizeTypeError – You specified both
fileandfiles.
- Returns
The message that was sent.
- Return type
- system_content¶
A property that returns the content that is rendered regardless of the
Message.type.In the case of
MessageType.defaultandMessageType.reply, this just returns the regularMessage.content. Otherwise this returns an English message denoting the contents of the system message.- Type
- to_reference(*, fail_if_not_exists=True)¶
Creates a
MessageReferencefrom the current message.New in version 1.6.
- Parameters
fail_if_not_exists (
bool) –Whether replying using the message reference should raise
HTTPExceptionif the message no longer exists or Discord could not fetch the message.New in version 1.7.
- Returns
The reference to this message.
- Return type
- await unpin(*, reason=None)¶
This function is a coroutine.
Unpins the message.
You must have
manage_messagesto do this in a non-private channel context.- Parameters
reason (Optional[
str]) –The reason for unpinning the message. Shows up on the audit log.
New in version 1.4.
- Raises
Forbidden – You do not have permissions to unpin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Unpinning the message failed.
SyncWebhook¶
- clsSyncWebhook.from_url
- clsSyncWebhook.partial
- defdelete
- defdelete_message
- defedit
- defedit_message
- deffetch
- deffetch_message
- defis_authenticated
- defis_partial
- defsend
- class discord.SyncWebhook¶
Represents a synchronous Discord webhook.
For an asynchronous counterpart, see
Webhook.- 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
Nonethen 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
typeisWebhookType.channel_follower.New in version 2.0.
- Type
Optional[
PartialWebhookGuild]
- source_channel¶
The channel that this webhook is following. Only given if
typeisWebhookType.channel_follower.New in version 2.0.
- Type
Optional[
PartialWebhookChannel]
- classmethod partial(id, token, *, session=..., user_token=None)¶
Creates a partial
Webhook.- Parameters
id (
int) – The ID of the webhook.token (
str) – The authentication token of the webhook.session (
requests.Session) – The session to use to send requests with. Note that the library does not manage the session and will not close it. If not given, therequestsauto session creation functions are used instead.user_token (Optional[
str]) – The bot authentication token for authenticated requests involving the webhook.
- Returns
A partial
SyncWebhook. A partialSyncWebhookis just aSyncWebhookobject with an ID and a token.- Return type
- classmethod from_url(url, *, session=..., user_token=None)¶
Creates a partial
Webhookfrom a webhook URL.- Parameters
url (
str) – The URL of the webhook.session (
requests.Session) – The session to use to send requests with. Note that the library does not manage the session and will not close it. If not given, therequestsauto session creation functions are used instead.user_token (Optional[
str]) – The bot authentication token for authenticated requests involving the webhook.
- Raises
ValueError – The URL is invalid.
- Returns
A partial
SyncWebhook. A partialSyncWebhookis just aSyncWebhookobject with an ID and a token.- Return type
- fetch(*, prefer_auth=True)¶
Fetches the current webhook.
This could be used to get a full webhook from a partial webhook.
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
- delete(*, reason=None, prefer_auth=True)¶
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.
- edit(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)¶
Edits this Webhook.
- 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.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 toTrue.
- 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.
- Returns
The newly edited webhook.
- Return type
- send(content=..., *, username=..., avatar_url=..., tts=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., thread=..., thread_name=..., wait=False, suppress_embeds=False, silent=False)¶
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
fileparameter should be used with a singleFileobject.If the
embedparameter is provided, it must be of typeEmbedand it must be a rich embed type. You cannot mix theembedparameter with theembedsparameter, which must be alistofEmbedobjects to send.- 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 fromNoneto aWebhookMessageif 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.file (
File) – The file to upload. This cannot be mixed withfilesparameter.files (List[
File]) – A list of files to send with the content. This cannot be mixed with thefileparameter.embed (
Embed) – The rich embed for the content to send. This cannot be mixed withembedsparameter.embeds (List[
Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with theembedparameter.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message.
New in version 1.4.
thread (
Snowflake) –The thread to send this message 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 thethreadparameter, 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.0.
- 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
embedandembedsorfileandfilesorthreadandthread_name.ValueError – The length of
embedswas invalid or there was no token associated with this webhook.
- Returns
If
waitisTruethen the message that was sent, otherwiseNone.- Return type
Optional[
SyncWebhookMessage]
- fetch_message(id, /, *, thread=...)¶
Retrieves a single
SyncWebhookMessageowned 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
- property avatar¶
Returns an
Assetfor the avatar the webhook has.If the webhook does not have a traditional avatar,
Noneis 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,StageChannel,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
- edit_message(message_id, *, content=..., embeds=..., embed=..., attachments=..., allowed_mentions=None, thread=...)¶
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.
- Parameters
message_id (
int) – The message ID to edit.content (Optional[
str]) – The content to edit the message with orNoneto clear it.embeds (List[
Embed]) – A list of embeds to edit the message with.embed (Optional[
Embed]) – The embed to edit the message with.Nonesuppresses the embeds. This should not be mixed with theembedsparameter.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.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
embedandembedsValueError – The length of
embedswas invalid or there was no token associated with this webhook.
- 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.
- delete_message(message_id, /, *, thread=...)¶
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.
- 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.
SyncWebhookMessage¶
- defadd_files
- defdelete
- defedit
- defremove_attachments
- class discord.SyncWebhookMessage¶
Represents a message sent from your webhook.
This allows you to edit or delete a message sent by your webhook.
This inherits from
discord.Messagewith changes toedit()anddelete()to work.New in version 2.0.
- edit(content=..., embeds=..., embed=..., attachments=..., allowed_mentions=None)¶
Edits the message.
Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content to edit the message with orNoneto clear it.embeds (List[
Embed]) – A list of embeds to edit the message with.embed (Optional[
Embed]) – The embed to edit the message with.Nonesuppresses the embeds. This should not be mixed with theembedsparameter.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.Note
New files will always appear after current attachments.
New in version 2.0.
allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. Seeabc.Messageable.send()for more information.
- Raises
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
TypeError – You specified both
embedandembedsValueError – The length of
embedswas invalid or there was no token associated with this webhook.
- Returns
The newly edited message.
- Return type
- add_files(*files)¶
Adds new files to the end of the message attachments.
New in version 2.0.
- Parameters
*files (
File) – New files to add to the message.- Raises
HTTPException – Editing the message failed.
Forbidden – Tried to edit a message that isn’t yours.
- Returns
The newly edited message.
- Return type
- remove_attachments(*attachments)¶
Removes attachments from the message.
New in version 2.0.
- Parameters
*attachments (
Attachment) – Attachments to remove from the message.- Raises
HTTPException – Editing the message failed.
Forbidden – Tried to edit a message that isn’t yours.
- Returns
The newly edited message.
- Return type
- delete(*, delay=None)¶
Deletes the message.
- Parameters
delay (Optional[
float]) – If provided, the number of seconds to wait before deleting the message. This blocks the thread.- Raises
Forbidden – You do not have proper permissions to delete the message.
NotFound – The message was deleted already.
HTTPException – Deleting the message failed.
PartialWebhookGuild¶
- class discord.PartialWebhookGuild¶
Represents a partial guild for webhooks.
These are typically given for channel follower webhooks.
New in version 2.0.
PartialWebhookChannel¶
Abstract Base Classes¶
An abstract base class (also known as an abc) is a class that models can inherit
to get their behaviour. Abstract base classes should not be instantiated.
They are mainly there for usage with isinstance() and issubclass().
This library has a module related to abstract base classes, in which all the ABCs are subclasses of
typing.Protocol.
Snowflake¶
- class discord.abc.Snowflake¶
An ABC that details the common operations on a Discord model.
Almost all Discord models meet this abstract base class.
If you want to create a snowflake on your own, consider using
Object.
User¶
- defmentioned_in
- class discord.abc.User¶
An ABC that details the common operations on a Discord user.
The following implement this ABC:
This ABC must also implement
Snowflake.- property avatar¶
Returns an Asset that represents the user’s avatar, if present.
- Type
Optional[
Asset]
- property avatar_decoration¶
Returns an Asset that represents the user’s avatar decoration, if present.
New in version 2.0.
- Type
Optional[
Asset]
- property default_avatar¶
Returns the default avatar for a given user. This is calculated by the user’s discriminator.
- 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
PrivateChannel¶
GuildChannel¶
- asyncclone
- asynccreate_invite
- asyncdelete
- asyncinvites
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncset_permissions
- class discord.abc.GuildChannel¶
An ABC that details the common operations on a Discord guild channel.
The following implement this ABC:
This ABC must also implement
Snowflake.- position¶
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type
- property notification_settings¶
Returns the notification settings for this channel.
If not found, an instance is created with defaults applied. This follows Discord behaviour.
New in version 2.0.
- Type
- property changed_roles¶
Returns a list of roles that have been overridden from their default values in the
rolesattribute.- Type
List[
Role]
- property created_at¶
Returns the channel’s creation time in UTC.
- Type
- property jump_url¶
Returns a URL that allows the client to jump to the channel.
New in version 2.0.
- Type
- overwrites_for(obj)¶
Returns the channel-specific overwrites for a member or a role.
- property overwrites¶
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Roleor aMemberand the value is the overwrite as aPermissionOverwrite.Changed in version 2.0: Overwrites can now be type-aware
Objectin case of cache lookup failure- Returns
The channel’s permission overwrites.
- Return type
Dict[Union[
Role,Member,Object],PermissionOverwrite]
- property category¶
The category this channel belongs to.
If there is no category then this is
None.- Type
Optional[
CategoryChannel]
- property permissions_synced¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.New in version 1.3.
- Type
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Implicit permissions
Member timeout
If a
Roleis passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The permissions of the role used as a parameter
The default role permission overwrites
The permission overwrites of the role used as a parameter
Changed in version 2.0: The object passed in can now be a role object.
Changed in version 2.0:
objparameter is now positional-only.
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the channel.
You must have
manage_channelsto do this.- Parameters
reason (Optional[
str]) – The reason for deleting this channel. Shows up on the audit log.- Raises
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)¶
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
targetparameter should either be aMemberor aRolethat belongs to guild.The
overwriteparameter, if given, must either beNoneorPermissionOverwrite. For convenience, you can pass in keyword arguments denotingPermissionsattributes. If this is done, then you cannot mix the keyword arguments with theoverwriteparameter.If the
overwriteparameter isNone, then the permission overwrites are deleted.You must have
manage_rolesto do this.Note
This method replaces the old overwrites with the ones given.
Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwriteoverwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
target (Union[
Member,Role]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
TypeError – The
overwriteparameter was invalid or the target type was notRoleorMember.ValueError – The
overwriteparameter andpositionsparameters were both unset.
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have
manage_channelsto do this.New in version 1.1.
- Parameters
- Raises
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns
The channel that was created.
- Return type
- await move(**kwargs)¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have
manage_channelsto do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
beginning (
bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend,before, andafter.end (
bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning,before, andafter.before (
Snowflake) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (
Snowflake) – The channel that should be after our current channel. This is mutually exclusive withbeginning,end, andbefore.offset (
int) – The number of channels to offset the move by. For example, an offset of2withbeginning=Truewould move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning,end,before, andafterparameters.category (Optional[
Snowflake]) – The category to move this channel under. IfNoneis given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool) – Whether to sync the permissions with the category (if given).reason (
str) – The reason for the move.
- Raises
ValueError – An invalid position was given.
TypeError – A bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, validate, target_type=None, target_user=None, target_application=None)¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have
create_instant_inviteto do this.- Parameters
max_age (
int) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse.unique (
bool) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalsethen it will return a previously created invite.validate (Union[
Invite,str]) –The existing channel invite to validate and return for reuse. If this invite is invalid, a new invite will be created according to the parameters and returned.
New in version 2.0.
target_type (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
New in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.New in version 2.0.
target_application: –
Optional[
Application]: The embedded application for the invite, required iftarget_typeisInviteTarget.embedded_application.New in version 2.0.
reason (Optional[
str]) – The reason for creating this invite. Shows up on the audit log.
- Raises
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns
The invite that was created.
- Return type
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channelsto get this information.- Raises
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns
The list of invites that are currently active.
- Return type
List[
Invite]
Messageable¶
- asyncack
- asyncack_pins
- asyncfetch_message
- asyncgreet
- async forhistory
- asyncpins
- asyncsend
- defslash_commands
- deftyping
- defuser_commands
- class discord.abc.Messageable¶
An ABC that details the common operations on a model that can send messages.
The following implement this ABC:
- async with typing()¶
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using
await.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!')
Example Usage:
await channel.typing() # Do some computational magic for about 10 seconds await channel.send('Done!')
Changed in version 2.0: This no longer works with the
withsyntax,async withmust be used instead.Changed in version 2.0: Added functionality to
awaitthe context manager to send a typing indicator for 10 seconds.
- async for ... in slash_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the slash commands available in the channel.
Examples
Usage
async for command in channel.slash_commands(): print(command.name)
Flattening into a list
commands = [command async for command in channel.slash_commands()] # commands is now a list of SlashCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
SlashCommand– A slash command.
- async for ... in user_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the user commands available to use on the user.
Examples
Usage
async for command in user.user_commands(): print(command.name)
Flattening into a list
commands = [command async for command in user.user_commands()] # commands is now a list of UserCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
UserCommand– A user command.
- await send(content=None, *, tts=False, file=None, files=None, stickers=None, delete_after=None, nonce=..., allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, silent=False)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then a sticker or file must be sent.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (
int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. Generates one by default.delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.New in version 1.6.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
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.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate size.TypeError – You specified both
fileandfiles, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The message that was sent.
- Return type
- await greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...)¶
This function is a coroutine.
Sends a sticker greeting to the destination.
A sticker greeting is used to begin a new DM or reply to a system message.
New in version 2.0.
- Parameters
sticker (Union[
GuildSticker,StickerItem]) – The sticker to greet with.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead. In the case of greeting, onlyreplied_useris considered.reference (Union[
Message,MessageReference,PartialMessage]) – A reference to theMessageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.mention_author (
bool) – If set, overrides thereplied_userattribute ofallowed_mentions.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
TypeError – The
referenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The sticker greeting that was sent.
- Return type
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters
id (
int) – The message ID to look for.- 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.
- Returns
The message asked for.
- Return type
- await ack()¶
This function is a coroutine.
Marks every message in this channel as read.
- Raises
HTTPException – Acking the channel failed.
- await ack_pins()¶
This function is a coroutine.
Marks a channel’s pins as viewed.
- Raises
HTTPException – Acking the pinned messages failed.
- await pins()¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises
Forbidden – You do not have the permission to retrieve pinned messages.
HTTPException – Retrieving the pinned messages failed.
- Returns
The messages that are currently pinned.
- Return type
List[
Message]
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an asynchronous iterator that enables receiving the destination’s message history.
You must have
read_message_historyto do this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in channel.history(limit=123)] # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. 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 messages after this date or message. 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.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields
Message– The message with the message data parsed.
Connectable¶
- asyncconnect
- class discord.abc.Connectable¶
An ABC that details the common operations on a channel that can connect to a voice server.
The following implement this ABC:
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, _channel=None, self_deaf=False, self_mute=False)¶
This function is a coroutine.
Connects to voice and creates a
VoiceClientto establish your connection to the voice server.- Parameters
timeout (
float) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (Type[
VoiceProtocol]) – A type that subclassesVoiceProtocolto connect with. Defaults toVoiceClient.self_mute (
bool) –Indicates if the client should be self-muted.
New in version 2.0.
self_deaf (
bool) –Indicates if the client should be self-deafened.
New in version 2.0.
- Raises
asyncio.TimeoutError – Could not connect to the voice channel in time.
ClientException – You are already connected to a voice channel.
OpusNotLoaded – The opus library has not been loaded.
- Returns
A voice client that is fully connected to the voice server.
- Return type
ApplicationCommand¶
- defis_group
- class discord.abc.ApplicationCommand¶
An ABC that represents a usable application command.
The following implement this ABC:
New in version 2.0.
- type¶
The type of application command.
- Type
- application¶
The application this command belongs to. Only available if requested.
- Type
Optional[
IntegrationApplication]
- guild_id¶
The ID of the guild this command is registered in. A value of
Nonedenotes that it is a global command.- Type
Optional[
int]
- is_group()¶
Query whether this command is a group.
- Returns
Whether this command is a group.
- Return type
- property target_channel¶
The channel this application command will be used on.
You can set this in order to use this command in a different channel without re-fetching it.
- Type
Optional[
abc.Messageable]
- property default_member_permissions¶
The default permissions required to use this command.
Note
This may be overrided on a guild-by-guild basis.
- Type
Optional[
Permissions]
Discord Models¶
Models are classes that are received from Discord and are not meant to be created by the user of the library.
Danger
The classes listed below are not intended to be created by users and are also read-only.
For example, this means that you should not make your own User instances
nor should you modify the User instance yourself.
If you want to get one of these model classes instances they’d have to be through
the cache, and a common way of doing so is through the utils.find() function
or attributes of model classes that you receive from the events specified in the
Event Reference.
Note
Nearly all classes here have __slots__ defined which means that it is impossible to have dynamic attributes to the data classes.
User¶
- accent_color
- accent_colour
- avatar
- avatar_decoration
- banner
- bio
- bot
- color
- colour
- created_at
- default_avatar
- desktop
- discriminator
- display_avatar
- display_banner
- display_name
- flags
- id
- locale
- mention
- mfa_enabled
- mobile
- name
- note
- nsfw_allowed
- phone
- premium
- premium_type
- premium_usage_flags
- public_flags
- purchased_flags
- system
- verified
- voice
- asyncedit
- defmentioned_in
- class discord.ClientUser¶
Represents your Discord user.
- x == y
Checks if two users are equal.
- x != y
Checks if two users are not equal.
- hash(x)
Return the user’s hash.
- str(x)
Returns the user’s name with discriminator.
- system¶
Specifies if the user is a system user (i.e. represents Discord officially).
New in version 1.3.
- Type
Specifies the type of premium a user has (i.e. Nitro, Nitro Classic, or Nitro Basic). Could be None if the user is not premium.
- Type
Optional[
PremiumType]
- nsfw_allowed¶
Specifies if the user should be allowed to access NSFW content. If
None, then the user’s date of birth is not known.New in version 2.0.
- Type
Optional[
bool]
Indicates if the user is a premium user (i.e. has Discord Nitro).
- property flags¶
Returns the user’s flags (including private).
New in version 2.0.
- Type
Returns the user’s premium usage flags.
New in version 2.0.
- Type
- property purchased_flags¶
Returns the user’s purchased flags.
New in version 2.0.
- Type
- await edit(*, username=..., avatar=..., avatar_decoration=..., password=..., new_password=..., email=..., house=..., discriminator=..., banner=..., accent_colour=..., accent_color=..., bio=..., date_of_birth=...)¶
This function is a coroutine.
Edits the current profile of the client.
Note
To upload an avatar, a bytes-like object must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via
open('some_filename', 'rb')and the bytes-like object is given through the use offp.read().Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned.
Changed in version 2.0: This function will now raise
ValueErrorinstead ofInvalidArgument.- Parameters
password (
str) – The current password for the client’s account. Required for everything except avatar, banner, accent_colour, date_of_birth, and bio.new_password (
str) – The new password you wish to change to.email (
str) – The new email you wish to change to.house (Optional[
HypeSquadHouse]) – The hypesquad house you wish to change to. Could beNoneto leave the current house.username (
str) – The new username you wish to change to.discriminator (
int) – The new discriminator you wish to change to. Can only be used if you have Nitro.avatar (Optional[
bytes]) – A bytes-like object representing the image to upload. Could beNoneto denote no avatar.avatar_decoration (Optional[
bytes]) –A bytes-like object representing the image to upload. Could be
Noneto denote no avatar decoration.New in version 2.0.
banner (
bytes) – A bytes-like object representing the image to upload. Could beNoneto denote no banner.accent_colour (
Colour) –A
Colourobject of the colour you want to set your profile to.New in version 2.0.
bio (
str) –Your “about me” section. Could be
Noneto represent no bio.New in version 2.0.
date_of_birth (
datetime.datetime) –Your date of birth. Can only ever be set once.
New in version 2.0.
- Raises
HTTPException – Editing your profile failed.
ValueError – Password was not passed when it was required. house field was not a
HypeSquadHouse. date_of_birth field was not adatetime.datetime. accent_colo(u)r parameter was not aColour.
- Returns
The newly edited client user.
- Return 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
Assetfor the avatar the user has.If the user has not uploaded a global avatar,
Noneis returned. If you want the avatar that a user has displayed, considerdisplay_avatar.- Type
Optional[
Asset]
- property avatar_decoration¶
Returns an
Assetfor the avatar decoration the user has.If the user does not have a avatar decoration,
Noneis returned.New in version 2.0.
- Type
Optional[
Asset]
- 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 default_avatar¶
Returns the default avatar for a given user. This is calculated by the user’s discriminator.
- 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_banner¶
Returns the user’s banner asset, if available.
This is the same as
bannerand is here for compatibility.New in version 2.0.
- Type
Optional[
Asset]
- property display_name¶
Returns the user’s display name.
For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
- Type
- mentioned_in(message)¶
Checks if the user is mentioned in the specified message.
- property public_flags¶
The publicly available flags the user has.
- Type
- property voice¶
Returns the user’s current voice state.
- Type
Optional[
VoiceState]
- asyncack
- asyncack_pins
- asyncblock
- asyncconnect
- asynccreate_dm
- asyncfetch_message
- asyncgreet
- async forhistory
- defis_blocked
- defis_friend
- defmentioned_in
- asyncpins
- asyncprofile
- asyncremove_friend
- asyncsend
- asyncsend_friend_request
- defslash_commands
- deftyping
- asyncunblock
- defuser_commands
- class discord.User¶
Represents a Discord user.
- x == y
Checks if two users are equal.
- x != y
Checks if two users are not equal.
- hash(x)
Return the user’s hash.
- str(x)
Returns the user’s name with discriminator.
- async with typing()¶
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using
await.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!')
Example Usage:
await channel.typing() # Do some computational magic for about 10 seconds await channel.send('Done!')
Changed in version 2.0: This no longer works with the
withsyntax,async withmust be used instead.Changed in version 2.0: Added functionality to
awaitthe context manager to send a typing indicator for 10 seconds.
- async for ... in slash_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the slash commands available in the channel.
Examples
Usage
async for command in channel.slash_commands(): print(command.name)
Flattening into a list
commands = [command async for command in channel.slash_commands()] # commands is now a list of SlashCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
SlashCommand– A slash command.
- async for ... in user_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the user commands available to use on the user.
Examples
Usage
async for command in user.user_commands(): print(command.name)
Flattening into a list
commands = [command async for command in user.user_commands()] # commands is now a list of UserCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
UserCommand– A user command.
- property dm_channel¶
Returns the channel associated with this user if it exists.
If this returns
None, you can create a DM channel by calling thecreate_dm()coroutine function.- Type
Optional[
DMChannel]
- property call¶
Returns the call associated with this user if it exists.
- Type
Optional[
PrivateCall]
- property relationship¶
Returns the
Relationshipwith this user if applicable,Noneotherwise.- Type
Optional[
Relationship]
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, _channel=None, self_deaf=False, self_mute=False)¶
This function is a coroutine.
Connects to voice and creates a
VoiceClientto establish your connection to the voice server.- Parameters
timeout (
float) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (Type[
VoiceProtocol]) – A type that subclassesVoiceProtocolto connect with. Defaults toVoiceClient.self_mute (
bool) –Indicates if the client should be self-muted.
New in version 2.0.
self_deaf (
bool) –Indicates if the client should be self-deafened.
New in version 2.0.
- Raises
asyncio.TimeoutError – Could not connect to the voice channel in time.
ClientException – You are already connected to a voice channel.
OpusNotLoaded – The opus library has not been loaded.
- Returns
A voice client that is fully connected to the voice server.
- Return type
- await create_dm()¶
This function is a coroutine.
Creates a
DMChannelwith this user.This should be rarely called, as this is done transparently for most people.
- Returns
The channel that was created.
- Return type
- await block()¶
This function is a coroutine.
Blocks the user.
- Raises
Forbidden – Not allowed to block this user.
HTTPException – Blocking the user failed.
- await unblock()¶
This function is a coroutine.
Unblocks the user.
- Raises
Forbidden – Not allowed to unblock this user.
HTTPException – Unblocking the user failed.
- await remove_friend()¶
This function is a coroutine.
Removes the user as a friend.
- Raises
Forbidden – Not allowed to remove this user as a friend.
HTTPException – Removing the user as a friend failed.
- await send_friend_request()¶
This function is a coroutine.
Sends the user a friend request.
- Raises
Forbidden – Not allowed to send a friend request to the user.
HTTPException – Sending the friend request failed.
- 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]
- await ack()¶
This function is a coroutine.
Marks every message in this channel as read.
- Raises
HTTPException – Acking the channel failed.
- await ack_pins()¶
This function is a coroutine.
Marks a channel’s pins as viewed.
- Raises
HTTPException – Acking the pinned messages failed.
- property avatar¶
Returns an
Assetfor the avatar the user has.If the user has not uploaded a global avatar,
Noneis returned. If you want the avatar that a user has displayed, considerdisplay_avatar.- Type
Optional[
Asset]
- property avatar_decoration¶
Returns an
Assetfor the avatar decoration the user has.If the user does not have a avatar decoration,
Noneis returned.New in version 2.0.
- Type
Optional[
Asset]
- 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 default_avatar¶
Returns the default avatar for a given user. This is calculated by the user’s discriminator.
- 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_banner¶
Returns the user’s banner asset, if available.
This is the same as
bannerand is here for compatibility.New in version 2.0.
- Type
Optional[
Asset]
- property display_name¶
Returns the user’s display name.
For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
- Type
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters
id (
int) – The message ID to look for.- 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.
- Returns
The message asked for.
- Return type
- await greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...)¶
This function is a coroutine.
Sends a sticker greeting to the destination.
A sticker greeting is used to begin a new DM or reply to a system message.
New in version 2.0.
- Parameters
sticker (Union[
GuildSticker,StickerItem]) – The sticker to greet with.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead. In the case of greeting, onlyreplied_useris considered.reference (Union[
Message,MessageReference,PartialMessage]) – A reference to theMessageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.mention_author (
bool) – If set, overrides thereplied_userattribute ofallowed_mentions.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
TypeError – The
referenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The sticker greeting that was sent.
- Return type
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an asynchronous iterator that enables receiving the destination’s message history.
You must have
read_message_historyto do this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in channel.history(limit=123)] # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. 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 messages after this date or message. 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.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields
Message– The message with the message data parsed.
- mentioned_in(message)¶
Checks if the user is mentioned in the specified message.
- note¶
Returns an object representing the user’s note.
New in version 2.0.
Note
The underlying note is cached and updated from gateway events.
- Type
- await pins()¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises
Forbidden – You do not have the permission to retrieve pinned messages.
HTTPException – Retrieving the pinned messages failed.
- Returns
The messages that are currently pinned.
- Return type
List[
Message]
- await profile(*, with_mutual_guilds=True, with_mutual_friends_count=False, with_mutual_friends=True)¶
This function is a coroutine.
A shorthand method to retrieve a
UserProfilefor the user.- Parameters
with_mutual_guilds (
bool) –Whether to fetch mutual guilds. This fills in
UserProfile.mutual_guilds.New in version 2.0.
with_mutual_friends_count (
bool) –Whether to fetch the number of mutual friends. This fills in
UserProfile.mutual_friends_count.New in version 2.0.
with_mutual_friends (
bool) –Whether to fetch mutual friends. This fills in
UserProfile.mutual_friendsandUserProfile.mutual_friends_count, but requires an extra API call.New in version 2.0.
- Raises
Forbidden – Not allowed to fetch this profile.
HTTPException – Fetching the profile failed.
- Returns
The profile of the user.
- Return type
- property public_flags¶
The publicly available flags the user has.
- Type
- await send(content=None, *, tts=False, file=None, files=None, stickers=None, delete_after=None, nonce=..., allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, silent=False)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then a sticker or file must be sent.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (
int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. Generates one by default.delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.New in version 1.6.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
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.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate size.TypeError – You specified both
fileandfiles, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The message that was sent.
- Return type
- property voice¶
Returns the user’s current voice state.
- Type
Optional[
VoiceState]
- accent_color
- accent_colour
- application
- avatar
- avatar_decoration
- banner
- bio
- call
- color
- colour
- connections
- created_at
- default_avatar
- display_avatar
- display_banner
- display_bio
- display_name
- dm_channel
- mention
- mutual_friends
- mutual_friends_count
- mutual_guilds
- note
- premium
- premium_guild_since
- premium_since
- premium_type
- public_flags
- relationship
- voice
- asyncack
- asyncack_pins
- asyncblock
- asyncconnect
- asynccreate_dm
- asyncfetch_message
- asyncgreet
- async forhistory
- defis_blocked
- defis_friend
- defmentioned_in
- asyncpins
- asyncprofile
- asyncremove_friend
- asyncsend
- asyncsend_friend_request
- defslash_commands
- deftyping
- asyncunblock
- defuser_commands
- class discord.UserProfile¶
Represents a Discord user’s profile.
This is a
Userwith extended attributes.- x == y
Checks if two users are equal.
- x != y
Checks if two users are not equal.
- hash(x)
Return the user’s hash.
- str(x)
Returns the user’s name with discriminator.
New in version 2.0.
- application¶
The application profile of the user, if it is a bot.
- Type
Optional[
ApplicationProfile]
Specifies the type of premium a user has (i.e. Nitro, Nitro Classic, or Nitro Basic). Could be None if the user is not premium.
- Type
Optional[
PremiumType]
An aware datetime object that specifies how long a user has been premium (had Nitro).
Noneif the user is not a premium user.- Type
Optional[
datetime.datetime]
An aware datetime object that specifies when a user first Nitro boosted a guild.
- Type
Optional[
datetime.datetime]
- connections¶
The connected accounts that show up on the profile.
- Type
Optional[List[
PartialConnection]]
- mutual_guilds¶
A list of guilds that you share with the user.
Noneif you didn’t fetch mutual guilds.- Type
Optional[List[
MutualGuild]]
- mutual_friends¶
A list of friends that you share with the user.
Noneif you didn’t fetch mutual friends.- Type
Optional[List[
User]]
- property display_bio¶
Returns the user’s display bio.
This is the same as
bioand is here for compatibility.- Type
Optional[
str]
- 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]
- await ack()¶
This function is a coroutine.
Marks every message in this channel as read.
- Raises
HTTPException – Acking the channel failed.
- await ack_pins()¶
This function is a coroutine.
Marks a channel’s pins as viewed.
- Raises
HTTPException – Acking the pinned messages failed.
- property avatar¶
Returns an
Assetfor the avatar the user has.If the user has not uploaded a global avatar,
Noneis returned. If you want the avatar that a user has displayed, considerdisplay_avatar.- Type
Optional[
Asset]
- property avatar_decoration¶
Returns an
Assetfor the avatar decoration the user has.If the user does not have a avatar decoration,
Noneis returned.New in version 2.0.
- Type
Optional[
Asset]
- 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]
- await block()¶
This function is a coroutine.
Blocks the user.
- Raises
Forbidden – Not allowed to block this user.
HTTPException – Blocking the user failed.
- property call¶
Returns the call associated with this user if it exists.
- Type
Optional[
PrivateCall]
- 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
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, _channel=None, self_deaf=False, self_mute=False)¶
This function is a coroutine.
Connects to voice and creates a
VoiceClientto establish your connection to the voice server.- Parameters
timeout (
float) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (Type[
VoiceProtocol]) – A type that subclassesVoiceProtocolto connect with. Defaults toVoiceClient.self_mute (
bool) –Indicates if the client should be self-muted.
New in version 2.0.
self_deaf (
bool) –Indicates if the client should be self-deafened.
New in version 2.0.
- Raises
asyncio.TimeoutError – Could not connect to the voice channel in time.
ClientException – You are already connected to a voice channel.
OpusNotLoaded – The opus library has not been loaded.
- Returns
A voice client that is fully connected to the voice server.
- Return type
- await create_dm()¶
This function is a coroutine.
Creates a
DMChannelwith this user.This should be rarely called, as this is done transparently for most people.
- Returns
The channel that was created.
- Return type
- property created_at¶
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
- Type
- property default_avatar¶
Returns the default avatar for a given user. This is calculated by the user’s discriminator.
- 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_banner¶
Returns the user’s banner asset, if available.
This is the same as
bannerand is here for compatibility.New in version 2.0.
- Type
Optional[
Asset]
- property display_name¶
Returns the user’s display name.
For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
- Type
- property dm_channel¶
Returns the channel associated with this user if it exists.
If this returns
None, you can create a DM channel by calling thecreate_dm()coroutine function.- Type
Optional[
DMChannel]
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters
id (
int) – The message ID to look for.- 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.
- Returns
The message asked for.
- Return type
- await greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...)¶
This function is a coroutine.
Sends a sticker greeting to the destination.
A sticker greeting is used to begin a new DM or reply to a system message.
New in version 2.0.
- Parameters
sticker (Union[
GuildSticker,StickerItem]) – The sticker to greet with.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead. In the case of greeting, onlyreplied_useris considered.reference (Union[
Message,MessageReference,PartialMessage]) – A reference to theMessageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.mention_author (
bool) – If set, overrides thereplied_userattribute ofallowed_mentions.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
TypeError – The
referenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The sticker greeting that was sent.
- Return type
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an asynchronous iterator that enables receiving the destination’s message history.
You must have
read_message_historyto do this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in channel.history(limit=123)] # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. 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 messages after this date or message. 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.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields
Message– The message with the message data parsed.
- mentioned_in(message)¶
Checks if the user is mentioned in the specified message.
- property mutual_friends_count¶
The number of mutual friends the user has with the client user.
- Type
Optional[
int]
- note¶
Returns an object representing the user’s note.
New in version 2.0.
Note
The underlying note is cached and updated from gateway events.
- Type
- await pins()¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises
Forbidden – You do not have the permission to retrieve pinned messages.
HTTPException – Retrieving the pinned messages failed.
- Returns
The messages that are currently pinned.
- Return type
List[
Message]
Indicates if the user is a premium user.
- Type
- await profile(*, with_mutual_guilds=True, with_mutual_friends_count=False, with_mutual_friends=True)¶
This function is a coroutine.
A shorthand method to retrieve a
UserProfilefor the user.- Parameters
with_mutual_guilds (
bool) –Whether to fetch mutual guilds. This fills in
UserProfile.mutual_guilds.New in version 2.0.
with_mutual_friends_count (
bool) –Whether to fetch the number of mutual friends. This fills in
UserProfile.mutual_friends_count.New in version 2.0.
with_mutual_friends (
bool) –Whether to fetch mutual friends. This fills in
UserProfile.mutual_friendsandUserProfile.mutual_friends_count, but requires an extra API call.New in version 2.0.
- Raises
Forbidden – Not allowed to fetch this profile.
HTTPException – Fetching the profile failed.
- Returns
The profile of the user.
- Return type
- property public_flags¶
The publicly available flags the user has.
- Type
- property relationship¶
Returns the
Relationshipwith this user if applicable,Noneotherwise.- Type
Optional[
Relationship]
- await remove_friend()¶
This function is a coroutine.
Removes the user as a friend.
- Raises
Forbidden – Not allowed to remove this user as a friend.
HTTPException – Removing the user as a friend failed.
- await send(content=None, *, tts=False, file=None, files=None, stickers=None, delete_after=None, nonce=..., allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, silent=False)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then a sticker or file must be sent.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (
int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. Generates one by default.delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.New in version 1.6.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
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.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate size.TypeError – You specified both
fileandfiles, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The message that was sent.
- Return type
- await send_friend_request()¶
This function is a coroutine.
Sends the user a friend request.
- Raises
Forbidden – Not allowed to send a friend request to the user.
HTTPException – Sending the friend request failed.
- slash_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the slash commands available in the channel.
Examples
Usage
async for command in channel.slash_commands(): print(command.name)
Flattening into a list
commands = [command async for command in channel.slash_commands()] # commands is now a list of SlashCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
SlashCommand– A slash command.
- typing()¶
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using
await.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!')
Example Usage:
await channel.typing() # Do some computational magic for about 10 seconds await channel.send('Done!')
Changed in version 2.0: This no longer works with the
withsyntax,async withmust be used instead.Changed in version 2.0: Added functionality to
awaitthe context manager to send a typing indicator for 10 seconds.
- await unblock()¶
This function is a coroutine.
Unblocks the user.
- Raises
Forbidden – Not allowed to unblock this user.
HTTPException – Unblocking the user failed.
- user_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the user commands available to use on the user.
Examples
Usage
async for command in user.user_commands(): print(command.name)
Flattening into a list
commands = [command async for command in user.user_commands()] # commands is now a list of UserCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
UserCommand– A user command.
- property voice¶
Returns the user’s current voice state.
- Type
Optional[
VoiceState]
- class discord.Note¶
Represents a Discord note.
- x == y
- Checks if two notes are equal.
- x != y
- Checks if two notes are not equal.
- hash(x)
- Returns the note's hash.
- str(x)
- Returns the note's content.
- Raises :exc:`ClientException` if the note is not fetched.
- bool(x)
- Returns the note's content as a boolean.
- len(x)
- Returns the note's length.
New in version 1.9.
- property note¶
Returns the note.
There is an alias for this called
value.- Raises
ClientException – Attempted to access note without fetching it.
- Type
Optional[
str]
- property value¶
Returns the note.
This is an alias of
note.- Raises
ClientException – Attempted to access note without fetching it.
- Type
Optional[
str]
- await fetch()¶
This function is a coroutine.
Retrieves the note.
- Raises
HTTPException – Fetching the note failed.
- Returns
The note or
Noneif it doesn’t exist.- Return type
Optional[
str]
- await edit(note)¶
This function is a coroutine.
Modifies the note. Can be at most 256 characters.
- Raises
HTTPException – Changing the note failed.
- await delete()¶
This function is a coroutine.
A shortcut to
edit()that deletes the note.- Raises
HTTPException – Deleting the note failed.
Affinity¶
- class discord.UserAffinity¶
Represents a user’s affinity with another user.
User affinities that the current user has a mutual guild with are treated as implicit relationships, meaning that you get their user presence synced like a friend.
These implicit relationships are not real relationships, and are therefore not returned by the API. However, they are lazily added to cache by the library when detected.
- x == y
Checks if two affinities are equal.
- x != y
Checks if two affinities are not equal.
- hash(x)
Return the affinity’s hash.
New in version 2.0.
- class discord.GuildAffinity¶
Represents a user’s affinity with a guild.
- x == y
Checks if two affinities are equal.
- x != y
Checks if two affinities are not equal.
- hash(x)
Return the affinity’s hash.
New in version 2.0.
Billing¶
- class discord.BillingAddress¶
Represents a billing address.
- x == y
Checks if two billing addresses are equal.
- x != y
Checks if two billing addresses are not equal.
- hash(x)
Returns the address’ hash.
New in version 2.0.
- await validate()¶
This function is a coroutine.
Validates the billing address.
- Raises
TypeError – The billing address does not have state attached.
HTTPException – The billing address is invalid.
- Returns
The billing address token.
- Return type
- class discord.PaymentSource¶
Represents a payment source.
- x == y
Checks if two payment sources are equal.
- x != y
Checks if two payment sources are not equal.
- hash(x)
Returns the source’s hash.
New in version 2.0.
- partial_card_number¶
The last four digits of the payment source. This is only available for cards.
- Type
Optional[
str]
- billing_address¶
The billing address of the payment source. Not available in all contexts.
- Type
Optional[
BillingAddress]
- type¶
The type of the payment source.
- Type
- payment_gateway¶
The payment gateway of the payment source.
- Type
- expires_at¶
When the payment source expires. This is only available for cards.
- Type
Optional[
datetime.date]
- email¶
The email address associated with the payment source, if any. This is only available for PayPal.
- Type
Optional[
str]
- bank¶
The bank associated with the payment source, if any. This is only available for certain payment sources.
- Type
Optional[
str]
- username¶
The username associated with the payment source, if any. This is only available for Venmo.
- Type
Optional[
str]
- property flags¶
Returns the payment source’s flags.
- Type
- await edit(*, billing_address=..., default=..., expires_at=...)¶
This function is a coroutine.
Edits the payment source.
- Parameters
billing_address (
BillingAddress) – The billing address of the payment source.default (
bool) – Whether the payment source is the default payment source.expires_at (
datetime.date) – When the payment source expires. This is only applicable to cards.
- Raises
HTTPException – Editing the payment source failed.
- await delete()¶
This function is a coroutine.
Deletes the payment source.
- Raises
HTTPException – Deleting the payment source failed.
- class discord.PremiumUsage¶
Represents the usage of a user’s premium perks.
New in version 2.0.
Connection¶
- asyncdelete
- asyncedit
- asyncfetch_access_token
- asyncrefresh
- class discord.Connection¶
Represents a Discord profile connection.
New in version 2.0.
- x == y
Checks if two connections are equal.
- x != y
Checks if two connections are not equal.
- hash(x)
Return the connection’s hash.
- str(x)
Returns the connection’s name.
- two_way_link¶
Whether the connection is authorized both ways (i.e. it’s both a connection and an authorization).
- Type
- metadata¶
Various metadata about the connection.
The contents of this are always subject to change.
- Type
Optional[
Metadata]
- integrations¶
The integrations attached to the connection.
- Type
List[
Integration]
- await edit(*, name=..., visible=..., friend_sync=..., show_activity=..., metadata_visible=...)¶
This function is a coroutine.
Edit the connection.
All parameters are optional.
- Parameters
name (
str) – The new name of the connection. Only editable for certain connection types.visible (
bool) – Whether the connection is visible on your profile.show_activity (
bool) – Whether activities from this connection will be shown in presences.friend_sync (
bool) – Whether friends are synced over the connection.metadata_visible (
bool) – Whether the connection’s metadata is visible.
- Raises
HTTPException – Editing the connection failed.
- Returns
The edited connection.
- Return type
- await refresh()¶
This function is a coroutine.
Refreshes the connection. This updates the connection’s
metadata.- Raises
HTTPException – Refreshing the connection failed.
- await delete()¶
This function is a coroutine.
Removes the connection.
- Raises
HTTPException – Deleting the connection failed.
- await fetch_access_token()¶
This function is a coroutine.
Retrieves a new access token for the connection. Only applicable for connections of type:attr:ConnectionType.twitch,
ConnectionType.youtube, andConnectionType.spotify.- Raises
HTTPException – Retrieving the access token failed.
- Returns
The new access token.
- Return type
- class discord.PartialConnection¶
Represents a partial Discord profile connection.
This is the info you get for other users’ connections.
New in version 2.0.
- x == y
Checks if two connections are equal.
- x != y
Checks if two connections are not equal.
- hash(x)
Return the connection’s hash.
- str(x)
Returns the connection’s name.
- type¶
The connection service type (e.g. youtube, twitch, etc.).
- Type
Relationship¶
- asyncaccept
- asyncdelete
- asyncedit
- defis_on_mobile
- class discord.Relationship¶
Represents a relationship in Discord.
A relationship is like a friendship, a person who is blocked, etc.
- x == y
Checks if two relationships are equal.
- x != y
Checks if two relationships are not equal.
- hash(x)
Return the relationship’s hash.
- type¶
The type of relationship you have.
- Type
- nick¶
The user’s friend nickname (if applicable).
New in version 1.9.
Changed in version 2.0: Renamed
nicknametonick.- Type
Optional[
str]
- since¶
When the relationship was created. Only available for type
RelationshipType.incoming_request.New in version 2.0.
- Type
Optional[
datetime.datetime]
- property status¶
The user’s overall status.
New in version 2.0.
Note
This is only reliably provided for type
RelationshipType.friend.- Type
- property raw_status¶
The user’s overall status as a string value.
New in version 2.0.
Note
This is only reliably provided for type
RelationshipType.friend.- Type
- property mobile_status¶
The user’s status on a mobile device, if applicable.
New in version 2.0.
Note
This is only reliably provided for type
RelationshipType.friend.- Type
- property desktop_status¶
The user’s status on the desktop client, if applicable.
New in version 2.0.
Note
This is only reliably provided for type
RelationshipType.friend.- Type
- property web_status¶
The user’s status on the web client, if applicable.
New in version 2.0.
Note
This is only reliably provided for type
RelationshipType.friend.- Type
- is_on_mobile()¶
bool: A helper function that determines if a user is active on a mobile device.New in version 2.0.
Note
This is only reliably provided for type
RelationshipType.friend.
- property activities¶
Returns the activities that the user is currently doing.
New in version 2.0.
Note
This is only reliably provided for type
RelationshipType.friend.Note
Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.
- Type
Tuple[Union[
BaseActivity,Spotify]]
- property activity¶
Returns the primary activity the user is currently doing. Could be
Noneif no activity is being done.New in version 2.0.
Note
This is only reliably provided for type
RelationshipType.friend.Note
Due to a Discord API limitation, this may be
Noneif the user is listening to a song on Spotify with a title longer than 128 characters. See GH-1738 for more information.Note
A user may have multiple activities, these can be accessed under
activities.- Type
Optional[Union[
BaseActivity,Spotify]]
- await delete()¶
This function is a coroutine.
Deletes the relationship.
Depending on the type, this could mean unfriending or unblocking the user, denying an incoming friend request, discarding an outgoing friend request, etc.
- Raises
HTTPException – Deleting the relationship failed.
- await accept()¶
This function is a coroutine.
Accepts the relationship request. Only applicable for type
RelationshipType.incoming_request.- Raises
HTTPException – Accepting the relationship failed.
- await edit(nick=...)¶
This function is a coroutine.
Edits the relationship.
New in version 1.9.
Changed in version 2.0: Changed the name of the method to
edit(). The edit is no longer in-place.- Parameters
nick (Optional[
str]) – The nickname to change to. Can beNoneto denote no nickname.- Raises
HTTPException – Changing the nickname failed.
Settings¶
- activity_joining_restricted_guilds
- activity_restricted_guilds
- afk_timeout
- allow_accessibility_detection
- allow_activity_friend_joins
- allow_activity_voice_channel_joins
- always_preview_video
- animate_emojis
- animate_stickers
- client_theme
- client_version
- collapsed_emoji_picker_sections
- collapsed_sticker_picker_sections
- contact_sync_enabled
- convert_emoticons
- custom_activity
- data_version
- default_guilds_activity_restricted
- default_guilds_restricted
- default_message_request_restricted
- detect_platform_accounts
- developer_mode
- disable_games_tab
- disable_mobile_redesign
- dismissed_contents
- diversity_surrogate
- drops
- enable_tts_command
- explicit_content_filter
- friend_discovery_flags
- friend_source_flags
- gif_auto_play
- guild_folders
- guild_positions
- guild_progress_settings
- home_auto_navigation
- in_app_notifications
- inbox_tab
- inbox_tutorial_viewed
- inline_attachment_media
- inline_embed_media
- install_shortcut_desktop
- install_shortcut_start_menu
- last_dismissed_promotion_start_date
- locale
- message_display_compact
- message_request_restricted_guilds
- native_phone_integration_enabled
- nitro_basic_modal_dismissed_at
- non_spam_retraining
- notification_center_acked_before_id
- passwordless
- render_embeds
- render_reactions
- render_spoilers
- restricted_guilds
- rtc_panel_show_voice_states
- send_stream_notifications
- server_version
- show_command_suggestions
- show_current_game
- show_expression_suggestions
- soundboard_volume
- status
- stream_audio_settings
- stream_notifications_enabled
- theme
- timezone_offset
- use_legacy_chat_input
- use_thread_sidebar
- user_audio_settings
- view_image_descriptions
- view_nsfw_commands
- view_nsfw_guilds
- asyncedit
- class discord.UserSettings¶
Represents the Discord client settings.
New in version 2.0.
- property client_version¶
The client version of the settings. Used for client-side data migrations.
- Type
- property server_version¶
The server version of the settings. Used for server-side data migrations.
- Type
- property guild_progress_settings¶
A list of guild progress settings.
- Type
List[
GuildProgress]
- property dismissed_contents¶
A list of enum values representing dismissable content in the app.
Note
For now, this just returns the raw values without converting to a proper enum, as the enum values change too often to be viably maintained.
- Type
Tuple[
int]
- property last_dismissed_promotion_start_date¶
The date the last dismissed promotion started.
- Type
Optional[
datetime.datetime]
- property nitro_basic_modal_dismissed_at¶
The date the Nitro Basic modal was dismissed.
- Type
Optional[
datetime.datetime]
- property always_preview_video¶
Whether to always show the preview modal when the user turns on their camera.
- property afk_timeout¶
How long (in seconds) the user needs to be AFK until Discord sends push notifications to mobile devices (30-600).
- Type
- property stream_notifications_enabled¶
Whether stream notifications for friends will be received.
- Type
- property diversity_surrogate¶
The unicode character used as the diversity surrogate for supported emojis (i.e. emoji skin tones,
🏻).- Type
Optional[
str]
- property render_spoilers¶
When to show spoiler content.
- Type
- property collapsed_emoji_picker_sections¶
A list of emoji picker sections (including guild IDs) that are collapsed.
- Type
Tuple[Union[
EmojiPickerSection,Guild]]
- property collapsed_sticker_picker_sections¶
A list of sticker picker sections (including guild and sticker pack IDs) that are collapsed.
- Type
Tuple[Union[
StickerPickerSection,Guild,Object]]
- property show_command_suggestions¶
Whether to show application command suggestions in-chat.
- Type
- property inline_attachment_media¶
Whether to display attachments when they are uploaded in chat.
- Type
- property inline_embed_media¶
Whether to display videos and images from links posted in chat.
- Type
- property animate_stickers¶
Whether to animate stickers in the chat.
- property explicit_content_filter¶
The filter for explicit content in all messages.
- Type
- property convert_emoticons¶
Whether to automatically convert emoticons into emojis (e.g.
:)-> 😃).- Type
- property show_expression_suggestions¶
Whether to show expression (emoji/sticker/soundboard) suggestions in-chat.
- Type
- property use_legacy_chat_input¶
Whether to use the legacy chat input over the new rich input.
- Type
- property send_stream_notifications¶
Whether to send notifications to friends when using the go live feature.
- Type
- property notification_center_acked_before_id¶
The ID of the last notification that was acknowledged in the notification center.
- Type
- property allow_activity_friend_joins¶
Whether to allow friends to join your activity without sending a request.
- Type
- property allow_activity_voice_channel_joins¶
Whether to allow people in the same voice channel as you to join your activity without sending a request. Does not apply to Community guilds.
- Type
- property default_guilds_restricted¶
Whether to automatically disable DMs between you and members of new guilds you join.
- Type
- property allow_accessibility_detection¶
Whether to allow Discord to track screen reader usage.
- Type
- property detect_platform_accounts¶
Whether to automatically detect accounts from services like Steam and Blizzard when you open the Discord client.
- Type
- property friend_source_flags¶
Who can add you as a friend.
- Type
- property friend_discovery_flags¶
How you get recommended friends.
- Type
- property activity_restricted_guilds¶
A list of guilds that your current activity will not be shown in.
- Type
List[
Guild]
- property default_guilds_activity_restricted¶
Whether to automatically disable showing your current activity in new large (over 200 member) guilds you join.
- Type
- property activity_joining_restricted_guilds¶
A list of guilds that will not be able to join your current activity.
- Type
List[
Guild]
- property message_request_restricted_guilds¶
A list of guilds whose originating DMs will not be filtered into your message requests.
- Type
List[
Guild]
- property default_message_request_restricted¶
Whether to automatically disable the message request system in new guilds you join.
- Type
- property non_spam_retraining¶
Whether to help improve Discord spam models when marking messages as non-spam; staff only.
- Type
Optional[
bool]
Whether to install a start menu shortcut for games.
- Type
- property custom_activity¶
The set custom activity.
- Type
- property locale¶
The RFC 3066 language identifier of the locale to use for the language of the Discord client.
- Type
- property client_theme¶
The client theme settings, in order of primary color, gradient preset, and gradient angle.
- property guild_folders¶
A list of guild folders.
- Type
List[
GuildFolder]
- property guild_positions¶
A list of guilds in order of the guild/guild icons that are on the left hand side of the UI.
- Type
List[
Guild]
- property user_audio_settings¶
A list of audio context settings for users.
- Type
List[
AudioContext]
- property stream_audio_settings¶
A list of audio context settings for streams.
- Type
List[
AudioContext]
Whether to automatically redirect to guild home for guilds that have not been accessed in a while.
- Type
- await edit(*, require_version=False, **kwargs)¶
This function is a coroutine.
Edits the current user’s settings.
Note
Settings subsections are not idempotently updated. This means if you change one setting in a subsection* on an outdated instance of
UserSettingsthen the other settings in that subsection* will be reset to the value of the instance.When operating on the cached user settings (i.e.
Client.settings), this should not be an issue. However, if you are operating on a fetched instance, consider using therequire_versionparameter to ensure you don’t overwrite newer settings.Any field may be explicitly set to
MISSINGto reset it to the default value.* A subsection is a group of settings that are stored in the same top-level protobuf message. Examples include Privacy, Text and Images, Voice and Video, etc.
Note
This method is ratelimited heavily. Updates should be batched together and sent at intervals.
Infrequent actions do not need a delay. Frequent actions should be delayed by 10 seconds and batched. Automated actions (such as migrations or frecency updates) should be delayed by 30 seconds and batched. Daily actions (things that change often and are not meaningful, such as emoji frencency) should be delayed by 1 day and batched.
- Parameters
require_version (Union[
bool,int]) – Whether to require the current version of the settings to be the same as the provided version. If this isTruethen the current version is used.**kwargs – The settings to edit. Refer to the
UserSettingsproperties for the valid fields. Unknown fields are ignored.
- Raises
HTTPException – Editing the settings failed.
TypeError – At least one setting is required to edit.
- Returns
The edited settings. Note that this is a new instance and not the same as the cached instance as mentioned above.
- Return type
- activity_joining_restricted_guilds
- activity_restricted_guilds
- afk_timeout
- allow_accessibility_detection
- animate_emojis
- animate_stickers
- contact_sync_enabled
- convert_emoticons
- custom_activity
- default_guilds_restricted
- detect_platform_accounts
- developer_mode
- disable_games_tab
- enable_tts_command
- explicit_content_filter
- friend_discovery_flags
- friend_source_flags
- gif_auto_play
- guild_folders
- guild_positions
- inline_attachment_media
- inline_embed_media
- locale
- message_display_compact
- native_phone_integration_enabled
- passwordless
- render_embeds
- render_reactions
- restricted_guilds
- show_current_game
- status
- stream_notifications_enabled
- theme
- timezone_offset
- view_nsfw_commands
- view_nsfw_guilds
- asyncedit
- class discord.LegacyUserSettings¶
Represents the legacy Discord client settings.
New in version 1.9.
Deprecated since version 2.0.
Note
Discord has migrated user settings to a new protocol buffer format. While these legacy settings still exist, they are no longer sent to newer clients (so they will have to be fetched).
The new settings are available in
UserSettings, and this class has been deprecated and renamed toLegacyUserSettings. All options in this class are available in the new format, and changes are reflected in both.- afk_timeout¶
How long (in seconds) the user needs to be AFK until Discord sends push notifications to mobile devices (30-600).
- Type
- default_guilds_restricted¶
Whether to automatically disable DMs between you and members of new guilds you join.
- Type
- detect_platform_accounts¶
Whether to automatically detect accounts from services like Steam and Blizzard when you open the Discord client.
- Type
- native_phone_integration_enabled¶
Whether to enable the new Discord mobile phone number friend requesting features.
- Type
- await edit(**kwargs)¶
This function is a coroutine.
Edits the client user’s settings.
Changed in version 2.0: The edit is no longer in-place, instead the newly edited settings are returned.
Deprecated since version 2.0.
- Parameters
activity_restricted_guilds (List[
Snowflake]) –A list of guilds that your current activity will not be shown in.
New in version 2.0.
activity_joining_restricted_guilds (List[
Snowflake]) –A list of guilds that will not be able to join your current activity.
New in version 2.0.
afk_timeout (
int) – How long (in seconds) the user needs to be AFK until Discord sends push notifications to mobile device (30-600).allow_accessibility_detection (
bool) – Whether to allow Discord to track screen reader usage.animate_emojis (
bool) – Whether to animate emojis in the chat.animate_stickers (
StickerAnimationOptions) – Whether to animate stickers in the chat.contact_sync_enabled (
bool) – Whether to enable the contact sync on Discord mobile.convert_emoticons (
bool) – Whether to automatically convert emoticons into emojis (e.g. :) -> 😃).default_guilds_restricted (
bool) – Whether to automatically disable DMs between you and members of new guilds you join.detect_platform_accounts (
bool) – Whether to automatically detect accounts from services like Steam and Blizzard when you open the Discord client.developer_mode (
bool) – Whether to enable developer mode.disable_games_tab (
bool) – Whether to disable the showing of the Games tab.enable_tts_command (
bool) – Whether to allow TTS messages to be played/sent.explicit_content_filter (
UserContentFilter) – The filter for explicit content in all messages.friend_source_flags (
FriendSourceFlags) – Who can add you as a friend.friend_discovery_flags (
FriendDiscoveryFlags) – How you get recommended friends.gif_auto_play (
bool) – Whether to automatically play GIFs that are in the chat.guild_positions (List[
Snowflake]) – A list of guilds in order of the guild/guild icons that are on the left hand side of the UI.inline_attachment_media (
bool) – Whether to display attachments when they are uploaded in chat.inline_embed_media (
bool) – Whether to display videos and images from links posted in chat.locale (
Locale) – The RFC 3066 language identifier of the locale to use for the language of the Discord client.message_display_compact (
bool) – Whether to use the compact Discord display mode.native_phone_integration_enabled (
bool) – Whether to enable the new Discord mobile phone number friend requesting features.passwordless (
bool) – Whether to enable passwordless login.render_embeds (
bool) – Whether to render embeds that are sent in the chat.render_reactions (
bool) – Whether to render reactions that are added to messages.restricted_guilds (List[
Snowflake]) – A list of guilds that you will not receive DMs from.show_current_game (
bool) – Whether to display the game that you are currently playing.stream_notifications_enabled (
bool) – Whether stream notifications for friends will be received.theme (
Theme) – The overall theme of the Discord UI.timezone_offset (
int) – The timezone offset to use.view_nsfw_commands (
bool) –Whether to show NSFW application commands in DMs.
New in version 2.0.
view_nsfw_guilds (
bool) –Whether to show NSFW guilds on iOS.
New in version 2.0.
- Raises
HTTPException – Editing the settings failed.
- Returns
The client user’s updated settings.
- Return type
- property activity_restricted_guilds¶
A list of guilds that your current activity will not be shown in.
New in version 2.0.
- Type
List[
Guild]
- property activity_joining_restricted_guilds¶
A list of guilds that will not be able to join your current activity.
New in version 2.0.
- Type
List[
Guild]
- property animate_stickers¶
Whether to animate stickers in the chat.
- property custom_activity¶
The set custom activity.
- Type
Optional[
CustomActivity]
- property explicit_content_filter¶
The filter for explicit content in all messages.
- Type
- property friend_source_flags¶
Who can add you as a friend.
- Type
- property friend_discovery_flags¶
How you get recommended friends.
- Type
- property guild_folders¶
A list of guild folders.
- Type
List[
GuildFolder]
- property guild_positions¶
A list of guilds in order of the guild/guild icons that are on the left hand side of the UI.
- Type
List[
Guild]
- asyncedit
- class discord.GuildSettings¶
Represents a guild’s notification settings.
New in version 2.0.
- level¶
The notification level for the guild.
- Type
- muted¶
The mute configuration for the guild.
- Type
- notify_highlights¶
Whether to include highlights in notifications.
- Type
- property guild¶
Returns the guild that these settings are for.
If the returned value is a
ClientUserthen the settings are for the user’s private channels.- Type
Union[
Guild,ClientUser]
- property channel_overrides¶
Returns a list of all the overrided channel notification settings.
- Type
List[
ChannelSettings
- await edit(muted_until=..., level=..., suppress_everyone=..., suppress_roles=..., mobile_push=..., hide_muted_channels=..., mute_scheduled_events=..., notify_highlights=...)¶
This function is a coroutine.
Edits the guild’s notification settings.
All parameters are optional.
- Parameters
muted_until (Optional[Union[
datetime.datetime,bool]]) –The date this guild’s mute should expire. This can be
Trueto mute indefinitely, orFalse/Noneto unmute.This must be a timezone-aware datetime object. Consider using
utils.utcnow().level (
NotificationLevel) – Determines what level of notifications you receive for the guild.suppress_everyone (
bool) – Indicates if @everyone mentions should be suppressed for the guild.suppress_roles (
bool) – Indicates if role mentions should be suppressed for the guild.mobile_push (
bool) – Indicates if push notifications should be sent to mobile devices for this guild.hide_muted_channels (
bool) – Indicates if channels that are muted should be hidden from the sidebar.mute_scheduled_events (
bool) – Indicates if scheduled events should be muted.notify_highlights (
HighlightLevel) – Indicates if highlights should be included in notifications.
- Raises
HTTPException – Editing the settings failed.
- Returns
The new notification settings.
- Return type
- class discord.ChannelSettings¶
Represents a channel’s notification settings.
New in version 2.0.
- level¶
The notification level for the channel.
- Type
- muted¶
The mute configuration for the channel.
- Type
- collapsed¶
Whether the channel is collapsed. Only applicable to channels of type
ChannelType.category.- Type
- property channel¶
Returns the channel these settings are for.
- Type
Union[
abc.GuildChannel,abc.PrivateChannel]
- await edit(*, muted_until=..., collapsed=..., level=...)¶
This function is a coroutine.
Edits the channel’s notification settings.
All parameters are optional.
- Parameters
muted_until (Optional[Union[
datetime.datetime,bool]]) –The date this channel’s mute should expire. This can be
Trueto mute indefinitely, orFalse/Noneto unmute.This must be a timezone-aware datetime object. Consider using
utils.utcnow().collapsed (
bool) – Indicates if the channel should be collapsed or not. Only applicable to channels of typeChannelType.category.level (
NotificationLevel) – Determines what level of notifications you receive for the channel.
- Raises
HTTPException – Editing the settings failed.
- Returns
The new notification settings.
- Return type
- asyncedit
- class discord.TrackingSettings¶
Represents your Discord tracking settings.
New in version 2.0.
- bool(x)
Checks if any tracking settings are enabled.
- usage_statistics¶
Whether you have consented to your data being used for usage statistics.
- Type
- asyncedit
- class discord.EmailSettings¶
Represents email communication preferences.
New in version 2.0.
- recommendations_and_events¶
Whether you want to receive emails for recommended servers and events.
- Type
- updates_and_announcements¶
Whether you want to receive emails for updates and new features.
- Type
- await edit(**kwargs)¶
This function is a coroutine.
Edits the email settings.
All parameters are optional.
- Parameters
communication (
bool) – Indicates if you want to receive communication emails.social (
bool) – Indicates if you want to receive social emails.recommendations_and_events (
bool) – Indicates if you want to receive recommendations and events emails.tips (
bool) – Indicates if you want to receive tips emails.updates_and_announcements (
bool) – Indicates if you want to receive updates and announcements emails.
- Raises
HTTPException – Editing the settings failed.
- defadd_guild
- defclear_guilds
- defcopy
- definsert_guild_at
- defremove_guild
- defset_guild_at
- class discord.GuildFolder¶
Represents a guild folder.
All properties have setters to faciliate editing the class for use with
UserSettings.edit().- str(x)
Returns the folder’s name.
- len(x)
Returns the number of guilds in the folder.
New in version 1.9.
Changed in version 2.0: Removed various operations and made
idandnameoptional.Note
Guilds not in folders are actually in folders API wise, with them being the only member.
These folders do not have an ID or name.
- copy()¶
Returns a shallow copy of the folder.
- add_guild(guild)¶
Adds a guild to the folder.
This function returns the class instance to allow for fluent-style chaining.
New in version 2.0.
- Parameters
guild (
abc.Snowflake) – The guild to add to the folder.
- insert_guild_at(index, guild)¶
Inserts a guild before a specified index to the folder.
This function returns the class instance to allow for fluent-style chaining.
New in version 2.0.
- Parameters
index (
int) – The index of where to insert the field.guild (
abc.Snowflake) – The guild to add to the folder.
- clear_guilds()¶
Removes all guilds from this folder.
New in version 2.0.
- remove_guild(index)¶
Removes a guild at a specified index.
If the index is invalid or out of bounds then the error is silently swallowed.
Note
When deleting a field by index, the index of the other fields shift to fill the gap just like a regular list.
New in version 2.0.
- Parameters
index (
int) – The index of the field to remove.
- set_guild_at(index, guild)¶
Modifies a guild to the guild object.
The index must point to a valid pre-existing guild.
This function returns the class instance to allow for fluent-style chaining.
New in version 2.0.
- Parameters
index (
int) – The index of the field to modify.guild (
abc.Snowflake) – The guild to add to the folder.
- Raises
IndexError – An invalid index was provided.
- defcopy
- class discord.GuildProgress¶
Represents a guild’s settings revolving around upsells, promotions, and feature progress.
All properties have setters to faciliate editing the class for use with
UserSettings.edit().New in version 2.0.
- recents_dismissed_at¶
When the guild recents were last dismissed.
- Type
Optional[
datetime.datetime]
- copy()¶
Returns a shallow copy of the progress settings.
- property guild¶
The guild this progress belongs to.
Noneif state is not attached.- Type
Optional[
Guild]
- property hub_progress¶
The hub’s usage and feature progress.
- Type
- property onboarding_progress¶
The guild’s onboarding usage and feature progress.
- property dismissed_contents¶
A list of enum values representing per-guild dismissable content in the app.
Note
For now, this just returns the raw values without converting to a proper enum, as the enum values change too often to be viably maintained.
- Type
Tuple[
int]
- property collapsed_channels¶
A list of guild channels that are collapsed in the inbox. Always
Objectif state is not attached.- Type
List[Union[
abc.GuildChannel,Object]]
- class discord.AudioContext¶
Represents saved audio settings for a user or stream.
All properties have setters to faciliate editing the class for use with
UserSettings.edit().New in version 2.0.
- modified_at¶
The time the settings were last modified.
- Type
- to_dict()¶
Converts the object to a dictionary.
- copy()¶
Returns a shallow copy of the audio context.
- class discord.MuteConfig¶
An object representing an object’s mute status.
New in version 2.0.
- x == y
Checks if two items are muted.
- x != y
Checks if two items are not muted.
- str(x)
Returns the mute status as a string.
- int(x)
Returns the mute status as an int.
- until¶
When the mute will expire.
- Type
Optional[
datetime.datetime]
Application¶
- asyncachievements
- asyncactivity_statistics
- asyncassets
- asyncbranches
- asynccreate_achievement
- asynccreate_asset
- asynccreate_bot
- asynccreate_branch
- asynccreate_gift_batch
- asynccreate_sku
- asynccreate_store_asset
- asyncedit
- asyncedit_embedded_activity_config
- asyncentitlement_ticket
- async forentitlements
- asynceula
- asyncfetch_achievement
- asyncfetch_bot
- asyncfetch_discoverability
- asyncfetch_embedded_activity_config
- asyncfetch_entitlement
- asyncgift_batches
- asyncmanifest_labels
- asyncprimary_sku
- asyncprimary_store_listing
- asyncpublished_store_listings
- asyncsecret
- asyncskus
- asyncstore_assets
- asyncstore_listing_sku
- asyncticket
- asyncwhitelist
- asyncwhitelisted
- class discord.Application¶
Represents application info for an application you own.
- x == y
Checks if two applications are equal.
- x != y
Checks if two applications are not equal.
- hash(x)
Return the application’s hash.
- str(x)
Returns the application’s name.
New in version 2.0.
- bot¶
The bot attached to the application, if any.
- Type
Optional[
ApplicationBot]
- 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.
- Type
Optional[
str]
- verification_state¶
The verification state of the application.
- store_application_state¶
The approval state of the commerce application.
- rpc_application_state¶
The approval state of the RPC usage application.
- Type
- discoverability_state¶
The discoverability (app directory) state of the application.
- property discovery_eligibility_flags¶
The discovery (app directory) eligibility flags for this application.
- await edit(*, name=..., description=..., icon=..., cover_image=..., tags=..., terms_of_service_url=..., privacy_policy_url=..., interactions_endpoint_url=..., redirect_uris=..., rpc_origins=..., public=..., require_code_grant=..., flags=..., custom_install_url=..., install_params=..., developers=..., publishers=..., guild=..., team=...)¶
This function is a coroutine.
Edits the application.
All parameters are optional.
- Parameters
name (
str) – The name of the application.description (
str) – The description of the application.icon (Optional[
bytes]) – The icon of the application.cover_image (Optional[
bytes]) – The cover image of the application.tags (List[
str]) – A list of tags that describe the application.terms_of_service_url (Optional[
str]) – The URL to the terms of service of the application.privacy_policy_url (Optional[
str]) – The URL to the privacy policy of the application.interactions_endpoint_url (Optional[
str]) – The URL interactions will be sent to, if set.redirect_uris (List[
str]) – A list of redirect URIs authorized for this application.rpc_origins (List[
str]) – A list of RPC origins authorized for this application.public (
bool) – Whether the application is public or not.require_code_grant (
bool) – Whether the application requires a code grant or not.flags (
ApplicationFlags) – The flags of the application.developers (List[
Company]) – A list of companies that are the developers of the application.publishers (List[
Company]) – A list of companies that are the publishers of the application.guild (
Guild) – The guild to transfer the application to.team (
Team) – The team to transfer the application to.
- Raises
Forbidden – You do not have permissions to edit this application.
HTTPException – Editing the application failed.
- await fetch_bot()¶
This function is a coroutine.
Retrieves the bot attached to this application.
- Raises
Forbidden – You do not have permissions to fetch the bot, or the application does not have a bot.
HTTPException – Fetching the bot failed.
- Returns
The bot attached to this application.
- Return type
- await create_bot()¶
This function is a coroutine.
Creates a bot attached to this application.
- Raises
Forbidden – You do not have permissions to create bots.
HTTPException – Creating the bot failed.
- Returns
The bot that was created.
- Return type
- await whitelisted()¶
This function is a coroutine.
Retrieves the list of whitelisted users (testers) for this application.
- Raises
Forbidden – You do not have permissions to fetch the testers.
HTTPException – Fetching the testers failed.
- Returns
The testers for this application.
- Return type
List[
ApplicationTester]
- await whitelist(*args)¶
This function is a coroutine.
Whitelists a user (adds a tester) for this application.
This function can be used in multiple ways.
# Passing a user object: await app.whitelist(user) # Passing a stringified user: await app.whitelist('Jake#0001') # Passing a username and discriminator: await app.whitelist('Jake', '0001')
- Parameters
- Raises
HTTPException – Inviting the user failed.
TypeError – More than 2 parameters or less than 1 parameter were passed.
- Returns
The new whitelisted user.
- Return type
- await create_asset(name, image, *, type=<ApplicationAssetType.one: 1>)¶
This function is a coroutine.
Uploads an asset to this application.
- Parameters
- Raises
Forbidden – You do not have permissions to upload assets.
HTTPException – Uploading the asset failed.
- Returns
The created asset.
- Return type
- await store_assets()¶
This function is a coroutine.
Retrieves the store assets for this application.
- Raises
Forbidden – You do not have permissions to store assets.
HTTPException – Storing the assets failed.
- Returns
The store assets retrieved.
- Return type
List[
StoreAsset]
- await create_store_asset(file, /)¶
This function is a coroutine.
Uploads a store asset to this application.
- Parameters
file (
File) – The file to upload. Must be a PNG, JPG, GIF, or MP4.- Raises
Forbidden – You do not have permissions to upload assets.
HTTPException – Uploading the asset failed.
- Returns
The created asset.
- Return type
- await skus(*, with_bundled_skus=True, localize=True)¶
This function is a coroutine.
Retrieves the SKUs for this application.
- Parameters
- Raises
Forbidden – You do not have permissions to fetch SKUs.
HTTPException – Fetching the SKUs failed.
- Returns
The SKUs retrieved.
- Return type
List[
SKU]
- await primary_sku(*, localize=True)¶
This function is a coroutine.
Retrieves the primary SKU for this application if it exists.
- Parameters
localize (
bool) – Whether to localize the SKU name and description to the current user’s locale. IfFalsethen all localizations are returned.- Raises
Forbidden – You do not have permissions to fetch SKUs.
HTTPException – Fetching the SKUs failed.
- Returns
The primary SKU retrieved.
- Return type
Optional[
SKU]
- await store_listing_sku(*, localize=True)¶
This function is a coroutine.
Retrieves the store listing SKU for this application if it exists.
- Parameters
localize (
bool) – Whether to localize the SKU name and description to the current user’s locale. IfFalsethen all localizations are returned.- Raises
Forbidden – You do not have permissions to fetch SKUs.
HTTPException – Fetching the SKUs failed.
- Returns
The store listing SKU retrieved.
- Return type
Optional[
SKU]
- await create_sku(*, name, name_localizations=None, legal_notice=None, legal_notice_localizations=None, type, price_tier=None, price_overrides=None, sale_price_tier=None, sale_price_overrides=None, dependent_sku=None, access_level=None, features=None, locales=None, genres=None, content_ratings=None, system_requirements=None, release_date=None, bundled_skus=None, manifest_labels=None)¶
This function is a coroutine.
Creates a SKU for this application.
- Parameters
name (
str) – The SKU’s name.name_localizations (Optional[Mapping[
Locale,str]]) – The SKU’s name localized to other languages.legal_notice (Optional[
str]) – The SKU’s legal notice.legal_notice_localizations (Optional[Mapping[
Locale,str]]) – The SKU’s legal notice localized to other languages.type (
SKUType) – The SKU’s type.price_tier (Optional[
int]) – The price tier of the SKU. This is the base price in USD that other currencies will be calculated from.price_overrides (Optional[Mapping[
str,int]]) – A mapping of currency to price. These prices override the base price tier.sale_price_tier (Optional[
int]) – The sale price tier of the SKU. This is the base sale price in USD that other currencies will be calculated from.sale_price_overrides (Optional[Mapping[
str,int]]) – A mapping of currency to sale price. These prices override the base sale price tier.dependent_sku (Optional[
int]) – The ID of the SKU that this SKU is dependent on.access_level (Optional[
SKUAccessLevel]) – The access level of the SKU.features (Optional[List[
SKUFeature]]) – A list of features of the SKU.locales (Optional[List[
Locale]]) – A list of locales supported by the SKU.genres (Optional[List[
SKUGenre]]) – A list of genres of the SKU.content_ratings (Optional[List[
ContentRating]]) – A list of content ratings of the SKU.system_requirements (Optional[List[
SystemRequirements]]) – A list of system requirements of the SKU.release_date (Optional[
datetime.date]) – The release date of the SKU.bundled_skus (Optional[List[
SKU]]) – A list SKUs that are bundled with this SKU.manifest_labels (Optional[List[
ManifestLabel]]) – A list of manifest labels for the SKU.
- Raises
Forbidden – You do not have permissions to create SKUs.
HTTPException – Creating the SKU failed.
- Returns
The SKU created.
- Return type
- await fetch_achievement(achievement_id)¶
This function is a coroutine.
Retrieves an achievement for this application.
- Parameters
achievement_id (
int) – The ID of the achievement to fetch.- Raises
Forbidden – You do not have permissions to fetch the achievement.
HTTPException – Fetching the achievement failed.
- Returns
The achievement retrieved.
- Return type
- await create_achievement(*, name, name_localizations=None, description, description_localizations=None, icon, secure=False, secret=False)¶
This function is a coroutine.
Creates an achievement for this application.
- Parameters
name (
str) – The name of the achievement.name_localizations (Mapping[
Locale,str]) – The localized names of the achievement.description (
str) – The description of the achievement.description_localizations (Mapping[
Locale,str]) – The localized descriptions of the achievement.icon (
bytes) – The icon of the achievement.secure (
bool) – Whether the achievement is secure.secret (
bool) – Whether the achievement is secret.
- Raises
Forbidden – You do not have permissions to create achievements.
HTTPException – Creating the achievement failed.
- Returns
The created achievement.
- Return type
- async for ... in entitlements(*, user=None, guild=None, skus=None, limit=100, before=None, after=None, oldest_first=..., with_payments=False, exclude_ended=False)¶
Returns an asynchronous iterator that enables receiving this application’s entitlements.
Examples
Usage
counter = 0 async for entitlement in application.entitlements(limit=200, user=client.user): if entitlement.consumed: counter += 1
Flattening into a list:
entitlements = [entitlement async for entitlement in application.entitlements(limit=123)] # entitlements is now a list of Entitlement...
All parameters are optional.
- Parameters
user (Optional[
User]) – The user to retrieve entitlements for.guild (Optional[
Guild]) – The guild to retrieve entitlements for.skus (Optional[List[
SKU]]) – The SKUs to retrieve entitlements for.limit (Optional[
int]) – The number of payments to retrieve. IfNone, retrieves every entitlement the application has. Note, however, that this would make it a slow operation.before (Optional[Union[
abc.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[
abc.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.oldest_first (
bool) – If set toTrue, return entitlements in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.with_payments (
bool) – Whether to include partial payment info in the response.exclude_ended (
bool) – Whether to exclude entitlements that have ended.
- Raises
HTTPException – The request to get payments failed.
- Yields
Entitlement– The entitlement retrieved.
- await fetch_entitlement(entitlement_id, /)¶
This function is a coroutine.
Retrieves an entitlement from this application.
- Parameters
entitlement_id (
int) – The ID of the entitlement to fetch.- Raises
HTTPException – Fetching the entitlement failed.
- Returns
The entitlement retrieved.
- Return type
- await gift_batches()¶
This function is a coroutine.
Retrieves the gift batches for this application.
- Raises
HTTPException – Fetching the gift batches failed.
- Returns
The gift batches retrieved.
- Return type
List[
GiftBatch]
- await create_gift_batch(sku, *, amount, description, entitlement_branches=None, entitlement_starts_at=None, entitlement_ends_at=None)¶
This function is a coroutine.
Creates a gift batch for the specified SKU.
- Parameters
sku (
SKU) – The SKU to create the gift batch for.amount (
int) – The amount of gifts to create in the batch.description (
str) – The description of the gift batch.entitlement_branches (List[
ApplicationBranch]) – The branches to grant in the gifts.entitlement_starts_at (
datetime.date) – When the entitlement is valid from.entitlement_ends_at (
datetime.date) – When the entitlement is valid until.
- Raises
Forbidden – You do not have permissions to create a gift batch.
HTTPException – Creating the gift batch failed.
- Returns
The gift batch created.
- Return type
- await branches()¶
This function is a coroutine.
Retrieves the branches for this application.
- Raises
HTTPException – Fetching the branches failed.
- Returns
The branches retrieved.
- Return type
List[
ApplicationBranch]
- await create_branch(name)¶
This function is a coroutine.
Creates a branch for this application.
Note
The first branch created will always be called
masterand share the same ID as the application.- Parameters
name (
str) – The name of the branch.- Raises
HTTPException – Creating the branch failed.
- Returns
The branch created.
- Return type
- await manifest_labels()¶
This function is a coroutine.
Retrieves the manifest labels for this application.
- Raises
HTTPException – Fetching the manifest labels failed.
- Returns
The manifest labels retrieved.
- Return type
List[
ManifestLabel]
- await fetch_discoverability()¶
This function is a coroutine.
Retrieves the discoverability state for this application.
Note
This method is an API call. For general usage, consider
discoverability_stateanddiscovery_eligibility_flagsinstead.- Raises
HTTPException – Fetching the discoverability failed.
- Returns
The discoverability retrieved.
- Return type
Tuple[
ApplicationDiscoverabilityState,ApplicationDiscoveryFlags]
- await fetch_embedded_activity_config()¶
This function is a coroutine.
Retrieves the embedded activity configuration for this application.
Note
This method is an API call. For general usage, consider
PartialApplication.embedded_activity_configinstead.- Raises
Forbidden – You do not have permissions to fetch the embedded activity config.
HTTPException – Fetching the embedded activity config failed.
- Returns
The embedded activity config retrieved.
- Return type
- await edit_embedded_activity_config(*, supported_platforms=..., orientation_lock_state=..., tablet_orientation_lock_state=..., requires_age_gate=..., shelf_rank=..., free_period_starts_at=..., free_period_ends_at=..., preview_video_asset=...)¶
This function is a coroutine.
Edits the application’s embedded activity configuration.
- Parameters
supported_platforms (List[
EmbeddedActivityPlatform]) – A list of platforms that the activity supports.orientation_lock_state (
EmbeddedActivityOrientation) – The mobile orientation lock state of the activity.tablet_orientation_lock_state (
EmbeddedActivityOrientation) – The mobile orientation lock state of the activity on tablets.requires_age_gate (
bool) – Whether the activity should be blocked from underage users.shelf_rank (
int) – The sorting rank of the activity in the activity shelf.free_period_starts_at (Optional[
datetime.datetime]) – When the activity’s free availability period starts.free_period_ends_at (Optional[
datetime.datetime]) – When the activity’s free availability period ends.preview_video_asset (Optional[
ApplicationAsset]) – The preview video asset of the activity.
- Raises
Forbidden – You are not allowed to edit this application’s configuration.
HTTPException – Editing the configuration failed.
- Returns
The edited configuration.
- Return type
- await secret()¶
This function is a coroutine.
Gets the application’s secret.
This revokes all previous secrets.
- Raises
Forbidden – You do not have permissions to reset the secret.
HTTPException – Getting the secret failed.
- Returns
The new secret.
- Return type
- await achievements(completed=True)¶
This function is a coroutine.
Retrieves the achievements for this application.
- Parameters
completed (
bool) –Whether to only include achievements the user has completed or can access. This means secret achievements that are not yet unlocked will not be included.
If
False, then you require access to the application.- Raises
Forbidden – You do not have permissions to fetch achievements.
HTTPException – Fetching the achievements failed.
- Returns
The achievements retrieved.
- Return type
List[
Achievement]
- await activity_statistics()¶
This function is a coroutine.
Retrieves the activity usage statistics for this application.
- Raises
HTTPException – Retrieving the statistics failed.
- Returns
The statistics retrieved.
- Return type
- await assets()¶
This function is a coroutine.
Retrieves the assets of this application.
- Raises
HTTPException – Retrieving the assets failed.
- Returns
The application’s assets.
- Return type
List[
ApplicationAsset]
- await entitlement_ticket()¶
This function is a coroutine.
Retrieves the entitlement ticket for this application.
- Raises
HTTPException – Retrieving the ticket failed.
- Returns
The ticket retrieved.
- Return type
- await eula()¶
This function is a coroutine.
Retrieves the EULA for this application.
- Raises
HTTPException – Retrieving the EULA failed.
- Returns
The EULA retrieved, if any.
- Return type
Optional[
EULA]
- property flags¶
The flags of this application.
- Type
- await primary_store_listing(*, localize=True)¶
This function is a coroutine.
Retrieves the primary store listing of this application.
This is the public store listing of the primary SKU.
- Parameters
localize (
bool) – Whether to localize the store listing to the current user’s locale. IfFalsethen all localizations are returned.- Raises
NotFound – The application does not have a primary SKU.
HTTPException – Retrieving the store listing failed.
- Returns
The application’s primary store listing, if any.
- Return type
- await published_store_listings(*, localize=True)¶
This function is a coroutine.
Retrieves all published store listings for this application.
- Parameters
localize (
bool) – Whether to localize the store listings to the current user’s locale. IfFalsethen all localizations are returned.- Raises
HTTPException – Retrieving the listings failed.
- Returns
The store listings.
- Return type
List[
StoreListing]
- property store_listing_sku_url¶
The URL to the store listing SKU of the application, if any.
- Type
- await ticket()¶
This function is a coroutine.
Retrieves the license ticket for this application.
- Raises
HTTPException – Retrieving the ticket failed.
- Returns
The ticket retrieved.
- Return type
- aliases
- cover_image
- custom_install_url
- description
- developers
- embedded_activity_config
- eula_id
- executables
- flags
- guild
- guild_id
- icon
- id
- install_params
- install_url
- max_participants
- name
- overlay
- owner
- primary_sku_id
- primary_sku_url
- privacy_policy_url
- public
- publishers
- require_code_grant
- rpc_origins
- slug
- store_listing_sku_id
- store_listing_sku_url
- tags
- team
- terms_of_service_url
- third_party_skus
- type
- verify_key
- asyncachievements
- asyncactivity_statistics
- asyncassets
- asyncentitlement_ticket
- asyncentitlements
- asynceula
- asyncprimary_store_listing
- asyncpublished_store_listings
- asyncticket
- class discord.PartialApplication¶
Represents a partial Application.
- x == y
Checks if two applications are equal.
- x != y
Checks if two applications are not equal.
- hash(x)
Return the application’s hash.
- str(x)
Returns the application’s name.
New in version 2.0.
- verify_key¶
The hex encoded key for verification in interactions and the GameSDK’s https://discord.com/developers/docs/GetTicket <game-sdk/applications#getticket.
- Type
- public¶
Whether the integration can be invited by anyone or if it is locked to the application owner.
- Type
- require_code_grant¶
Whether the integration requires the completion of the full OAuth2 code grant flow to join
- Type
- max_participants¶
The max number of people that can participate in the activity. Only available for embedded activities.
- Type
Optional[
int]
- type¶
The type of application.
- Type
Optional[
ApplicationType]
- primary_sku_id¶
The application’s primary SKU ID, if any. This can be an application’s game SKU, subscription SKU, etc.
- Type
Optional[
int]
- store_listing_sku_id¶
The application’s store listing SKU ID, if any. If exists, this SKU ID should be used for checks.
- Type
Optional[
int]
- executables¶
A list of executables that are the application’s.
- Type
List[
ApplicationExecutable]
- third_party_skus¶
A list of third party platforms the SKU is available at.
- Type
List[
ThirdPartySKU]
- custom_install_url¶
The custom URL to use for authorizing the application, if specified.
- Type
Optional[
str]
- install_params¶
The parameters to use for authorizing the application, if specified.
- Type
Optional[
ApplicationInstallParams]
- embedded_activity_config¶
The application’s embedded activity configuration, if any.
- Type
Optional[
EmbeddedActivityConfig]
- owner¶
The application owner. This may be a team user account.
Note
In almost all cases, this is not available for partial applications.
- Type
Optional[
User]
- team¶
The team that owns the application.
Note
In almost all cases, this is not available.
- Type
Optional[
Team]
- property flags¶
The flags of this application.
- Type
- property store_listing_sku_url¶
The URL to the store listing SKU of the application, if any.
- Type
- await assets()¶
This function is a coroutine.
Retrieves the assets of this application.
- Raises
HTTPException – Retrieving the assets failed.
- Returns
The application’s assets.
- Return type
List[
ApplicationAsset]
- await published_store_listings(*, localize=True)¶
This function is a coroutine.
Retrieves all published store listings for this application.
- Parameters
localize (
bool) – Whether to localize the store listings to the current user’s locale. IfFalsethen all localizations are returned.- Raises
HTTPException – Retrieving the listings failed.
- Returns
The store listings.
- Return type
List[
StoreListing]
- await primary_store_listing(*, localize=True)¶
This function is a coroutine.
Retrieves the primary store listing of this application.
This is the public store listing of the primary SKU.
- Parameters
localize (
bool) – Whether to localize the store listing to the current user’s locale. IfFalsethen all localizations are returned.- Raises
NotFound – The application does not have a primary SKU.
HTTPException – Retrieving the store listing failed.
- Returns
The application’s primary store listing, if any.
- Return type
- await achievements(completed=True)¶
This function is a coroutine.
Retrieves the achievements for this application.
- Parameters
completed (
bool) –Whether to only include achievements the user has completed or can access. This means secret achievements that are not yet unlocked will not be included.
If
False, then you require access to the application.- Raises
Forbidden – You do not have permissions to fetch achievements.
HTTPException – Fetching the achievements failed.
- Returns
The achievements retrieved.
- Return type
List[
Achievement]
- await entitlements(*, exclude_consumed=True)¶
This function is a coroutine.
Retrieves the entitlements this account has granted for this application.
- Parameters
exclude_consumed (
bool) – Whether to exclude consumed entitlements.- Raises
HTTPException – Fetching the entitlements failed.
- Returns
The entitlements retrieved.
- Return type
List[
Entitlement]
- await eula()¶
This function is a coroutine.
Retrieves the EULA for this application.
- Raises
HTTPException – Retrieving the EULA failed.
- Returns
The EULA retrieved, if any.
- Return type
Optional[
EULA]
- await ticket()¶
This function is a coroutine.
Retrieves the license ticket for this application.
- Raises
HTTPException – Retrieving the ticket failed.
- Returns
The ticket retrieved.
- Return type
- await entitlement_ticket()¶
This function is a coroutine.
Retrieves the entitlement ticket for this application.
- Raises
HTTPException – Retrieving the ticket failed.
- Returns
The ticket retrieved.
- Return type
- await activity_statistics()¶
This function is a coroutine.
Retrieves the activity usage statistics for this application.
- Raises
HTTPException – Retrieving the statistics failed.
- Returns
The statistics retrieved.
- Return type
- class discord.ApplicationProfile¶
Represents a Discord application profile.
- x == y
Checks if two applications are equal.
- x != y
Checks if two applications are not equal.
- hash(x)
Return the applications’s hash.
New in version 2.0.
- popular_application_command_ids¶
A list of the IDs of the application’s popular commands.
- Type
List[
int]
- primary_sku_id¶
The application’s primary SKU ID, if any. This can be an application’s game SKU, subscription SKU, etc.
- Type
Optional[
int]
- custom_install_url¶
The custom URL to use for authorizing the application, if specified.
- Type
Optional[
str]
- install_params¶
The parameters to use for authorizing the application, if specified.
- Type
Optional[
ApplicationInstallParams]
- property flags¶
The flags of this application.
- Type
- asyncack
- asyncack_pins
- asyncblock
- asyncconnect
- asynccreate_dm
- asyncedit
- asyncfetch_message
- asyncgreet
- async forhistory
- defis_blocked
- defis_friend
- defmentioned_in
- asyncpins
- asyncprofile
- asyncremove_friend
- asyncsend
- asyncsend_friend_request
- defslash_commands
- asynctoken
- deftyping
- asyncunblock
- defuser_commands
- class discord.ApplicationBot¶
Represents a bot attached to an application.
- x == y
Checks if two bots are equal.
- x != y
Checks if two bots are not equal.
- hash(x)
Return the bot’s hash.
- str(x)
Returns the bot’s name with discriminator.
New in version 2.0.
- application¶
The application that the bot is attached to.
- Type
- public¶
Whether the bot can be invited by anyone or if it is locked to the application owner.
- Type
- require_code_grant¶
Whether the bot requires the completion of the full OAuth2 code grant flow to join.
- Type
- property mfa_enabled¶
Whether the bot has MFA turned on and working. This follows the bot owner’s value.
- Type
- property verified¶
Whether the bot’s email has been verified. This follows the bot owner’s value.
- Type
- await edit(*, username=..., avatar=..., bio=..., public=..., require_code_grant=...)¶
This function is a coroutine.
Edits the bot.
All parameters are optional.
- Parameters
username (
str) – The new username you wish to change your bot to.avatar (Optional[
bytes]) – A bytes-like object representing the image to upload. Could beNoneto denote no avatar.bio (Optional[
str]) – Your bot’s ‘about me’ section. This is just the application description. Could beNoneto represent no ‘about me’.public (
bool) – Whether the bot is public or not.require_code_grant (
bool) – Whether the bot requires a code grant or not.
- Raises
Forbidden – You are not allowed to edit this bot.
HTTPException – Editing the bot failed.
- await token()¶
This function is a coroutine.
Gets the bot’s token.
This revokes all previous tokens.
- Raises
Forbidden – You are not allowed to reset the token.
HTTPException – Resetting the token failed.
- Returns
The new token.
- Return 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]
- await ack()¶
This function is a coroutine.
Marks every message in this channel as read.
- Raises
HTTPException – Acking the channel failed.
- await ack_pins()¶
This function is a coroutine.
Marks a channel’s pins as viewed.
- Raises
HTTPException – Acking the pinned messages failed.
- property avatar¶
Returns an
Assetfor the avatar the user has.If the user has not uploaded a global avatar,
Noneis returned. If you want the avatar that a user has displayed, considerdisplay_avatar.- Type
Optional[
Asset]
- property avatar_decoration¶
Returns an
Assetfor the avatar decoration the user has.If the user does not have a avatar decoration,
Noneis returned.New in version 2.0.
- Type
Optional[
Asset]
- 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]
- await block()¶
This function is a coroutine.
Blocks the user.
- Raises
Forbidden – Not allowed to block this user.
HTTPException – Blocking the user failed.
- property call¶
Returns the call associated with this user if it exists.
- Type
Optional[
PrivateCall]
- 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
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, _channel=None, self_deaf=False, self_mute=False)¶
This function is a coroutine.
Connects to voice and creates a
VoiceClientto establish your connection to the voice server.- Parameters
timeout (
float) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (Type[
VoiceProtocol]) – A type that subclassesVoiceProtocolto connect with. Defaults toVoiceClient.self_mute (
bool) –Indicates if the client should be self-muted.
New in version 2.0.
self_deaf (
bool) –Indicates if the client should be self-deafened.
New in version 2.0.
- Raises
asyncio.TimeoutError – Could not connect to the voice channel in time.
ClientException – You are already connected to a voice channel.
OpusNotLoaded – The opus library has not been loaded.
- Returns
A voice client that is fully connected to the voice server.
- Return type
- await create_dm()¶
This function is a coroutine.
Creates a
DMChannelwith this user.This should be rarely called, as this is done transparently for most people.
- Returns
The channel that was created.
- Return type
- property created_at¶
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
- Type
- property default_avatar¶
Returns the default avatar for a given user. This is calculated by the user’s discriminator.
- 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_banner¶
Returns the user’s banner asset, if available.
This is the same as
bannerand is here for compatibility.New in version 2.0.
- Type
Optional[
Asset]
- property display_name¶
Returns the user’s display name.
For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
- Type
- property dm_channel¶
Returns the channel associated with this user if it exists.
If this returns
None, you can create a DM channel by calling thecreate_dm()coroutine function.- Type
Optional[
DMChannel]
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters
id (
int) – The message ID to look for.- 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.
- Returns
The message asked for.
- Return type
- await greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...)¶
This function is a coroutine.
Sends a sticker greeting to the destination.
A sticker greeting is used to begin a new DM or reply to a system message.
New in version 2.0.
- Parameters
sticker (Union[
GuildSticker,StickerItem]) – The sticker to greet with.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead. In the case of greeting, onlyreplied_useris considered.reference (Union[
Message,MessageReference,PartialMessage]) – A reference to theMessageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.mention_author (
bool) – If set, overrides thereplied_userattribute ofallowed_mentions.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
TypeError – The
referenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The sticker greeting that was sent.
- Return type
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an asynchronous iterator that enables receiving the destination’s message history.
You must have
read_message_historyto do this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in channel.history(limit=123)] # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. 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 messages after this date or message. 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.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields
Message– The message with the message data parsed.
- mentioned_in(message)¶
Checks if the user is mentioned in the specified message.
- note¶
Returns an object representing the user’s note.
New in version 2.0.
Note
The underlying note is cached and updated from gateway events.
- Type
- await pins()¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises
Forbidden – You do not have the permission to retrieve pinned messages.
HTTPException – Retrieving the pinned messages failed.
- Returns
The messages that are currently pinned.
- Return type
List[
Message]
- await profile(*, with_mutual_guilds=True, with_mutual_friends_count=False, with_mutual_friends=True)¶
This function is a coroutine.
A shorthand method to retrieve a
UserProfilefor the user.- Parameters
with_mutual_guilds (
bool) –Whether to fetch mutual guilds. This fills in
UserProfile.mutual_guilds.New in version 2.0.
with_mutual_friends_count (
bool) –Whether to fetch the number of mutual friends. This fills in
UserProfile.mutual_friends_count.New in version 2.0.
with_mutual_friends (
bool) –Whether to fetch mutual friends. This fills in
UserProfile.mutual_friendsandUserProfile.mutual_friends_count, but requires an extra API call.New in version 2.0.
- Raises
Forbidden – Not allowed to fetch this profile.
HTTPException – Fetching the profile failed.
- Returns
The profile of the user.
- Return type
- property public_flags¶
The publicly available flags the user has.
- Type
- property relationship¶
Returns the
Relationshipwith this user if applicable,Noneotherwise.- Type
Optional[
Relationship]
- await remove_friend()¶
This function is a coroutine.
Removes the user as a friend.
- Raises
Forbidden – Not allowed to remove this user as a friend.
HTTPException – Removing the user as a friend failed.
- await send(content=None, *, tts=False, file=None, files=None, stickers=None, delete_after=None, nonce=..., allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, silent=False)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then a sticker or file must be sent.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (
int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. Generates one by default.delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.New in version 1.6.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
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.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate size.TypeError – You specified both
fileandfiles, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The message that was sent.
- Return type
- await send_friend_request()¶
This function is a coroutine.
Sends the user a friend request.
- Raises
Forbidden – Not allowed to send a friend request to the user.
HTTPException – Sending the friend request failed.
- slash_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the slash commands available in the channel.
Examples
Usage
async for command in channel.slash_commands(): print(command.name)
Flattening into a list
commands = [command async for command in channel.slash_commands()] # commands is now a list of SlashCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
SlashCommand– A slash command.
- typing()¶
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using
await.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!')
Example Usage:
await channel.typing() # Do some computational magic for about 10 seconds await channel.send('Done!')
Changed in version 2.0: This no longer works with the
withsyntax,async withmust be used instead.Changed in version 2.0: Added functionality to
awaitthe context manager to send a typing indicator for 10 seconds.
- await unblock()¶
This function is a coroutine.
Unblocks the user.
- Raises
Forbidden – Not allowed to unblock this user.
HTTPException – Unblocking the user failed.
- user_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the user commands available to use on the user.
Examples
Usage
async for command in user.user_commands(): print(command.name)
Flattening into a list
commands = [command async for command in user.user_commands()] # commands is now a list of UserCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
UserCommand– A user command.
- property voice¶
Returns the user’s current voice state.
- Type
Optional[
VoiceState]
- class discord.ApplicationExecutable¶
Represents an application executable.
- str(x)
Returns the executable’s name.
New in version 2.0.
- application¶
The application that the executable is for.
- Type
- class discord.ApplicationInstallParams¶
Represents an application’s authorization parameters.
- str(x)
Returns the authorization URL.
New in version 2.0.
- scopes¶
The list of OAuth2 scopes to add the application with.
- Type
List[
str]
- permissions¶
The permissions to grant to the added bot.
- Type
- class discord.ApplicationAsset¶
Represents an application asset.
- x == y
Checks if two assets are equal.
- x != y
Checks if two assets are not equal.
- hash(x)
Return the asset’s hash.
- str(x)
Returns the asset’s name.
New in version 2.0.
- application¶
The application that the asset is for.
- Type
- await delete()¶
This function is a coroutine.
Deletes the asset.
- Raises
Forbidden – You are not allowed to delete this asset.
HTTPException – Deleting the asset failed.
- asyncapplication
- class discord.ApplicationActivityStatistics¶
Represents an application’s activity usage statistics for a particular user.
New in version 2.0.
- updated_at¶
When the user last played the game.
- Type
- await application()¶
This function is a coroutine.
Returns the application associated with the statistics.
- Raises
HTTPException – Fetching the application failed.
- asyncremove
- class discord.ApplicationTester¶
Represents a user whitelisted for an application.
- x == y
Checks if two testers are equal.
- x != y
Checks if two testers are not equal.
- hash(x)
Return the tester’s hash.
- str(x)
Returns the tester’s name with discriminator.
New in version 2.0.
- application¶
The application the tester is whitelisted for.
- Type
- state¶
The state of the tester (i.e. invited or accepted)
- await remove()¶
This function is a coroutine.
Removes the user from the whitelist.
- Raises
HTTPException – Removing the user failed.
- asyncedit
- class discord.EmbeddedActivityConfig¶
Represents an application’s embedded activity configuration.
New in version 2.0.
- application¶
The application that the configuration is for.
- Type
- supported_platforms¶
A list of platforms that the activity supports.
- Type
List[
EmbeddedActivityPlatform]
- orientation_lock_state¶
The mobile orientation lock state of the activity.
- tablet_orientation_lock_state¶
The mobile orientation lock state of the activity on tablets.
The guild premium tier required to use the activity.
- Type
- free_period_starts_at¶
When the activity’s free availability period starts.
- Type
Optional[
datetime.datetime]
- free_period_ends_at¶
When the activity’s free availability period ends.
- Type
Optional[
datetime.datetime]
- property preview_video_asset¶
The preview video asset of the activity, if available.
- Type
Optional[
ApplicationAsset]
- await edit(*, supported_platforms=..., orientation_lock_state=..., tablet_orientation_lock_state=..., requires_age_gate=..., shelf_rank=..., free_period_starts_at=..., free_period_ends_at=..., preview_video_asset=...)¶
This function is a coroutine.
Edits the application’s embedded activity configuration.
- Parameters
supported_platforms (List[
EmbeddedActivityPlatform]) – A list of platforms that the activity supports.orientation_lock_state (
EmbeddedActivityOrientation) – The mobile orientation lock state of the activity.tablet_orientation_lock_state (
EmbeddedActivityOrientation) – The mobile orientation lock state of the activity on tablets.requires_age_gate (
bool) – Whether the activity should be blocked from underage users.shelf_rank (
int) – The sorting rank of the activity in the activity shelf.free_period_starts_at (Optional[
datetime.datetime]) – When the activity’s free availability period starts.free_period_ends_at (Optional[
datetime.datetime]) – When the activity’s free availability period ends.preview_video_asset (Optional[
ApplicationAsset]) – The preview video asset of the activity.
- Raises
Forbidden – You are not allowed to edit this application’s configuration.
HTTPException – Editing the configuration failed.
ApplicationBranch¶
- asyncbuilds
- asynccreate_build
- asyncdelete
- asyncfetch_build
- asyncfetch_live_build_id
- defis_master
- asynclatest_build
- asynclive_build
- asyncpromote
- class discord.ApplicationBranch¶
Represents an application branch.
- x == y
Checks if two branches are equal.
- x != y
Checks if two branches are not equal.
- hash(x)
Return the branch’s hash.
- str(x)
Returns the branch’s name.
New in version 2.0.
- property created_at¶
Returns the branch’s creation time in UTC.
Note
This may be innacurate for the master branch if the data is not provided, as the ID is shared with the application ID.
- Type
- await builds()¶
This function is a coroutine.
Retrieves the builds of the branch.
- Raises
Forbidden – You are not allowed to manage this application.
HTTPException – Fetching the builds failed.
- await fetch_build(build_id, /)¶
This function is a coroutine.
Retrieves a build of the branch with the given ID.
- Parameters
build_id (
int) – The ID of the build to fetch.- Raises
NotFound – The build does not exist.
Forbidden – You are not allowed to manage this application.
HTTPException – Fetching the build failed.
- await fetch_live_build_id()¶
This function is a coroutine.
Retrieves and caches the ID of the live build of the branch.
- Raises
HTTPException – Fetching the build failed.
- Returns
The ID of the live build, if it exists.
- Return type
Optional[
int]
- await live_build(*, locale=..., platform)¶
This function is a coroutine.
Retrieves the live build of the branch.
- Parameters
- Raises
NotFound – The branch does not have a live build.
HTTPException – Fetching the build failed.
- await latest_build()¶
This function is a coroutine.
Retrieves the latest successful build of the branch.
- Raises
NotFound – The branch does not have a successful build.
Forbidden – You are not allowed to manage this application.
HTTPException – Fetching the build failed.
- await create_build(*, built_with='DISPATCH', manifests, source_build=None)¶
This function is a coroutine.
Creates a build for the branch.
- Parameters
manifests (List[
Metadata]) – A list of dict-like objects representing the manifests.source_build (Optional[
ApplicationBuild]) – The source build of the build, if any.
- Raises
Forbidden – You are not allowed to manage this application.
HTTPException – Creating the build failed.
- Returns
The created build and manifest uploads.
- Return type
Tuple[
ApplicationBuild, List[Manifest]]
- await promote(branch, /)¶
This function is a coroutine.
Promotes this branch’s live build to the given branch.
- Parameters
branch (
ApplicationBranch) – The target branch to promote the build to.- Raises
Forbidden – You are not allowed to manage this application.
HTTPException – Promoting the branch failed.
- await delete()¶
This function is a coroutine.
Deletes the branch.
- Raises
Forbidden – You are not allowed to manage this application.
HTTPException – Deleting the branch failed.
- asyncdelete
- asyncdownload_urls
- asyncedit
- asyncpublish
- asyncsize
- asyncupload_files
- class discord.ApplicationBuild¶
Represents a build of an
ApplicationBranch.- x == y
Checks if two builds are equal.
- x != y
Checks if two builds are not equal.
- hash(x)
Return the build’s hash.
New in version 2.0.
- branch¶
The branch the build belongs to.
- Type
- created_at¶
When the build was created.
- Type
- status¶
The status of the build.
- await size(manifests=...)¶
This function is a coroutine.
Retrieves the storage space used by the build.
- Parameters
manifests (List[
Manifest]) – The manifests to fetch the storage space for. Defaults to all the build’s manifests.- Raises
HTTPException – Fetching the storage space failed.
- Returns
The storage space used by the build in kilobytes.
- Return type
- await download_urls(manifest_labels=...)¶
This function is a coroutine.
Retrieves the download URLs of the build.
These download URLs are for the manifest metadata, which can be used to download the artifacts.
Note
The download URLs are signed and valid for roughly 7 days.
- Parameters
manifest_labels (List[
ManifestLabel]) – The manifest labels to fetch the download URLs for. Defaults to all the build’s manifest labels.- Raises
NotFound – The build was not found or you are not entitled to it.
Forbidden – You are not allowed to manage this application.
HTTPException – Fetching the download URLs failed.
- Returns
The download URLs of the build.
- Return type
List[
str]
- await edit(status)¶
This function is a coroutine.
Edits the build.
- Parameters
status (
ApplicationBuildStatus) – The new status of the build.- Raises
Forbidden – You are not allowed to manage this application.
HTTPException – Editing the build failed.
- await upload_files(*files, hash=True)¶
This function is a coroutine.
Uploads files to the build.
Note
This should only be used for builds with a status of
ApplicationBuildStatus.uploading.Warning
This does not account for chunking large files.
- Parameters
*files (
discord.File) – The files to upload.hash (
bool) – Whether to calculate the MD5 hash of the files before upload.
- Raises
Forbidden – You are not allowed to manage this application.
HTTPException – Uploading the files failed.
- await publish()¶
This function is a coroutine.
Publishes the build.
This can only be done on builds with an
statusofApplicationBuildStatus.ready.- Raises
Forbidden – You are not allowed to manage this application.
HTTPException – Publishing the build failed.
- await delete()¶
This function is a coroutine.
Deletes the build.
- Raises
Forbidden – You are not allowed to manage this application.
HTTPException – Deleting the build failed.
- class discord.ManifestLabel¶
Represents an application manifest label.
- x == y
Checks if two manifest labels are equal.
- x != y
Checks if two manifest labels are not equal.
- hash(x)
Return the manifest label’s hash.
- str(x)
Returns the manifest label’s name.
New in version 2.0.
- asyncupload
- class discord.Manifest¶
Represents an application manifest.
- x == y
Checks if two manifests are equal.
- x != y
Checks if two manifests are not equal.
- hash(x)
Return the manifest’s hash.
New in version 2.0.
- label¶
The manifest’s label, if available.
- Type
Optional[
ManifestLabel]
- redistributable_label_ids¶
The label IDs of the manifest’s redistributables, if available.
- Type
List[
int]
- await upload(manifest, /)¶
This function is a coroutine.
Uploads the manifest object to the manifest.
Note
This should only be used for builds with a status of
ApplicationBuildStatus.uploading.Additionally, it requires that
urlis set to the uploadable URL (populated on uploadable manifest objects returned fromApplicationBranch.create_build()).- Parameters
manifest (
Metadata) – A dict-like object representing the manifest to upload.- Raises
ValueError – Upload URL is not set.
Forbidden – Upload URL invalid.
HTTPException – Uploading the manifest failed.
Team¶
- asyncapplications
- asynccreate_company
- asyncdelete
- asyncedit
- asyncfetch_members
- asyncinvite_member
- asyncleave
- async forpayouts
- class discord.Team¶
Represents an application team.
- x == y
Checks if two teams are equal.
- x != y
Checks if two teams are not equal.
- hash(x)
Return the team’s hash.
- str(x)
Returns the team’s name.
New in version 2.0.
- members¶
The team’s members.
Note
In almost all cases, a call to
fetch_members()is required to populate this list past (sometimes) the owner.- Type
List[
TeamMember]
- payout_account_status¶
The team’s payout account status, if any and available.
- Type
Optional[
PayoutAccountStatus]
- stripe_connect_account_id¶
The account ID representing the Stripe Connect account the team’s payout account is linked to, if any and available.
- Type
Optional[
str]
- property default_icon¶
Returns the default icon for the team. This is calculated by the team’s ID.
- Type
- property display_icon¶
Returns the team’s display icon.
For regular teams this is just their default icon or uploaded icon.
- Type
- property owner¶
The team’s owner, if available.
- Type
Optional[
TeamMember]
- await edit(*, name=..., icon=..., owner=...)¶
This function is a coroutine.
Edits the team.
All parameters are optional.
- Parameters
- Raises
Forbidden – You do not have permissions to edit the team.
HTTPException – Editing the team failed.
- await applications()¶
This function is a coroutine.
Retrieves the team’s applications.
- Returns
The team’s applications.
- Return type
List[
TeamMember]- Raises
Forbidden – You do not have permissions to fetch the team’s applications.
HTTPException – Retrieving the team applications failed.
- await fetch_members()¶
This function is a coroutine.
Retrieves and caches the team’s members.
- Returns
The team’s members.
- Return type
List[
TeamMember]- Raises
Forbidden – You do not have permissions to fetch the team’s members.
HTTPException – Retrieving the team members failed.
- await invite_member(*args)¶
This function is a coroutine.
Invites a member to the team.
This function can be used in multiple ways.
# Passing a user object: await team.invite_member(user) # Passing a stringified user: await team.invite_member('Jake#0001') # Passing a username and discriminator: await team.invite_member('Jake', '0001')
- Parameters
- Raises
Forbidden – You do not have permissions to invite the user.
HTTPException – Inviting the user failed.
TypeError – More than 2 parameters or less than 1 parameter were passed.
- Returns
The new member.
- Return type
- await create_company(name, /)¶
This function is a coroutine.
Creates a company for the team.
- Parameters
name (
str) – The name of the company.- Raises
Forbidden – You do not have permissions to create a company.
HTTPException – Creating the company failed.
- Returns
The created company.
- Return type
- async for ... in payouts(*, limit=96, before=None)¶
Returns an asynchronous iterator that enables receiving your team payouts.
New in version 2.0.
Examples
Usage
total = 0 async for payout in team.payouts(): if payout.period_end: total += payout.amount
Flattening into a list:
payments = [payout async for payout in team.payouts(limit=123)] # payments is now a list of TeamPayout...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of payouts to retrieve. IfNone, retrieves every payout you have. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve payments before this date or payout. 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.
- Raises
HTTPException – The request to get team payouts failed.
- Yields
TeamPayout– The payout received.
- await leave()¶
This function is a coroutine.
Leaves the team.
Note
You cannot leave a team that you own, you must delete it instead via
delete().- Raises
Forbidden – You do not have permissions to leave the team.
HTTPException – Leaving the team failed.
- await delete()¶
This function is a coroutine.
Deletes the team.
- Raises
Forbidden – You do not have permissions to delete the team.
HTTPException – Deleting the team failed.
- asyncack
- asyncack_pins
- asyncblock
- asyncconnect
- asynccreate_dm
- asyncfetch_message
- asyncgreet
- async forhistory
- defis_blocked
- defis_friend
- defmentioned_in
- asyncpins
- asyncprofile
- asyncremove
- asyncremove_friend
- asyncsend
- asyncsend_friend_request
- defslash_commands
- deftyping
- asyncunblock
- defuser_commands
- 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 name with discriminator.
New in version 1.3.
- membership_state¶
The membership state of the member (i.e. invited or accepted)
- await remove()¶
This function is a coroutine.
Removes the member from the team.
- Raises
Forbidden – You do not have permissions to remove the member.
HTTPException – Removing the member failed.
- 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]
- await ack()¶
This function is a coroutine.
Marks every message in this channel as read.
- Raises
HTTPException – Acking the channel failed.
- await ack_pins()¶
This function is a coroutine.
Marks a channel’s pins as viewed.
- Raises
HTTPException – Acking the pinned messages failed.
- property avatar¶
Returns an
Assetfor the avatar the user has.If the user has not uploaded a global avatar,
Noneis returned. If you want the avatar that a user has displayed, considerdisplay_avatar.- Type
Optional[
Asset]
- property avatar_decoration¶
Returns an
Assetfor the avatar decoration the user has.If the user does not have a avatar decoration,
Noneis returned.New in version 2.0.
- Type
Optional[
Asset]
- 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]
- await block()¶
This function is a coroutine.
Blocks the user.
- Raises
Forbidden – Not allowed to block this user.
HTTPException – Blocking the user failed.
- property call¶
Returns the call associated with this user if it exists.
- Type
Optional[
PrivateCall]
- 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
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, _channel=None, self_deaf=False, self_mute=False)¶
This function is a coroutine.
Connects to voice and creates a
VoiceClientto establish your connection to the voice server.- Parameters
timeout (
float) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (Type[
VoiceProtocol]) – A type that subclassesVoiceProtocolto connect with. Defaults toVoiceClient.self_mute (
bool) –Indicates if the client should be self-muted.
New in version 2.0.
self_deaf (
bool) –Indicates if the client should be self-deafened.
New in version 2.0.
- Raises
asyncio.TimeoutError – Could not connect to the voice channel in time.
ClientException – You are already connected to a voice channel.
OpusNotLoaded – The opus library has not been loaded.
- Returns
A voice client that is fully connected to the voice server.
- Return type
- await create_dm()¶
This function is a coroutine.
Creates a
DMChannelwith this user.This should be rarely called, as this is done transparently for most people.
- Returns
The channel that was created.
- Return type
- property created_at¶
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
- Type
- property default_avatar¶
Returns the default avatar for a given user. This is calculated by the user’s discriminator.
- 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_banner¶
Returns the user’s banner asset, if available.
This is the same as
bannerand is here for compatibility.New in version 2.0.
- Type
Optional[
Asset]
- property display_name¶
Returns the user’s display name.
For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
- Type
- property dm_channel¶
Returns the channel associated with this user if it exists.
If this returns
None, you can create a DM channel by calling thecreate_dm()coroutine function.- Type
Optional[
DMChannel]
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters
id (
int) – The message ID to look for.- 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.
- Returns
The message asked for.
- Return type
- await greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...)¶
This function is a coroutine.
Sends a sticker greeting to the destination.
A sticker greeting is used to begin a new DM or reply to a system message.
New in version 2.0.
- Parameters
sticker (Union[
GuildSticker,StickerItem]) – The sticker to greet with.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead. In the case of greeting, onlyreplied_useris considered.reference (Union[
Message,MessageReference,PartialMessage]) – A reference to theMessageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.mention_author (
bool) – If set, overrides thereplied_userattribute ofallowed_mentions.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
TypeError – The
referenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The sticker greeting that was sent.
- Return type
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an asynchronous iterator that enables receiving the destination’s message history.
You must have
read_message_historyto do this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in channel.history(limit=123)] # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. 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 messages after this date or message. 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.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields
Message– The message with the message data parsed.
- mentioned_in(message)¶
Checks if the user is mentioned in the specified message.
- note¶
Returns an object representing the user’s note.
New in version 2.0.
Note
The underlying note is cached and updated from gateway events.
- Type
- await pins()¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises
Forbidden – You do not have the permission to retrieve pinned messages.
HTTPException – Retrieving the pinned messages failed.
- Returns
The messages that are currently pinned.
- Return type
List[
Message]
- await profile(*, with_mutual_guilds=True, with_mutual_friends_count=False, with_mutual_friends=True)¶
This function is a coroutine.
A shorthand method to retrieve a
UserProfilefor the user.- Parameters
with_mutual_guilds (
bool) –Whether to fetch mutual guilds. This fills in
UserProfile.mutual_guilds.New in version 2.0.
with_mutual_friends_count (
bool) –Whether to fetch the number of mutual friends. This fills in
UserProfile.mutual_friends_count.New in version 2.0.
with_mutual_friends (
bool) –Whether to fetch mutual friends. This fills in
UserProfile.mutual_friendsandUserProfile.mutual_friends_count, but requires an extra API call.New in version 2.0.
- Raises
Forbidden – Not allowed to fetch this profile.
HTTPException – Fetching the profile failed.
- Returns
The profile of the user.
- Return type
- property public_flags¶
The publicly available flags the user has.
- Type
- property relationship¶
Returns the
Relationshipwith this user if applicable,Noneotherwise.- Type
Optional[
Relationship]
- await remove_friend()¶
This function is a coroutine.
Removes the user as a friend.
- Raises
Forbidden – Not allowed to remove this user as a friend.
HTTPException – Removing the user as a friend failed.
- await send(content=None, *, tts=False, file=None, files=None, stickers=None, delete_after=None, nonce=..., allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, silent=False)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then a sticker or file must be sent.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (
int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. Generates one by default.delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.New in version 1.6.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
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.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate size.TypeError – You specified both
fileandfiles, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The message that was sent.
- Return type
- await send_friend_request()¶
This function is a coroutine.
Sends the user a friend request.
- Raises
Forbidden – Not allowed to send a friend request to the user.
HTTPException – Sending the friend request failed.
- slash_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the slash commands available in the channel.
Examples
Usage
async for command in channel.slash_commands(): print(command.name)
Flattening into a list
commands = [command async for command in channel.slash_commands()] # commands is now a list of SlashCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
SlashCommand– A slash command.
- typing()¶
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using
await.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!')
Example Usage:
await channel.typing() # Do some computational magic for about 10 seconds await channel.send('Done!')
Changed in version 2.0: This no longer works with the
withsyntax,async withmust be used instead.Changed in version 2.0: Added functionality to
awaitthe context manager to send a typing indicator for 10 seconds.
- await unblock()¶
This function is a coroutine.
Unblocks the user.
- Raises
Forbidden – Not allowed to unblock this user.
HTTPException – Unblocking the user failed.
- user_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the user commands available to use on the user.
Examples
Usage
async for command in user.user_commands(): print(command.name)
Flattening into a list
commands = [command async for command in user.user_commands()] # commands is now a list of UserCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
UserCommand– A user command.
- property voice¶
Returns the user’s current voice state.
- Type
Optional[
VoiceState]
- asyncreport
- class discord.TeamPayout¶
Represents a team payout.
- x == y
Checks if two team payouts are equal.
- x != y
Checks if two team payouts are not equal.
- hash(x)
Return the team payout’s hash.
New in version 2.0.
- status¶
The status of the payout.
- Type
- period_start¶
The start of the payout period.
- Type
- period_end¶
The end of the payout period, if ended.
- Type
Optional[
datetime.date]
- payout_date¶
The date the payout was made, if made.
- Type
Optional[
datetime.date]
- await report(type)¶
This function is a coroutine.
Returns the report for the payout in CSV format.
- Parameters
type (
PayoutReportType) – The type of report to get the URL for.- Raises
Forbidden – You do not have permissions to get the report URL.
HTTPException – Getting the report URL failed.
- Returns
The report content.
- Return type
- class discord.Company¶
Represents a Discord company. This is usually the developer or publisher of an application.
- x == y
Checks if two companies are equal.
- x != y
Checks if two companies are not equal.
- hash(x)
Return the company’s hash.
- str(x)
Returns the company’s name.
New in version 2.0.
- class discord.EULA¶
Represents the EULA for an application.
This is usually found on applications that are a game.
- x == y
Checks if two EULAs are equal.
- x != y
Checks if two EULAs are not equal.
- hash(x)
Returns the EULA’s hash.
- str(x)
Returns the EULA’s name.
New in version 2.0.
Entitlement¶
- asyncconsume
- asyncdelete
- defis_active
- defis_giftable
- asyncsubscription
- class discord.Entitlement¶
Represents a Discord entitlement.
- x == y
Checks if two entitlements are equal.
- x != y
Checks if two entitlements are not equal.
- hash(x)
Returns the entitlement’s hash.
- bool(x)
Checks if the entitlement is active.
New in version 2.0.
- type¶
The type of entitlement.
- Type
- gift_batch_id¶
The ID of the batch the gift attached to this entitlement is from.
- Type
Optional[
int]
- starts_at¶
When the entitlement period starts.
- Type
Optional[
datetime.datetime]
- ends_at¶
When the entitlement period ends.
- Type
Optional[
datetime.datetime]
- subscription_plan¶
The subscription plan the entitlement is for.
Note
This is a partial object without price information.
- Type
Optional[
SubscriptionPlan]
- payment¶
The payment made for the entitlement. Not available in some contexts.
- Type
Optional[
EntitlementPayment]
The premium type this entitlement grants, if it is for a premium subscription.
- Type
Optional[
PremiumType]
- await subscription()¶
This function is a coroutine.
Retrieves the subscription this entitlement is attached to, if applicable.
- Raises
NotFound – You cannot access this subscription.
HTTPException – Fetching the subscription failed.
- Returns
The retrieved subscription, if applicable.
- Return type
Optional[
Subscription]
- await consume()¶
This function is a coroutine.
Consumes the entitlement. This marks a given user entitlement as expended, and removes the entitlement from the user’s active entitlements.
This should be called after the user has received the relevant item, and only works on entitlements for SKUs of type
SKUType.consumable.- Raises
Forbidden – You do not have permissions to access this application.
HTTPException – Consuming the entitlement failed.
- await delete()¶
This function is a coroutine.
Deletes the entitlement. This removes the entitlement from the user’s entitlements, and is irreversible.
This is only useable on entitlements of type
EntitlementType.test_mode_purchase.- Raises
Forbidden – You do not have permissions to access this application.
HTTPException – Deleting the entitlement failed.
- class discord.EntitlementPayment¶
Represents a partial payment for an entitlement.
- x == y
Checks if two payments are equal.
- x != y
Checks if two payments are not equal.
- hash(x)
Returns the payment’s hash.
New in version 2.0.
- entitlement¶
The entitlement the payment is for.
- Type
- asyncdelete
- defis_claimed
- defis_expired
- defis_premium_subscription
- defis_subscription
- asyncredeem
- class discord.Gift¶
Represents a Discord gift.
- x == y
Checks if two gifts are equal.
- x != y
Checks if two gifts are not equal.
- hash(x)
Returns the gift’s hash.
New in version 2.0.
- expires_at¶
When the gift expires.
- Type
Optional[
datetime.datetime]
- application_id¶
The ID of the application that owns the SKU the gift is for. Not available in all contexts.
- Type
Optional[
int]
- guild_id¶
The ID of the guild the gift was redeemed in. Not available in all contexts.
- Type
Optional[
int]
- channel_id¶
The ID of the channel the gift was redeemed in. Not available in all contexts.
- Type
Optional[
int]
- store_listing¶
The store listing for the SKU the gift is for. Not available in all contexts.
- Type
Optional[
StoreListing]
- subscription_trial¶
The subscription trial the gift is a part of, if any.
- Type
Optional[
SubscriptionTrial]
- subscription_plan¶
The subscription plan the gift is for, if any.
- Type
Optional[
SubscriptionPlan]
The premium type this gift grants, if it is for a premium subscription.
- Type
Optional[
PremiumType]
bool: Checks if the gift is for a premium subscription.
- await redeem(payment_source=None, *, channel=None, gateway_checkout_context=None)¶
This function is a coroutine.
Redeems the gift.
- Parameters
payment_source (Optional[
PaymentSource]) – The payment source to use for the redemption. Only required if the gift’sflagshaveGiftFlags.payment_source_requiredset toTrue.channel (Optional[Union[
TextChannel,VoiceChannel,StageChannel,Thread,DMChannel,GroupChannel]]) – The channel to redeem the gift in. This is usually the channel the gift was sent in. While this is optional, it is recommended to pass this in.gateway_checkout_context (Optional[
str]) – The current checkout context.
- Raises
HTTPException – The gift failed to redeem.
- Returns
The entitlement that was created from redeeming the gift.
- Return type
- await delete()¶
This function is a coroutine.
Revokes the gift.
This is only possible for gifts the current account has created.
- Raises
NotFound – The owned gift was not found.
HTTPException – The gift failed to delete.
- class discord.GiftBatch¶
Represents a batch of gifts for an SKU.
- x == y
Checks if two gift batches are equal.
- x != y
Checks if two gift batches are not equal.
- hash(x)
Returns the gift batch’s hash.
- str(x)
Returns the gift batch’s description.
New in version 2.0.
- entitlement_starts_at¶
When the entitlement is valid from.
- Type
Optional[
datetime.datetime]
- entitlement_ends_at¶
When the entitlement is valid until.
- Type
Optional[
datetime.datetime]
- await download()¶
This function is a coroutine.
Returns the gifts in the gift batch in CSV format.
- Raises
Forbidden – You do not have permissions to download the batch.
HTTPException – Downloading the batch failed.
- Returns
The report content.
- Return type
- class discord.Achievement¶
Represents a Discord application achievement.
- x == y
Checks if two achievements are equal.
- x != y
Checks if two achievements are not equal.
- hash(x)
Return the achievement’s hash.
- str(x)
Returns the achievement’s name.
New in version 2.0.
- name_localizations¶
The achievement’s name localized to other languages, if available.
- description_localizations¶
The achievement’s description localized to other languages, if available.
- await edit(*, name=..., name_localizations=..., description=..., description_localizations=..., icon=..., secure=..., secret=...)¶
This function is a coroutine.
Edits the achievement.
All parameters are optional.
- Parameters
name (
str) – The achievement’s name.name_localizations (Dict[
Locale,str]) – The achievement’s name localized to other languages.description (
str) – The achievement’s description.description_localizations (Dict[
Locale,str]) – The achievement’s description localized to other languages.icon (
bytes) – A bytes-like object representing the new icon.secure (
bool) – Whether the achievement is secure.secret (
bool) – Whether the achievement is secret.
- Raises
Forbidden – You do not have permissions to edit the achievement.
HTTPException – Editing the achievement failed.
- await update(user, percent_complete)¶
This function is a coroutine.
Updates the achievement progress for a specific user.
- Parameters
- Raises
Forbidden – You do not have permissions to update the achievement.
HTTPException – Updating the achievement failed.
- await delete()¶
This function is a coroutine.
Deletes the achievement.
- Raises
Forbidden – You do not have permissions to delete the achievement.
HTTPException – Deleting the achievement failed.
Library¶
- asyncactivity_statistics
- asyncdelete
- asyncedit
- asyncmark_installed
- class discord.LibraryApplication¶
Represents a library entry.
- x == y
Checks if two library entries are equal.
- x != y
Checks if two library entries are not equal.
- hash(x)
Returns the library entry’s hash.
- str(x)
Returns the library entry’s name.
New in version 2.0.
- created_at¶
When this library entry was created.
- Type
- application¶
The application that this library entry is for.
- Type
- sku¶
The SKU that this library entry is for.
- Type
- entitlements¶
The entitlements that this library entry has.
- Type
List[
Entitlement]
- branch¶
The branch that this library entry installs.
- Type
- property flags¶
The library entry’s flags.
- await activity_statistics()¶
This function is a coroutine.
Gets the activity statistics for this library entry.
- Raises
HTTPException – Getting the activity statistics failed.
- Returns
The activity statistics for this library entry.
- Return type
- await mark_installed()¶
This function is a coroutine.
Marks the library entry as installed.
- Raises
HTTPException – Marking the library entry as installed failed.
- await edit(*, flags=...)¶
This function is a coroutine.
Edits the library entry.
All parameters are optional.
- Parameters
flags (
LibraryApplicationFlags) – The new flags to set for the library entry.- Raises
HTTPException – Editing the library entry failed.
- await delete()¶
This function is a coroutine.
Deletes the library entry.
- Raises
HTTPException – Deleting the library entry failed.
- class discord.LibrarySKU¶
Represents a partial store SKU for a library entry.
- x == y
Checks if two library SKUs are equal.
- x != y
Checks if two library SKUs are not equal.
- hash(x)
Returns the library SKU’s hash.
New in version 2.0.
- preorder_release_date¶
The approximate date that the SKU will released for pre-order, if any.
- Type
Optional[
datetime.date]
- preorder_released_at¶
The date that the SKU was released for pre-order, if any.
- Type
Optional[
datetime.datetime]
Whether this SKU is provided for free to premium users.
- Type
Promotion¶
- asyncclaim
- defis_active
- defis_claimed
- class discord.Promotion¶
Represents a Discord promotion.
- x == y
Checks if two promotions are equal.
- x != y
Checks if two promotions are not equal.
- hash(x)
Returns the promotion’s hash.
- str(x)
Returns the outbound promotion’s name.
New in version 2.0.
- starts_at¶
When the promotion starts.
- Type
- ends_at¶
When the promotion ends.
- Type
- claimed_at¶
When the promotion was claimed. Only available for claimed promotions.
- Type
Optional[
datetime.datetime]
- outbound_restricted_countries¶
The countries that the outbound promotion is not available in.
- Type
List[
str]
- inbound_title¶
The title of the inbound promotion. This is usually Discord Nitro.
- Type
Optional[
str]
- inbound_restricted_countries¶
The countries that the inbound promotion is not available in.
- Type
List[
str]
- property flags¶
Returns the promotion’s flags.
- Type
- is_claimed()¶
bool: Checks if the promotion has been claimed.Only accurate if the promotion was fetched from
Client.promotions()withclaimedset toTrueorclaim()was just called.
- await claim()¶
This function is a coroutine.
Claims the promotion.
Sets
claimed_atandcode.- Raises
Forbidden – You are not allowed to claim the promotion.
HTTPException – Claiming the promotion failed.
- Returns
The claim code for the outbound promotion.
- Return type
- class discord.PricingPromotion¶
Represents a Discord localized pricing promotion.
New in version 2.0.
- payment_source_types¶
The payment source types the promotion is restricted to.
- Type
List[
PaymentSourceType]
- asyncack
- class discord.TrialOffer¶
Represents a Discord user trial offer.
- x == y
Checks if two trial offers are equal.
- x != y
Checks if two trial offers are not equal.
- hash(x)
Returns the trial offer’s hash.
New in version 2.0.
- expires_at¶
When the trial offer expires.
- Type
- trial¶
The trial offered.
- Type
- await ack()¶
This function is a coroutine.
Acknowledges the trial offer.
- Raises
HTTPException – Acknowledging the trial offer failed.
Subscription¶
- canceled_at
- cancelled_at
- created_at
- currency
- current_period_end
- current_period_start
- ended_at
- grace_period
- guild
- id
- items
- latest_invoice
- metadata
- payment_gateway
- payment_gateway_plan_id
- payment_gateway_subscription_id
- payment_source_id
- remaining
- renewal_mutations
- status
- streak_started_at
- trial_ends_at
- trial_id
- trial_remaining
- type
- asynccancel
- asyncdelete
- asyncedit
- asyncinvoices
- defis_active
- defis_trial
- asyncpayment_source
- asyncpreview_invoice
- class discord.Subscription¶
Represents a Discord subscription.
- x == y
Checks if two premium subscriptions are equal.
- x != y
Checks if two premium subscriptions are not equal.
- hash(x)
Returns the subscription’s hash.
- len(x)
Returns the number of items in the subscription, including quantity.
- bool(x)
Checks if the subscription is currently active and offering perks.
New in version 2.0.
- type¶
The type of the subscription.
- Type
- status¶
The status of the subscription. This is
Nonefor fake subscriptions.- Type
Optional[
SubscriptionStatus]
- payment_gateway¶
The payment gateway used to bill the subscription.
- Type
Optional[
PaymentGateway]
- items¶
The items in the subscription.
- Type
List[
SubscriptionItem]
- renewal_mutations¶
The mutations to the subscription that will occur after renewal.
- payment_source_id¶
The ID of the payment source the subscription is paid with, if applicable.
- Type
Optional[
int]
- payment_gateway_plan_id¶
The payment gateway’s plan ID for the subscription, if applicable.
- Type
Optional[
str]
- payment_gateway_subscription_id¶
The payment gateway’s subscription ID for the subscription, if applicable.
- Type
Optional[
str]
- created_at¶
When the subscription was created.
- Type
- canceled_at¶
When the subscription was canceled. This is only available for subscriptions with a
statusofSubscriptionStatus.canceled.- Type
Optional[
datetime.datetime]
- current_period_start¶
When the current billing period started.
- Type
- current_period_end¶
When the current billing period ends.
- Type
- trial_ends_at¶
When the trial ends, if applicable.
- Type
Optional[
datetime.datetime]
- streak_started_at¶
When the current subscription streak started.
- Type
Optional[
datetime.datetime]
- ended_at¶
When the subscription finally ended.
- Type
Optional[
datetime.datetime]
- latest_invoice¶
The latest invoice for the subscription, if applicable.
- Type
Optional[
SubscriptionInvoice]
- property cancelled_at¶
When the subscription was canceled. This is only available for subscriptions with a
statusofSubscriptionStatus.canceled.This is an alias of
canceled_at.- Type
Optional[
datetime.datetime]
- property grace_period¶
How many days past the renewal date the user has available to pay outstanding invoices.
Note
This is a static value and does not change based on the subscription’s status. For that, see
remaining.- Type
- property remaining¶
The remaining time until the subscription ends.
- Type
- property trial_remaining¶
The remaining time until the trial applied to the subscription ends.
- Type
- await edit(items=..., payment_source=..., currency=..., *, status=..., payment_source_token=None)¶
This function is a coroutine.
Edits the subscription.
All parameters are optional.
- Parameters
items (List[
SubscriptionItem]) – The new subscription items to use.payment_source (
int) – The new payment source for payment.currency (
str) – The new currency to use for payment.status (
SubscriptionStatus) – The new status of the subscription.payment_source_token (Optional[
str]) – The token used to authorize with the payment source.
- Raises
Forbidden – You do not have permissions to edit the subscription.
HTTPException – Editing the subscription failed.
- await delete()¶
This function is a coroutine.
Deletes the subscription.
There is an alias of this called
cancel().- Raises
HTTPException – Deleting the subscription failed.
- await cancel()¶
This function is a coroutine.
Deletes the subscription.
Alias of
delete().- Raises
HTTPException – Deleting the subscription failed.
- await preview_invoice(*, items=..., payment_source=..., currency=..., apply_entitlements=..., renewal=...)¶
This function is a coroutine.
Preview an invoice for the subscription with the given parameters.
All parameters are optional and default to the current subscription values.
- Parameters
items (List[
SubscriptionItem]) – The items the previewed invoice should have.payment_source (
PaymentSource) – The payment source the previewed invoice should be paid with.currency (
str) – The currency the previewed invoice should be paid in.apply_entitlements (
bool) – Whether to apply entitlements (credits) to the previewed invoice.renewal (
bool) – Whether the previewed invoice should be a renewal.
- Raises
HTTPException – Failed to preview the invoice.
- Returns
The previewed invoice.
- Return type
- await payment_source()¶
This function is a coroutine.
Retrieves the payment source the subscription is paid with, if applicable.
- Raises
NotFound – The payment source could not be found.
HTTPException – Retrieving the payment source failed.
- Returns
The payment source the subscription is paid with, if applicable.
- Return type
Optional[
PaymentSource]
- await invoices()¶
This function is a coroutine.
Retrieves all invoices for the subscription.
- Raises
NotFound – The payment source or invoices could not be found.
HTTPException – Retrieving the invoices failed.
- Returns
The invoices.
- Return type
List[
SubscriptionInvoice]
- class discord.SubscriptionItem¶
Represents a Discord subscription item.
- x == y
Checks if two subscription items are equal.
- x != y
Checks if two subscription items are not equal.
- hash(x)
Returns the item’s hash.
- len(x)
Returns the quantity of the subscription item.
New in version 2.0.
- class discord.SubscriptionDiscount¶
Represents a discount on a Discord subscription item.
- int(x)
Returns the discount’s amount.
New in version 2.0.
- type¶
The type of the discount.
- defis_discounted
- defis_preview
- asyncpay
- class discord.SubscriptionInvoice¶
Represents an invoice for a Discord subscription.
- x == y
Checks if two invoices are equal.
- x != y
Checks if two invoices are not equal.
- hash(x)
Returns the invoice’s hash.
New in version 2.0.
- subscription¶
The subscription the invoice is for. Not available for new subscription previews.
- Type
Optional[
Subscription]
- status¶
The status of the invoice. Not available for subscription previews.
- Type
Optional[
SubscriptionInvoiceStatus]
- items¶
The items in the invoice.
- Type
List[
SubscriptionInvoiceItem]
- current_period_start¶
When the current billing period started.
- Type
- current_period_end¶
When the current billing period ends.
- Type
- await pay(payment_source=None, currency='usd', *, payment_source_token=None, return_url=None)¶
This function is a coroutine.
Pays the invoice.
- Parameters
payment_source (Optional[
PaymentSource]) – The payment source the invoice should be paid with.currency (
str) – The currency to pay with.payment_source_token (Optional[
str]) – The token used to authorize with the payment source.return_url (Optional[
str]) – The URL to return to after the payment is complete.
- Raises
TypeError – The invoice is a preview and not real.
NotFound – The invoice is not open or found.
HTTPException – Paying the invoice failed.
- defis_discounted
- defis_trial
- class discord.SubscriptionInvoiceItem¶
Represents an invoice item.
- x == y
Checks if two invoice items are equal.
- x != y
Checks if two invoice items are not equal.
- hash(x)
Returns the invoice’s hash.
- len(x)
Returns the quantity of the invoice item.
New in version 2.0.
- plan_price¶
The price of the subscription plan the item represents. This does not include discounts.
- Type
- discounts¶
A list of discounts applied to the item.
- Type
List[
SubscriptionDiscount]
- defis_mutated
- class discord.SubscriptionRenewalMutations¶
Represents a subscription renewal mutation.
This represents changes to a subscription that will occur after renewal.
- len(x)
Returns the number of items in the changed subscription, including quantity.
- bool(x)
Returns whether any mutations are present.
New in version 2.0.
- payment_gateway_plan_id¶
The payment gateway’s new plan ID for the subscription. This signifies an external plan change.
- Type
Optional[
str]
- items¶
The new items of the subscription.
- Type
Optional[List[
SubscriptionItem]]
SubscriptionPlan¶
- asynccreate_gift
- asyncgifts
- asyncpreview_purchase
- asyncpurchase
- class discord.SubscriptionPlan¶
Represents a subscription plan for a
SKU.- x == y
Checks if two subscription plans are equal.
- x != y
Checks if two subscription plans are not equal.
- hash(x)
Returns the subscription plan’s hash.
- str(x)
Returns the subscription plan’s name.
New in version 2.0.
- interval¶
The interval of the subscription plan.
- Type
- prices¶
The different prices of the subscription plan. Not available in some contexts.
- Type
- currency¶
The currency of the subscription plan’s price. Not available in some contexts.
- Type
Optional[
str]
- discount_price¶
The discounted price of the subscription plan. This price is the one premium subscribers will pay, and is only available for premium subscribers.
- Type
Optional[
int]
- fallback_currency¶
The fallback currency of the subscription plan’s price. This is the currency that will be used for gifting if the user’s currency is not giftable.
- Type
Optional[
str]
- fallback_price¶
The fallback price of the subscription plan. This is the price that will be used for gifting if the user’s currency is not giftable.
- Type
Optional[
int]
- fallback_discount_price¶
The fallback discounted price of the subscription plan. This is the discounted price that will be used for gifting if the user’s currency is not giftable.
- Type
Optional[
int]
- property duration¶
How long the subscription plan lasts.
- Type
The premium type of the subscription plan, if it is a premium subscription.
- Type
Optional[
PremiumType]
- await gifts()¶
This function is a coroutine.
Retrieves the gifts purchased for this subscription plan.
- Raises
HTTPException – Retrieving the gifts failed.
- Returns
The gifts that have been purchased for this SKU.
- Return type
List[
Gift]
- await create_gift(*, gift_style=None)¶
This function is a coroutine.
Creates a gift for this subscription plan.
You must have a giftable entitlement for this subscription plan to create a gift.
- Parameters
gift_style (Optional[
GiftStyle]) – The style of the gift.- Raises
Forbidden – You do not have permissions to create a gift.
HTTPException – Creating the gift failed.
- Returns
The gift created.
- Return type
- await preview_purchase(payment_source, *, test_mode=False)¶
This function is a coroutine.
Previews a purchase of this subscription plan.
- Parameters
payment_source (
PaymentSource) – The payment source to use for the purchase.test_mode (
bool) – Whether to preview the purchase in test mode.
- Raises
HTTPException – Previewing the purchase failed.
- Returns
The previewed purchase price.
- Return type
- await purchase(payment_source=None, *, expected_amount=None, expected_currency=None, gift=False, gift_style=None, test_mode=False, payment_source_token=None, purchase_token=None, return_url=None, gateway_checkout_context=None)¶
This function is a coroutine.
Purchases this subscription plan.
This can only be used on premium subscription plans.
- Parameters
payment_source (Optional[
PaymentSource]) – The payment source to use for the purchase. Not required for free subscription plans.expected_amount (Optional[
int]) –The expected amount of the purchase. This can be gotten from
priceorpreview_purchase().If the value passed here does not match the actual purchase amount, the purchase will error.
expected_currency (Optional[
str]) –The expected currency of the purchase. This can be gotten from
priceorpreview_purchase().If the value passed here does not match the actual purchase currency, the purchase will error.
gift (
bool) – Whether to purchase the subscription plan as a gift. Certain requirements must be met for this to be possible.gift_style (Optional[
GiftStyle]) – The style of the gift. Only applicable ifgiftisTrue.test_mode (
bool) – Whether to purchase the subscription plan in test mode.payment_source_token (Optional[
str]) – The token used to authorize with the payment source.purchase_token (Optional[
str]) – The purchase token to use.return_url (Optional[
str]) – The URL to return to after the payment is complete.gateway_checkout_context (Optional[
str]) – The current checkout context.
- Raises
TypeError –
gift_stylewas passed butgiftwas notTrue.HTTPException – Purchasing the subscription plan failed.
- Returns
The purchased entitlements, the library entries created, and the gift created (if any).
- Return type
Tuple[List[
Entitlement], List[LibraryApplication], Optional[Gift]]
- class discord.SubscriptionPlanPrices¶
Represents the different prices for a
SubscriptionPlan.New in version 2.0.
Payment¶
- defis_premium_subscription
- defis_premium_subscription_gift
- defis_purchased_externally
- defis_subscription
- asyncrefund
- asyncvoid
- class discord.Payment¶
Represents a payment to Discord.
- x == y
Checks if two payments are equal.
- x != y
Checks if two payments are not equal.
- hash(x)
Returns the payment’s hash.
- str(x)
Returns the payment’s description.
New in version 2.0.
- status¶
The status of the payment.
- Type
- created_at¶
The time the payment was made.
- Type
- subscription_plan_id¶
The ID of the subscription plan the payment was for, if applicable.
- Type
Optional[
int]
- subscription¶
The subscription the payment was for, if applicable.
- Type
Optional[
Subscription]
- payment_source¶
The payment source the payment was made with.
- Type
Optional[
PaymentSource]
- payment_gateway¶
The payment gateway the payment was made with, if applicable.
- Type
Optional[
PaymentGateway]
- payment_gateway_payment_id¶
The ID of the payment on the payment gateway, if any.
- Type
Optional[
str]
- refund_invoices_urls¶
A list of URLs to download VAT credit notices for refunds on this payment, if available.
- Type
List[
str]
- refund_disqualification_reasons¶
A list of reasons why the payment cannot be refunded, if any.
- Type
List[
str]
bool: Whether the payment was for a Discord premium subscription.
bool: Whether the payment was for a Discord premium subscription gift.
- property flags¶
Returns the payment’s flags.
- Type
- await void()¶
This function is a coroutine.
Void the payment. Only applicable for payments of status
PaymentStatus.pending.- Raises
HTTPException – Voiding the payment failed.
- await refund(reason=None)¶
This function is a coroutine.
Refund the payment.
- Raises
HTTPException – Refunding the payment failed.
SKU¶
- access_level
- application
- application_id
- available_regions
- bundled_skus
- content_ratings
- dependent_sku_id
- exclusive
- external_purchase_url
- features
- flags
- genres
- id
- legal_notice
- legal_notice_localizations
- locales
- manifest_label_ids
- name
- name_localizations
- premium
- preorder_release_date
- preorder_released_at
- price
- price_overrides
- price_tier
- release_date
- restricted
- sale_price_overrides
- sale_price_tier
- show_age_gate
- slug
- summary
- summary_localizations
- supported_operating_systems
- system_requirements
- type
- url
- asynccreate_discount
- asynccreate_gift
- asynccreate_gift_batch
- asynccreate_store_listing
- asyncdelete_discount
- asyncedit
- asyncgifts
- defis_free
- defis_game_awards_winner
- defis_giftable
- defis_paid
- defis_premium_perk
- defis_premium_subscription
- defis_preorder
- defis_released
- asyncpreview_purchase
- asyncpurchase
- asyncstore_listings
- asyncsubscription_plans
- class discord.SKU¶
Represents a store SKU.
- x == y
Checks if two SKUs are equal.
- x != y
Checks if two SKUs are not equal.
- hash(x)
Returns the SKU’s hash.
- str(x)
Returns the SKU’s name.
New in version 2.0.
- summary_localizations¶
The summary of the SKU localized to different languages.
- legal_notice_localizations¶
The legal notice of the SKU localized to different languages.
- application¶
The application that owns this SKU, if available.
- Type
Optional[
PartialApplication]
- price_tier¶
The price tier of the SKU. This is the base price in USD. Not available for public SKUs.
- Type
Optional[
int]
- price_overrides¶
Price overrides for specific currencies. These override the base price tier. Not available for public SKUs.
- sale_price_tier¶
The sale price tier of the SKU. This is the base sale price in USD. Not available for public SKUs.
- Type
Optional[
int]
- sale_price_overrides¶
Sale price overrides for specific currencies. These override the base sale price tier.
- access_level¶
The access level of the SKU.
- Type
- features¶
A list of features that this SKU has.
- Type
List[
SKUFeature]
- available_regions¶
The regions that this SKU is available in. If this is
None, then the SKU is available everywhere.- Type
Optional[List[
str]]
- content_ratings¶
The content ratings of the SKU, if any. For public SKUs, only the rating of your region is returned.
- Type
List[
ContentRating]
- system_requirements¶
The system requirements of the SKU by operating system, if any.
- Type
List[
SystemRequirements]
- release_date¶
The date that the SKU will released, if any.
- Type
Optional[
datetime.date]
- preorder_release_date¶
The approximate date that the SKU will released for pre-order, if any.
- Type
Optional[
datetime.date]
- preorder_released_at¶
The date that the SKU was released for pre-order, if any.
- Type
Optional[
datetime.datetime]
Whether this SKU is provided for free to premium users.
- Type
- bundled_skus¶
A list of SKUs bundled with this SKU. These are SKUs that the user will be entitled to after purchasing this parent SKU.
- Type
List[
SKU]
bool: Checks if the SKU is a perk for premium users.
bool: Checks if the SKU is a premium subscription (e.g. Nitro or Server Boosts).
- property supported_operating_systems¶
A list of supported operating systems.
- Type
List[
OperatingSystem]
- await edit(name=..., name_localizations=..., legal_notice=..., legal_notice_localizations=..., price_tier=..., price_overrides=..., sale_price_tier=..., sale_price_overrides=..., dependent_sku=..., flags=..., access_level=..., features=..., locales=..., genres=..., content_ratings=..., system_requirements=..., release_date=..., bundled_skus=..., manifest_labels=...)¶
This function is a coroutine.
Edits the SKU.
All parameters are optional.
- Parameters
name (
str) – The SKU’s name.name_localizations (Dict[
Locale,str]) – The SKU’s name localized to other languages.legal_notice (Optional[
str]) – The SKU’s legal notice.legal_notice_localizations (Dict[
Locale,str]) – The SKU’s legal notice localized to other languages.price_tier (Optional[
int]) – The price tier of the SKU. This is the base price in USD that other currencies will be calculated from.price_overrides (Dict[
str,int]) – A mapping of currency to price. These prices override the base price tier.sale_price_tier (Optional[
int]) – The sale price tier of the SKU. This is the base sale price in USD that other currencies will be calculated from.sale_price_overrides (Dict[
str,int]) – A mapping of currency to sale price. These prices override the base sale price tier.dependent_sku (Optional[
SKU]) – The ID of the SKU that this SKU is dependent on.flags (
SKUFlags) – The SKU’s flags.access_level (
SKUAccessLevel) – The access level of the SKU.features (List[
SKUFeature]) – A list of features of the SKU.locales (List[
Locale]) – A list of locales supported by the SKU.genres (List[
SKUGenre]) – A list of genres of the SKU.content_ratings (List[
ContentRating]) – A list of content ratings of the SKU.system_requirements (List[
SystemRequirements]) – A list of system requirements of the SKU.release_date (Optional[
datetime.date]) – The release date of the SKU.bundled_skus (List[
SKU]) – A list SKUs that are bundled with this SKU.manifest_labels (List[
ManifestLabel]) – A list of manifest labels for the SKU.
- Raises
Forbidden – You do not have access to edit the SKU.
HTTPException – Editing the SKU failed.
- await subscription_plans(*, country_code=..., payment_source=..., with_unpublished=False)¶
This function is a coroutine.
Returns a list of
SubscriptionPlans for this SKU.New in version 2.0.
- Parameters
country_code (
str) – The country code to retrieve the subscription plan prices for. Defaults to the country code of the current user.payment_source (
PaymentSource) – The specific payment source to retrieve the subscription plan prices for. Defaults to all payment sources of the current user.with_unpublished (
bool) –Whether to include unpublished subscription plans.
If
True, then you require access to the application.
- Raises
HTTPException – Retrieving the subscription plans failed.
- Returns
The subscription plans for this SKU.
- Return type
List[
SubscriptionPlan]
- await store_listings(localize=True)¶
This function is a coroutine.
Returns a list of
StoreListings for this SKU.- Parameters
localize (
bool) – Whether to localize the store listings to the current user’s locale. IfFalsethen all localizations are returned.- Raises
Forbidden – You do not have access to fetch store listings.
HTTPException – Retrieving the store listings failed.
- Returns
The store listings for this SKU.
- Return type
List[
StoreListing]
- await create_store_listing(*, summary, summary_localizations=None, description, description_localizations=None, tagline=None, tagline_localizations=None, child_skus=None, guild=None, published=False, carousel_items=None, preview_video=None, header_background=None, hero_background=None, hero_video=None, box_art=None, thumbnail=None, header_logo_light=None, header_logo_dark=None)¶
This function is a coroutine.
Creates a a store listing for this SKU.
- Parameters
summary (
str) – The summary of the store listing.summary_localizations (Optional[Dict[
Locale,str]]) – The summary of the store listing localized to different languages.description (
str) – The description of the store listing.description_localizations (Optional[Dict[
Locale,str]]) – The description of the store listing localized to different languages.tagline (Optional[
str]) – The tagline of the store listing.tagline_localizations (Optional[Dict[
Locale,str]]) – The tagline of the store listing localized to different languages.child_skus (Optional[List[
SKU]]) – The child SKUs of the store listing.guild (Optional[
Guild]) – The guild that the store listing is for.published (
bool) – Whether the store listing is published.carousel_items (Optional[List[Union[
StoreAsset,str]]]) – A list of carousel items to add to the store listing. These can be store assets or YouTube video IDs.preview_video (Optional[
StoreAsset]) – The preview video of the store listing.header_background (Optional[
StoreAsset]) – The header background of the store listing.hero_background (Optional[
StoreAsset]) – The hero background of the store listing.hero_video (Optional[
StoreAsset]) – The hero video of the store listing.box_art (Optional[
StoreAsset]) – The box art of the store listing.thumbnail (Optional[
StoreAsset]) – The thumbnail of the store listing.header_logo_light (Optional[
StoreAsset]) – The header logo image for light backgrounds.header_logo_dark (Optional[
StoreAsset]) – The header logo image for dark backgrounds.
- Raises
Forbidden – You do not have permissions to edit the store listing.
HTTPException – Editing the store listing failed.
- await create_discount(user, percent_off, *, ttl=3600)¶
This function is a coroutine.
Creates a discount for this SKU for a user.
This discount will be applied to the user’s next purchase of this SKU.
- Parameters
- Raises
Forbidden – You do not have permissions to create the discount.
HTTPException – Creating the discount failed.
- await delete_discount(user)¶
This function is a coroutine.
Deletes a discount for this SKU for a user.
You do not need to call this after a discounted purchase has been made, as the discount will be automatically consumed and deleted.
- Parameters
user (
User) – The user to delete the discount for.- Raises
Forbidden – You do not have permissions to delete the discount.
HTTPException – Deleting the discount failed.
- await create_gift_batch(*, amount, description, entitlement_branches=None, entitlement_starts_at=None, entitlement_ends_at=None)¶
This function is a coroutine.
Creates a gift batch for this SKU.
- Parameters
amount (
int) – The amount of gifts to create in the batch.description (
str) – The description of the gift batch.entitlement_branches (List[
ApplicationBranch]) – The branches to grant in the gifts.entitlement_starts_at (
datetime.date) – When the entitlement is valid from.entitlement_ends_at (
datetime.date) – When the entitlement is valid until.
- Raises
Forbidden – You do not have permissions to create a gift batch.
HTTPException – Creating the gift batch failed.
- Returns
The gift batch created.
- Return type
- await gifts(subscription_plan=None)¶
This function is a coroutine.
Retrieves the gifts purchased for this SKU.
- Parameters
subscription_plan (Optional[
SubscriptionPlan]) – The subscription plan to retrieve the gifts for.- Raises
HTTPException – Retrieving the gifts failed.
- Returns
The gifts that have been purchased for this SKU.
- Return type
List[
Gift]
- await create_gift(*, subscription_plan=None, gift_style=None)¶
This function is a coroutine.
Creates a gift for this SKU.
You must have a giftable entitlement for this SKU to create a gift.
- Parameters
subscription_plan (Optional[
SubscriptionPlan]) – The subscription plan to gift.gift_style (Optional[
GiftStyle]) – The style of the gift.
- Raises
Forbidden – You do not have permissions to create a gift.
HTTPException – Creating the gift failed.
- Returns
The gift created.
- Return type
- await preview_purchase(payment_source, *, subscription_plan=None, test_mode=False)¶
This function is a coroutine.
Previews a purchase of this SKU.
- Parameters
payment_source (
PaymentSource) – The payment source to use for the purchase.subscription_plan (Optional[
SubscriptionPlan]) – The subscription plan being purchased.test_mode (
bool) – Whether to preview the purchase in test mode.
- Raises
HTTPException – Previewing the purchase failed.
- Returns
The previewed purchase price.
- Return type
- await purchase(payment_source=None, *, subscription_plan=None, expected_amount=None, expected_currency=None, gift=False, gift_style=None, test_mode=False, payment_source_token=None, purchase_token=None, return_url=None, gateway_checkout_context=None)¶
This function is a coroutine.
Purchases this SKU.
- Parameters
payment_source (Optional[
PaymentSource]) – The payment source to use for the purchase. Not required for free SKUs.subscription_plan (Optional[
SubscriptionPlan]) – The subscription plan to purchase. Can only be used for premium subscription SKUs.expected_amount (Optional[
int]) –The expected amount of the purchase. This can be gotten from
priceorpreview_purchase().If the value passed here does not match the actual purchase amount, the purchase will error.
expected_currency (Optional[
str]) –The expected currency of the purchase. This can be gotten from
priceorpreview_purchase().If the value passed here does not match the actual purchase currency, the purchase will error.
gift (
bool) – Whether to purchase the SKU as a gift. Certain requirements must be met for this to be possible.gift_style (Optional[
GiftStyle]) – The style of the gift. Only applicable ifgiftisTrue.test_mode (
bool) – Whether to purchase the SKU in test mode.payment_source_token (Optional[
str]) – The token used to authorize with the payment source.purchase_token (Optional[
str]) – The purchase token to use.return_url (Optional[
str]) – The URL to return to after the payment is complete.gateway_checkout_context (Optional[
str]) – The current checkout context.
- Raises
TypeError –
gift_stylewas passed butgiftwas notTrue.HTTPException – Purchasing the SKU failed.
- Returns
The purchased entitlements, the library entries created, and the gift created (if any).
- Return type
Tuple[List[
Entitlement], List[LibraryApplication], Optional[Gift]]
- class discord.ThirdPartySKU¶
Represents an application’s primary SKU on third-party platforms.
New in version 2.0.
- application¶
The application that the SKU belongs to.
- Type
- distributor¶
The distributor of the SKU.
- Type
- defis_discounted
- defis_free
- class discord.SKUPrice¶
Represents a SKU’s price.
- bool(x)
Checks if a SKU costs anything.
- int(x)
Returns the price of the SKU.
New in version 2.0.
- asyncedit
- class discord.StoreListing¶
Represents a store listing.
- x == y
Checks if two listings are equal.
- x != y
Checks if two listings are not equal.
- hash(x)
Returns the listing’s hash.
- str(x)
Returns the listing’s summary.
New in version 2.0.
- summary_localizations¶
The listing’s summary localized to different languages.
- description_localizations¶
The listing’s description localized to different languages.
- tagline_localizations¶
The listing’s tagline localized to different languages.
- assets¶
A list of assets used in this listing.
- Type
List[
StoreAsset]
- carousel_items¶
A list of assets and YouTube videos displayed in the carousel.
- Type
List[
StoreAsset]
- preview_video¶
The preview video of the store listing.
- Type
Optional[
StoreAsset]
- header_background¶
The header background image.
- Type
Optional[
StoreAsset]
- hero_background¶
The hero background image.
- Type
Optional[
StoreAsset]
- box_art¶
The box art of the product.
- Type
Optional[
StoreAsset]
- thumbnail¶
The listing’s thumbnail.
- Type
Optional[
StoreAsset]
- header_logo_light¶
The header logo image for light backgrounds.
- Type
Optional[
StoreAsset]
- header_logo_dark¶
The header logo image for dark backgrounds.
- Type
Optional[
StoreAsset]
- await edit(*, summary=..., summary_localizations=..., description=..., description_localizations=..., tagline=..., tagline_localizations=..., child_skus=..., guild=..., published=..., carousel_items=..., preview_video=..., header_background=..., hero_background=..., hero_video=..., box_art=..., thumbnail=..., header_logo_light=..., header_logo_dark=...)¶
This function is a coroutine.
Edits the store listing.
All parameters are optional.
- Parameters
summary (Optional[
str]) – The summary of the store listing.summary_localizations (Dict[
Locale,str]) – The summary of the store listing localized to different languages.description (Optional[
str]) – The description of the store listing.description_localizations (Dict[
Locale,str]) – The description of the store listing localized to different languages.tagline (Optional[
str]) – The tagline of the store listing.tagline_localizations (Dict[
Locale,str]) – The tagline of the store listing localized to different languages.child_skus (List[
SKU]) – The child SKUs of the store listing.guild (Optional[
Guild]) – The guild that the store listing is for.published (
bool) – Whether the store listing is published.carousel_items (List[Union[
StoreAsset,str]]) – A list of carousel items to add to the store listing. These can be store assets or YouTube video IDs.preview_video (Optional[
StoreAsset]) – The preview video of the store listing.header_background (Optional[
StoreAsset]) – The header background of the store listing.hero_background (Optional[
StoreAsset]) – The hero background of the store listing.hero_video (Optional[
StoreAsset]) – The hero video of the store listing.box_art (Optional[
StoreAsset]) – The box art of the store listing.thumbnail (Optional[
StoreAsset]) – The thumbnail of the store listing.header_logo_light (Optional[
StoreAsset]) – The header logo image for light backgrounds.header_logo_dark (Optional[
StoreAsset]) – The header logo image for dark backgrounds.
- Raises
Forbidden – You do not have permissions to edit the store listing.
HTTPException – Editing the store listing failed.
- asyncdelete
- defis_youtube_video
- asyncread
- class discord.StoreAsset¶
Represents an application store asset.
- x == y
Checks if two assets are equal.
- x != y
Checks if two assets are not equal.
- hash(x)
Returns the asset’s hash.
New in version 2.0.
- parent¶
The store listing or application that this asset belongs to.
- Type
Union[
StoreListing,Application]
- await read()¶
This function is a coroutine.
Retrieves the content of this asset as a
bytesobject.- Raises
ValueError – The asset is a YouTube video.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns
The content of the asset.
- Return type
- await delete()¶
This function is a coroutine.
Deletes the asset.
- Raises
ValueError – The asset is a YouTube video.
Forbidden – You are not allowed to delete this asset.
HTTPException – Deleting the asset failed.
- class discord.StoreNote¶
Represents a note for a store listing.
- str(x)
Returns the note’s content.
New in version 2.0.
- class discord.ContentRating¶
Represents a SKU’s content rating.
New in version 2.0.
- agency¶
The agency that rated the content.
- Type
- rating¶
The rating of the content.
- Type
Union[
ESRBRating,PEGIRating]
- descriptors¶
Extra descriptors for the content rating.
- Type
Union[List[
ESRBContentDescriptor], List[PEGIContentDescriptor]
- minimum_cpu
- minimum_directx
- minimum_disk
- minimum_gpu
- minimum_network
- minimum_notes
- minimum_os_version
- minimum_ram
- minimum_sound_card
- os
- recommended_cpu
- recommended_directx
- recommended_disk
- recommended_gpu
- recommended_network
- recommended_notes
- recommended_os_version
- recommended_ram
- recommended_sound_card
Metadata¶
- class discord.Metadata¶
Represents a raw model from Discord.
Because of how unstable and wildly varying some metadata in Discord can be, this is a simple class that just provides access to the raw data using dot notation. This means that
Noneis returned for unknown attributes instead of raising an exception. This class can be used similarly to a dictionary.New in version 2.0.
- x == y
Checks if two metadata objects are equal.
- x != y
Checks if two metadata objects are not equal.
- x[key]
Returns a metadata value if it is found, otherwise raises a
KeyError.
- key in x
Checks if a metadata value is present.
- len(x)
Returns the number of metadata values present.
- iter(x)
- Returns an iterator of ``(field, value)`` pairs. This allows this class
- to be used as an iterable in list/dict/etc constructions.
- keys()¶
A set-like object providing a view on the metadata’s keys.
- values()¶
A set-like object providing a view on the metadata’s values.
- items()¶
A set-like object providing a view on the metadata’s items.
Asset¶
- defis_animated
- defis_passthrough
- asyncread
- defreplace
- asyncsave
- asyncto_file
- defwith_format
- defwith_size
- defwith_static_format
- class discord.Asset¶
Represents a CDN asset on Discord.
- str(x)
Returns the URL of the CDN asset.
- len(x)
Returns the length of the CDN asset’s URL.
- x == y
Checks if the asset is equal to another asset.
- x != y
Checks if the asset is not equal to another asset.
- hash(x)
Returns the hash of the asset.
- replace(*, size=..., format=..., static_format=..., passthrough=..., keep_aspect_ratio=False)¶
Returns a new asset with the passed components replaced.
Changed in version 2.0:
static_formatis now preferred overformatif both are present and the asset is not animated.Changed in version 2.0: This function will now raise
ValueErrorinstead ofInvalidArgument.- Parameters
size (
int) – The new size of the asset.format (
str) – The new format to change it to. Must be either ‘webp’, ‘jpeg’, ‘jpg’, ‘png’, or ‘gif’ if it’s animated.static_format (
str) – The new format to change it to if the asset isn’t animated. Must be either ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’.passthrough (
bool) –Whether to return the asset in the original, Discord-defined quality and format (usually APNG). This only has an affect on specific asset types. This will cause the
formatandsizeparameters to be ignored by the CDN. By default, this is set toFalseif a size or format parameter is passed and the asset is marked as passed through, else untouched. A value ofNonewill unconditionally omit the parameter from the query string.New in version 2.0.
keep_aspect_ratio (
bool) –Whether to return the original aspect ratio of the asset instead of having it resized to the endpoint’s enforced aspect ratio.
New in version 2.0.
- Raises
ValueError – An invalid size or format was passed.
- Returns
The newly updated asset.
- Return type
- with_size(size, /)¶
Returns a new asset with the specified size. Also sets
passthroughtoFalseif the asset is marked as passed through.Changed in version 2.0: This function will now raise
ValueErrorinstead ofInvalidArgument.- Parameters
size (
int) – The new size of the asset.- Raises
ValueError – The asset had an invalid size.
- Returns
The new updated asset.
- Return type
- with_format(format, /)¶
Returns a new asset with the specified format. Also sets
passthroughtoFalseif the asset is marked as passed through.Changed in version 2.0: This function will now raise
ValueErrorinstead ofInvalidArgument.- Parameters
format (
str) – The new format of the asset.- Raises
ValueError – The asset had an invalid format.
- Returns
The new updated asset.
- Return type
- with_static_format(format, /)¶
Returns a new asset with the specified static format. Also sets
passthroughtoFalseif the asset is marked as passed through.This only changes the format if the underlying asset is not animated. Otherwise, the asset is not changed.
Changed in version 2.0: This function will now raise
ValueErrorinstead ofInvalidArgument.- Parameters
format (
str) – The new static format of the asset.- Raises
ValueError – The asset had an invalid format.
- Returns
The new updated asset.
- Return type
- await read()¶
This function is a coroutine.
Retrieves the content of this asset as a
bytesobject.- Raises
DiscordException – There was no internal connection state.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns
The content of the asset.
- Return type
- await save(fp, *, seek_begin=True)¶
This function is a coroutine.
Saves this asset into a file-like object.
- Parameters
fp (Union[
io.BufferedIOBase,os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.seek_begin (
bool) – Whether to seek to the beginning of the file after saving is successfully done.
- Raises
DiscordException – There was no internal connection state.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns
The number of bytes written.
- Return type
- await to_file(*, filename=..., description=None, spoiler=False)¶
This function is a coroutine.
Converts the asset into a
Filesuitable for sending viaabc.Messageable.send().New in version 2.0.
- Parameters
- Raises
DiscordException – The asset does not have an associated state.
ValueError – The asset is a unicode emoji.
TypeError – The asset is a sticker with lottie type.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns
The asset as a file suitable for sending.
- Return type
Guild¶
- afk_channel
- afk_timeout
- application_command_count
- application_command_counts
- approximate_member_count
- approximate_presence_count
- banner
- bitrate_limit
- categories
- channels
- chunked
- created_at
- default_notifications
- default_role
- description
- discovery_splash
- emoji_limit
- emojis
- explicit_content_filter
- features
- filesize_limit
- forums
- icon
- id
- joined_at
- large
- max_members
- max_presences
- max_video_channel_users
- me
- member_count
- members
- mfa_level
- name
- notification_settings
- nsfw_level
- online_count
- owner
- owner_application_id
- owner_id
- preferred_locale
- premium_progress_bar_enabled
- premium_subscriber_role
- premium_subscribers
- premium_subscription_count
- premium_tier
- public_updates_channel
- roles
- rules_channel
- scheduled_events
- splash
- stage_channels
- stage_instances
- sticker_limit
- stickers
- system_channel
- system_channel_flags
- text_channels
- threads
- unavailable
- vanity_url
- vanity_url_code
- verification_level
- voice_channels
- voice_client
- widget_channel
- widget_enabled
- asyncack
- asyncapplications
- asyncapply_premium_subscription_slots
- async foraudit_logs
- asyncautomod_rules
- asyncban
- async forbans
- defby_category
- asyncchange_voice_state
- asyncchunk
- asynccreate_automod_rule
- asynccreate_category
- asynccreate_category_channel
- asynccreate_custom_emoji
- asynccreate_forum
- asynccreate_integration
- asynccreate_role
- asynccreate_scheduled_event
- asynccreate_stage_channel
- asynccreate_sticker
- asynccreate_template
- asynccreate_text_channel
- asynccreate_voice_channel
- asyncdelete
- asyncdelete_emoji
- asyncdelete_sticker
- asyncedit
- asyncedit_role_positions
- asyncedit_welcome_screen
- asyncedit_widget
- asyncentitlements
- asyncestimate_pruned_members
- asyncfetch_automod_rule
- asyncfetch_ban
- asyncfetch_channel
- asyncfetch_channels
- asyncfetch_emoji
- asyncfetch_emojis
- asyncfetch_member
- asyncfetch_member_profile
- asyncfetch_members
- asyncfetch_price_tier
- asyncfetch_roles
- asyncfetch_scheduled_event
- asyncfetch_scheduled_events
- asyncfetch_sticker
- asyncfetch_stickers
- defget_channel
- defget_channel_or_thread
- defget_emoji
- defget_member
- defget_member_named
- defget_role
- defget_scheduled_event
- defget_stage_instance
- defget_thread
- asyncintegrations
- asyncinvites
- defis_joined
- asynckick
- asyncleave
- asyncpremium_subscriptions
- asyncprice_tiers
- asyncprune_members
- asyncquery_members
- asyncrequest
- asynctemplates
- asynctop_emojis
- asyncunban
- asyncvanity_invite
- asyncwebhooks
- asyncwelcome_screen
- asyncwidget
- class discord.Guild¶
Represents a Discord guild.
This is referred to as a “server” in the official Discord UI.
- x == y
Checks if two guilds are equal.
- x != y
Checks if two guilds are not equal.
- hash(x)
Returns the guild’s hash.
- str(x)
Returns the guild’s name.
- stickers¶
All stickers that the guild owns.
New in version 2.0.
- Type
Tuple[
GuildSticker, …]
Indicates if the guild is unavailable. If this is
Truethen the reliability of other attributes outside ofGuild.idis slim and they might all beNone. It is best to not do anything with the guild if it is unavailable.Check the
on_guild_unavailable()andon_guild_available()events.- Type
- max_video_channel_users¶
The maximum amount of users in a video channel.
New in version 1.4.
- Type
Optional[
int]
- verification_level¶
The guild’s verification level.
- Type
- explicit_content_filter¶
The guild’s explicit content filter.
- Type
- default_notifications¶
The guild’s notification settings.
- Type
- features¶
A list of features that the guild has. The features that a guild can have are subject to arbitrary change by Discord.
- Type
List[
str]
The number of “boosts” this guild currently has.
- Type
- preferred_locale¶
The preferred locale for the guild. Used when filtering Server Discovery results to a specific language.
Changed in version 2.0: This field is now an enum instead of a
str.- Type
- mfa_level¶
The guild’s Multi-Factor Authentication requirement level.
Changed in version 2.0: This field is now an enum instead of an
int.- Type
- application_command_counts¶
A namedtuple representing the number of application commands in the guild, separated by type.
New in version 2.0.
- Type
Optional[
ApplicationCommandCounts]
- approximate_member_count¶
The approximate number of members in the guild. This is
Noneunless the guild is obtained usingClient.fetch_guild()withwith_counts=True.New in version 2.0.
- Type
Optional[
int]
- approximate_presence_count¶
The approximate number of members currently active in the guild. Offline members are excluded. This is
Noneunless the guild is obtained usingClient.fetch_guild()withwith_counts=True.New in version 2.0.
- Type
Optional[
int]
Indicates if the guild has the premium (server boost) progress bar enabled.
New in version 2.0.
- Type
- property channels¶
A list of channels that belongs to this guild.
- Type
Sequence[
abc.GuildChannel]
- property threads¶
A list of active threads that you have permission to view.
New in version 2.0.
- Type
Sequence[
Thread]
- property large¶
Indicates if the guild is a ‘large’ guild.
A large guild is defined as having more than
large_thresholdcount members, which for this library is set to the maximum of 250.- Type
- property voice_channels¶
A list of voice channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
- Type
List[
VoiceChannel]
- property stage_channels¶
A list of stage channels that belongs to this guild.
New in version 1.7.
This is sorted by the position and are in UI order from top to bottom.
- Type
List[
StageChannel]
- property me¶
Similar to
Client.userexcept an instance ofMember. This is essentially used to get the member version of yourself.Changed in version 2.0: The type has been updated to be optional, which properly reflects cases where the current user is not a member of the guild, or the current user’s member object is not cached.
- Type
Optional[
Member]
- is_joined()¶
Returns whether you are a member of this guild.
May not be accurate for
Guilds fetched over HTTP.New in version 2.0.
- Returns
Whether you are a member of this guild.
- Return type
- property joined_at¶
Returns when you joined the guild.
New in version 2.0.
- Type
- property voice_client¶
Returns the
VoiceProtocolassociated with this guild, if any.- Type
Optional[
VoiceProtocol]
- property notification_settings¶
Returns the notification settings for the guild.
If not found, an instance is created with defaults applied. This follows Discord behaviour.
New in version 2.0.
- Type
- property text_channels¶
A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
- Type
List[
TextChannel]
- property categories¶
A list of categories that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
- Type
List[
CategoryChannel]
- property forums¶
A list of forum channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
New in version 2.0.
- Type
List[
ForumChannel]
- by_category()¶
Returns every
CategoryChanneland their associated channels.These channels and categories are sorted in the official Discord UI order.
If the channels do not have a category, then the first element of the tuple is
None.- Returns
The categories and their associated channels.
- Return type
List[Tuple[Optional[
CategoryChannel], List[abc.GuildChannel]]]
- get_channel_or_thread(channel_id, /)¶
Returns a channel or thread with the given ID.
New in version 2.0.
- Parameters
channel_id (
int) – The ID to search for.- Returns
The returned channel, thread, or
Noneif not found.- Return type
Optional[Union[
Thread,abc.GuildChannel]]
- get_channel(channel_id, /)¶
Returns a channel with the given ID.
Note
This does not search for threads.
Changed in version 2.0:
channel_idparameter is now positional-only.- Parameters
channel_id (
int) – The ID to search for.- Returns
The returned channel or
Noneif not found.- Return type
Optional[
abc.GuildChannel]
- get_thread(thread_id, /)¶
Returns a thread with the given ID.
Note
This does not always retrieve archived threads, as they are not retained in the internal cache. Use
fetch_channel()instead.New in version 2.0.
- get_emoji(emoji_id, /)¶
Returns an emoji with the given ID.
New in version 2.0.
- property system_channel¶
Returns the guild’s channel used for system messages.
If no channel is set, then this returns
None.- Type
Optional[
TextChannel]
- property system_channel_flags¶
Returns the guild’s system channel settings.
- Type
- property rules_channel¶
Return’s the guild’s channel used for the rules. The guild must be a Community guild.
If no channel is set, then this returns
None.New in version 1.3.
- Type
Optional[
TextChannel]
- property public_updates_channel¶
Return’s the guild’s channel where admins and moderators of the guilds receive notices from Discord. The guild must be a Community guild.
If no channel is set, then this returns
None.New in version 1.4.
- Type
Optional[
TextChannel]
- property afk_channel¶
Returns the guild channel AFK users are moved to.
If no channel is set, then this returns
None.- Type
Optional[
VoiceChannel]
- property widget_channel¶
Returns the widget channel of the guild.
If no channel is set, then this returns
None.New in version 2.0.
- Type
Optional[Union[
TextChannel,ForumChannel,VoiceChannel,StageChannel]]
- property sticker_limit¶
The maximum number of sticker slots this guild has.
New in version 2.0.
- Type
- property filesize_limit¶
The maximum number of bytes files can have when uploaded to this guild.
- Type
- get_member(user_id, /)¶
Returns a member with the given ID.
Changed in version 2.0:
user_idparameter is now positional-only.
The premium tier for this guild. Corresponds to “Server Boost Level” in the official UI. The number goes from 0 to 3 inclusive.
- Type
A list of members who have subscribed to (boosted) this guild.
- Type
List[
Member]
- property roles¶
Returns a sequence of the guild’s roles in hierarchy order.
The first element of this sequence will be the lowest role in the hierarchy.
- Type
Sequence[
Role]
- get_role(role_id, /)¶
Returns a role with the given ID.
Changed in version 2.0:
role_idparameter is now positional-only.
Gets the premium subscriber role, AKA “boost” role, in this guild.
New in version 1.6.
- Type
Optional[
Role]
- property stage_instances¶
Returns a sequence of the guild’s stage instances that are currently running.
New in version 2.0.
- Type
Sequence[
StageInstance]
- get_stage_instance(stage_instance_id, /)¶
Returns a stage instance with the given ID.
New in version 2.0.
- Parameters
stage_instance_id (
int) – The ID to search for.- Returns
The stage instance or
Noneif not found.- Return type
Optional[
StageInstance]
- property scheduled_events¶
Returns a sequence of the guild’s scheduled events.
New in version 2.0.
- Type
Sequence[
ScheduledEvent]
- get_scheduled_event(scheduled_event_id, /)¶
Returns a scheduled event with the given ID.
New in version 2.0.
- Parameters
scheduled_event_id (
int) – The ID to search for.- Returns
The scheduled event or
Noneif not found.- Return type
Optional[
ScheduledEvent]
- property discovery_splash¶
Returns the guild’s discovery splash asset, if available.
- Type
Optional[
Asset]
- property member_count¶
Returns the member count if available.
Warning
Due to a Discord limitation, this may not always be up-to-date and accurate.
- Type
Optional[
int]
- property online_count¶
Returns the online member count.
New in version 1.9.
Warning
Due to a Discord limitation, this may not always be up-to-date and accurate.
- Type
Optional[
int]
- property application_command_count¶
Returns the application command count if available.
New in version 2.0.
- Type
Optional[
int]
- property chunked¶
Returns a boolean indicating if the guild is “chunked”.
A chunked guild means that
member_countis equal to the number of members stored in the internalmemberscache.If this value returns
False, then you should request for offline members.- Type
- property created_at¶
Returns the guild’s creation time in UTC.
- Type
- get_member_named(name, /)¶
Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.
If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.
If no member is found,
Noneis returned.Changed in version 2.0:
nameparameter is now positional-only.
- await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=..., default_thread_slowmode_delay=...)¶
This function is a coroutine.
Creates a
TextChannelfor the guild.Note that you must have
manage_channelsto create the channel.The
overwritesparameter can be used to create a ‘secret’ channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas the value.Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to
edit()will be required to update the position of the channel in the channel list.Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.Examples
Creating a basic channel:
channel = await guild.create_text_channel('cool-channel')
Creating a “secret” channel:
overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True) } channel = await guild.create_text_channel('secret', overwrites=overwrites)
- Parameters
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member],PermissionOverwrite]) – Adictof target (either a role or a member) toPermissionOverwriteto apply upon creation of a channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (
str) – The new channel’s topic.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is21600.nsfw (
bool) – To mark the channel as NSFW or not.news (
bool) –Whether to create the text channel as a news channel.
New in version 2.0.
default_auto_archive_duration (
int) –The default auto archive duration for threads created in the text channel (in minutes). Must be one of
60,1440,4320, or10080.New in version 2.0.
default_thread_slowmode_delay (
int) –The default slowmode delay in seconds for threads created in the text channel.
New in version 2.0.
reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.
- Raises
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
TypeError – The permission overwrite information is not in proper form.
- Returns
The channel that was just created.
- Return type
- await create_voice_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=...)¶
This function is a coroutine.
This is similar to
create_text_channel()except makes aVoiceChannelinstead.Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member],PermissionOverwrite]) – Adictof target (either a role or a member) toPermissionOverwriteto apply upon creation of a channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.bitrate (
int) – The channel’s preferred audio bitrate in bits per second.user_limit (
int) – The channel’s limit for number of members that can be in a voice channel.rtc_region (Optional[
str]) –The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.New in version 1.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
New in version 2.0.
reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.
- Raises
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
TypeError – The permission overwrite information is not in proper form.
- Returns
The channel that was just created.
- Return type
- await create_stage_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=...)¶
This function is a coroutine.
This is similar to
create_text_channel()except makes aStageChannelinstead.New in version 1.7.
Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member],PermissionOverwrite]) – Adictof target (either a role or a member) toPermissionOverwriteto apply upon creation of a channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.bitrate (
int) –The channel’s preferred audio bitrate in bits per second.
New in version 2.0.
user_limit (
int) –The channel’s limit for number of members that can be in a voice channel.
New in version 2.0.
rtc_region (Optional[
str]) –The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.New in version 2.0.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
New in version 2.0.
reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.
- Raises
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
TypeError – The permission overwrite information is not in proper form.
- Returns
The channel that was just created.
- Return type
- await create_category(name, *, overwrites=..., reason=None, position=...)¶
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter is not supported in this function since categories cannot have categories.Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Raises
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
TypeError – The permission overwrite information is not in proper form.
- Returns
The channel that was just created.
- Return type
- await create_category_channel(name, *, overwrites=..., reason=None, position=...)¶
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter is not supported in this function since categories cannot have categories.Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Raises
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
TypeError – The permission overwrite information is not in proper form.
- Returns
The channel that was just created.
- Return type
- await create_forum(name, *, topic=..., position=..., category=None, slowmode_delay=..., nsfw=..., overwrites=..., reason=None, default_auto_archive_duration=..., default_thread_slowmode_delay=..., default_sort_order=..., default_reaction_emoji=..., default_layout=..., available_tags=...)¶
This function is a coroutine.
Similar to
create_text_channel()except makes aForumChannelinstead.The
overwritesparameter can be used to create a ‘secret’ channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas the value.New in version 2.0.
- Parameters
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member],PermissionOverwrite]) – Adictof target (either a role or a member) toPermissionOverwriteto apply upon creation of a channel. Useful for creating secret channels.topic (
str) – The channel’s topic.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.nsfw (
bool) – To mark the channel as NSFW or not.slowmode_delay (
int) – Specifies the slowmode rate limit for users in this channel, in seconds. The maximum possible value is21600.reason (Optional[
str]) – The reason for creating this channel. Shows up in the audit log.default_auto_archive_duration (
int) – The default auto archive duration for threads created in the forum channel (in minutes). Must be one of60,1440,4320, or10080.default_thread_slowmode_delay (
int) – The default slowmode delay in seconds for threads created in this forum.default_sort_order (
ForumOrderType) – The default sort order for posts in this forum channel.default_reaction_emoji (Union[
Emoji,PartialEmoji,str]) – The default reaction emoji for threads created in this forum to show in the add reaction button.default_layout (
ForumLayoutType) – The default layout for posts in this forum.available_tags (Sequence[
ForumTag]) – The available tags for this forum channel.
- Raises
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
TypeError – The permission overwrite information is not in proper form.
- Returns
The channel that was just created.
- Return type
- await leave()¶
This function is a coroutine.
Leaves the guild.
Note
You cannot leave a guild that you own, you must delete it instead via
delete().- Raises
HTTPException – Leaving the guild failed.
- await delete()¶
This function is a coroutine.
Deletes the guild. You must be the guild owner to delete the guild.
- Raises
HTTPException – Deleting the guild failed.
Forbidden – You do not have permissions to delete the guild.
- await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., afk_channel=..., owner=..., afk_timeout=..., default_notifications=..., verification_level=..., explicit_content_filter=..., vanity_code=..., system_channel=..., system_channel_flags=..., preferred_locale=..., rules_channel=..., public_updates_channel=..., premium_progress_bar_enabled=..., discoverable=..., invites_disabled=..., widget_enabled=..., widget_channel=..., mfa_level=...)¶
This function is a coroutine.
Edits the guild.
You must have
manage_guildto edit the guild.Changed in version 2.0: The newly updated guild is returned.
Changed in version 2.0: The
regionkeyword parameter has been removed.Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
name (
str) – The new name of the guild.description (Optional[
str]) – The new description of the guild. Could beNonefor no description.icon (
bytes) – A bytes-like object representing the icon. Only PNG/JPEG is supported. GIF is only available to guilds that containANIMATED_ICONinGuild.features. Could beNoneto denote removal of the icon.banner (
bytes) – A bytes-like object representing the banner. Only PNG/JPEG is supported. GIF is only available to guilds that containANIMATED_BANNERinGuild.features. Could beNoneto denote removal of the banner. This is only available to guilds that containBANNERinGuild.features.splash (
bytes) – A bytes-like object representing the invite splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containINVITE_SPLASHinGuild.features.discovery_splash (
bytes) –A bytes-like object representing the discovery splash. Only PNG/JPEG supported. Could be
Noneto denote removing the splash. This is only available to guilds that containDISCOVERABLEinGuild.features.New in version 2.0.
community (
bool) –Whether the guild should be a Community guild. If set to
True, bothrules_channelandpublic_updates_channelparameters are required.New in version 2.0.
afk_channel (Optional[
VoiceChannel]) – The new channel that is the AFK channel. Could beNonefor no AFK channel.afk_timeout (
int) – The number of seconds until someone is moved to the AFK channel.owner (
Member) – The new owner of the guild to transfer ownership to. Note that you must be owner of the guild to do this.verification_level (
VerificationLevel) – The new verification level for the guild.default_notifications (
NotificationLevel) – The new default notification level for the guild.explicit_content_filter (
ContentFilter) – The new explicit content filter for the guild.vanity_code (
str) – The new vanity code for the guild.system_channel (Optional[
TextChannel]) – The new channel that is used for the system channel. Could beNonefor no system channel.system_channel_flags (
SystemChannelFlags) – The new system channel settings to use with the new system channel.preferred_locale (
Locale) –The new preferred locale for the guild. Used as the primary language in the guild.
Changed in version 2.0: Now accepts an enum instead of
str.rules_channel (Optional[
TextChannel]) –The new channel that is used for rules. This is only available to guilds that contain
COMMUNITYinGuild.features. Could beNonefor no rules channel.New in version 1.4.
public_updates_channel (Optional[
TextChannel]) –The new channel that is used for public updates from Discord. This is only available to guilds that contain
COMMUNITYinGuild.features. Could beNonefor no public updates channel.New in version 1.4.
premium_progress_bar_enabled (
bool) –Whether the premium AKA server boost level progress bar should be enabled for the guild.
New in version 2.0.
discoverable (
bool) –Whether server discovery is enabled for this guild.
New in version 2.0.
invites_disabled (
bool) –Whether joining via invites should be disabled for the guild.
New in version 2.0.
widget_enabled (
bool) –Whether to enable the widget for the guild.
New in version 2.0.
widget_channel (Optional[
abc.Snowflake]) –The new widget channel.
Noneremoves the widget channel.New in version 2.0.
mfa_level (
MFALevel) –The guild’s new Multi-Factor Authentication requirement level. Note that you must be owner of the guild to do this.
New in version 2.0.
reason (Optional[
str]) – The reason for editing this guild. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to edit the guild.
HTTPException – Editing the guild failed.
ValueError – The image format passed in to
iconis invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer.TypeError – The type passed to the
default_notifications,verification_level,explicit_content_filter,system_channel_flags, ormfa_levelparameter was of the incorrect type.
- Returns
The newly updated guild. Note that this has the same limitations as mentioned in
Client.fetch_guild()and may not have full data.- Return type
- await fetch_channels()¶
This function is a coroutine.
Retrieves all
abc.GuildChannelthat the guild has.Note
This method is an API call. For general usage, consider
channelsinstead.New in version 1.2.
- Raises
InvalidData – An unknown channel type was received from Discord.
HTTPException – Retrieving the channels failed.
- Returns
All channels in the guild.
- Return type
Sequence[
abc.GuildChannel]
- await fetch_member(member_id, /)¶
This function is a coroutine.
Retrieves a
Memberfrom a guild ID, and a member ID.Note
This method is an API call. If you have member cache, consider
get_member()instead.Changed in version 2.0:
member_idparameter is now positional-only.- Parameters
member_id (
int) – The member’s ID to fetch from.- Raises
Forbidden – You do not have access to the guild.
HTTPException – Fetching the member failed.
NotFound – The member could not be found.
- Returns
The member from the member ID.
- Return type
- await fetch_member_profile(member_id, /, *, with_mutual_guilds=True, with_mutual_friends_count=False, with_mutual_friends=True)¶
This function is a coroutine.
Retrieves a
MemberProfilefrom a guild ID, and a member ID.New in version 2.0.
- Parameters
member_id (
int) – The ID of the member to fetch their profile for.with_mutual_guilds (
bool) – Whether to fetch mutual guilds. This fills inMemberProfile.mutual_guilds.with_mutual_friends_count (
bool) – Whether to fetch the number of mutual friends. This fills inMemberProfile.mutual_friends_count.with_mutual_friends (
bool) – Whether to fetch mutual friends. This fills inMemberProfile.mutual_friendsandMemberProfile.mutual_friends_count, but requires an extra API call.
- Raises
NotFound – A user with this ID does not exist.
Forbidden – You do not have a mutual with this user, and and the user is not a bot.
HTTPException – Fetching the profile failed.
InvalidData – The member is not in this guild or has blocked you.
- Returns
The profile of the member.
- Return type
- await fetch_ban(user)¶
This function is a coroutine.
Retrieves the
BanEntryfor a user.You must have
ban_membersto get this information.- Parameters
user (
abc.Snowflake) – The user to get ban information from.- Raises
Forbidden – You do not have proper permissions to get the information.
NotFound – This user is not banned.
HTTPException – An error occurred while fetching the information.
- Returns
The
BanEntryobject for the specified user.- Return type
- await fetch_channel(channel_id, /)¶
This function is a coroutine.
Retrieves a
abc.GuildChannelorThreadwith the specified ID.Note
This method is an API call. For general usage, consider
get_channel_or_thread()instead.New in version 2.0.
- Raises
InvalidData – An unknown channel type was received from Discord or the guild the channel belongs to is not the same as the one in this object points to.
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,Thread]
- async for ... in bans(*, limit=1000, before=..., after=..., paginate=True)¶
Retrieves an asynchronous iterator of the users that are banned from the guild as a
BanEntry.You must have
ban_membersto get this information.Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.
Examples
Usage
async for entry in guild.bans(limit=150): print(entry.user, entry.reason)
Flattening into a list
bans = [entry async for entry in guild.bans(limit=2000)] # bans is now a list of BanEntry...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of bans to retrieve. IfNone, it retrieves every ban in the guild. Note, however, that this would make it a slow operation. Defaults to1000.before (
abc.Snowflake) – Retrieves bans before this user.after (
abc.Snowflake) – Retrieve bans after this user.paginate (
bool) –Whether to paginate the results. If
False, all bans are fetched with a single request and yielded,limitis ignored, andbeforeandaftermust not be provided.New in version 2.0.
- Raises
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
TypeError – Both
afterandbeforewere provided, as Discord does not support this type of pagination.
- Yields
BanEntry– The ban entry of the banned user.
- await prune_members(*, days, compute_prune_count=True, roles=..., reason=None)¶
This function is a coroutine.
Prunes the guild from its inactive members.
The inactive members are denoted if they have not logged on in
daysnumber of days and they have no roles.You must have
kick_membersto do this.To check how many members you would prune without actually pruning, see the
estimate_pruned_members()function.To prune members that have specific roles see the
rolesparameter.Changed in version 1.4: The
roleskeyword-only parameter was added.Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
days (
int) – The number of days before counting as inactive.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.compute_prune_count (
bool) – Whether to compute the prune count. This defaults toTruewhich makes it prone to timeouts in very large guilds. In order to prevent timeouts, you must set this toFalse. If this is set toFalse, then this function will always returnNone.roles (List[
abc.Snowflake]) – A list ofabc.Snowflakethat represent roles to include in the pruning process. If a member has a role that is not specified, they’ll be excluded.
- Raises
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while pruning members.
TypeError – An integer was not passed for
days.
- Returns
The number of members pruned. If
compute_prune_countisFalsethen this returnsNone.- Return type
Optional[
int]
- await templates()¶
This function is a coroutine.
Gets the list of templates from this guild.
You must have
manage_guildto do this.New in version 1.7.
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this guild.
You must have
manage_webhooksto do this.
- await estimate_pruned_members(*, days, roles=...)¶
This function is a coroutine.
Similar to
prune_members()except instead of actually pruning members, it returns how many members it would prune from the guild had it been called.Changed in version 2.0: The returned value can be
None.Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
days (
int) – The number of days before counting as inactive.roles (List[
abc.Snowflake]) –A list of
abc.Snowflakethat represent roles to include in the estimate. If a member has a role that is not specified, they’ll be excluded.New in version 1.7.
- Raises
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while fetching the prune members estimate.
TypeError – An integer was not passed for
days.
- Returns
The number of members estimated to be pruned.
- Return type
Optional[
int]
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from the guild.
You must have
manage_guildto get this information.- Raises
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns
The list of invites that are currently active.
- Return type
List[
Invite]
- await create_template(*, name, description=...)¶
This function is a coroutine.
Creates a template for the guild.
You must have
manage_guildto do this.New in version 1.7.
- await create_integration(*, type, id, reason=None)¶
This function is a coroutine.
Attaches an integration to the guild. This “enables” an existing integration.
You must have
manage_guildto do this.New in version 1.4.
- Parameters
- Raises
Forbidden – You do not have permission to create the integration.
HTTPException – The account could not be found.
- await integrations(*, with_applications=True)¶
This function is a coroutine.
Returns a list of all integrations attached to the guild.
You must have
manage_guildto do this.New in version 1.4.
- Parameters
with_applications (
bool) – Whether to include applications.- Raises
Forbidden – You do not have permission to create the integration.
HTTPException – Fetching the integrations failed.
- Returns
The list of integrations that are attached to the guild.
- Return type
List[
Integration]
- await fetch_stickers()¶
This function is a coroutine.
Retrieves a list of all
Stickers for the guild.New in version 2.0.
Note
This method is an API call. For general usage, consider
stickersinstead.- Raises
HTTPException – An error occurred fetching the stickers.
- Returns
The retrieved stickers.
- Return type
List[
GuildSticker]
- await fetch_sticker(sticker_id, /)¶
This function is a coroutine.
Retrieves a custom
Stickerfrom the guild.New in version 2.0.
Note
This method is an API call. For general usage, consider iterating over
stickersinstead.- Parameters
sticker_id (
int) – The sticker’s ID.- Raises
NotFound – The sticker requested could not be found.
HTTPException – An error occurred fetching the sticker.
- Returns
The retrieved sticker.
- Return type
- await create_sticker(*, name, description, emoji, file, reason=None)¶
This function is a coroutine.
Creates a
Stickerfor the guild.You must have
manage_emojis_and_stickersto do this.New in version 2.0.
- Parameters
name (
str) – The sticker name. Must be at least 2 characters.description (
str) – The sticker’s description.emoji (
str) – The name of a unicode emoji that represents the sticker’s expression.file (
File) – The file of the sticker to upload.reason (
str) – The reason for creating this sticker. Shows up on the audit log.
- Raises
Forbidden – You are not allowed to create stickers.
HTTPException – An error occurred creating a sticker.
- Returns
The created sticker.
- Return type
- await delete_sticker(sticker, /, *, reason=None)¶
This function is a coroutine.
Deletes the custom
Stickerfrom the guild.You must have
manage_emojis_and_stickersto do this.New in version 2.0.
- Parameters
sticker (
abc.Snowflake) – The sticker you are deleting.reason (Optional[
str]) – The reason for deleting this sticker. Shows up on the audit log.
- Raises
Forbidden – You are not allowed to delete stickers.
HTTPException – An error occurred deleting the sticker.
- await fetch_scheduled_events(*, with_counts=True)¶
This function is a coroutine.
Retrieves a list of all scheduled events for the guild.
New in version 2.0.
- Parameters
with_counts (
bool) – Whether to include the number of users that are subscribed to the event. Defaults toTrue.- Raises
HTTPException – Retrieving the scheduled events failed.
- Returns
The scheduled events.
- Return type
List[
ScheduledEvent]
- await fetch_scheduled_event(scheduled_event_id, /, *, with_counts=True)¶
This function is a coroutine.
Retrieves a scheduled event from the guild.
New in version 2.0.
- Parameters
- Raises
NotFound – The scheduled event was not found.
HTTPException – Retrieving the scheduled event failed.
- Returns
The scheduled event.
- Return type
- await create_scheduled_event(*, name, start_time, entity_type=..., privacy_level=..., channel=..., location=..., end_time=..., description=..., image=..., reason=None)¶
This function is a coroutine.
Creates a scheduled event for the guild.
You must have
manage_eventsto do this.New in version 2.0.
- Parameters
name (
str) – The name of the scheduled event.description (
str) – The description of the scheduled event.channel (Optional[
abc.Snowflake]) –The channel to send the scheduled event to. If the channel is a
StageInstanceorVoiceChannelthen it automatically sets the entity type.Required if
entity_typeis eitherEntityType.voiceorEntityType.stage_instance.start_time (
datetime.datetime) – The scheduled start time of the scheduled event. This must be a timezone-aware datetime object. Consider usingutils.utcnow().end_time (
datetime.datetime) –The scheduled end time of the scheduled event. This must be a timezone-aware datetime object. Consider using
utils.utcnow().Required if the entity type is
EntityType.external.privacy_level (
PrivacyLevel) – The privacy level of the scheduled event.entity_type (
EntityType) – The entity type of the scheduled event. If the channel is aStageInstanceorVoiceChannelthen this is automatically set to the appropriate entity type. If no channel is passed then the entity type is assumed to beEntityType.externalimage (
bytes) – The image of the scheduled event.location (
str) –The location of the scheduled event.
Required if the
entity_typeisEntityType.external.reason (Optional[
str]) – The reason for creating this scheduled event. Shows up on the audit log.
- Raises
TypeError –
imagewas not a bytes-like object, orprivacy_levelwas not aPrivacyLevel, orentity_typewas not anEntityType,statuswas not anEventStatus, or an argument was provided that was incompatible with the providedentity_type.ValueError –
start_timeorend_timewas not a timezone-aware datetime object.Forbidden – You are not allowed to create scheduled events.
HTTPException – Creating the scheduled event failed.
- Returns
The created scheduled event.
- Return type
- await top_emojis()¶
This function is a coroutine.
Retrieves the most used custom emojis in the guild. Emojis are returned in order of descending usage.
New in version 2.0.
- Raises
HTTPException – Retrieving the top emojis failed.
- Returns
The most used emojis. Falls back to a bare
PartialEmojiif the emoji is not found in cache.- Return type
List[Union[
Emoji,PartialEmoji]]
- await fetch_emojis()¶
This function is a coroutine.
Retrieves all custom
Emojis from the guild.Note
This method is an API call. For general usage, consider
emojisinstead.- Raises
HTTPException – An error occurred fetching the emojis.
- Returns
The retrieved emojis.
- Return type
List[
Emoji]
- await fetch_emoji(emoji_id, /)¶
This function is a coroutine.
Retrieves a custom
Emojifrom the guild.Note
This method is an API call. For general usage, consider iterating over
emojisinstead.Changed in version 2.0:
emoji_idparameter is now positional-only.- Parameters
emoji_id (
int) – The emoji’s ID.- Raises
NotFound – The emoji requested could not be found.
HTTPException – An error occurred fetching the emoji.
- Returns
The retrieved emoji.
- Return type
- await create_custom_emoji(*, name, image, roles=..., reason=None)¶
This function is a coroutine.
Creates a custom
Emojifor the guild.There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the
MORE_EMOJIfeature which extends the limit to 200.You must have
manage_emojisto do this.- Parameters
name (
str) – The emoji name. Must be at least 2 characters.image (
bytes) – The bytes-like object representing the image data to use. Only JPG, PNG and GIF images are supported.roles (List[
Role]) – AlistofRoles that can use this emoji. Leave empty to make it available to everyone.reason (Optional[
str]) – The reason for creating this emoji. Shows up on the audit log.
- Raises
Forbidden – You are not allowed to create emojis.
HTTPException – An error occurred creating an emoji.
- Returns
The created emoji.
- Return type
- await delete_emoji(emoji, /, *, reason=None)¶
This function is a coroutine.
Deletes the custom
Emojifrom the guild.You must have
manage_emojisto do this.Changed in version 2.0:
emojiparameter is now positional-only.- Parameters
emoji (
abc.Snowflake) – The emoji you are deleting.reason (Optional[
str]) – The reason for deleting this emoji. Shows up on the audit log.
- Raises
Forbidden – You are not allowed to delete emojis.
HTTPException – An error occurred deleting the emoji.
- await fetch_roles()¶
This function is a coroutine.
Retrieves all
Rolethat the guild has.Note
This method is an API call. For general usage, consider
rolesinstead.New in version 1.3.
- Raises
HTTPException – Retrieving the roles failed.
- Returns
All roles in the guild.
- Return type
List[
Role]
- await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., display_icon=..., mentionable=..., icon=..., emoji=..., reason=None)¶
This function is a coroutine.
Creates a
Rolefor the guild.All fields are optional.
You must have
manage_rolesto do this.Changed in version 1.6: Can now pass
inttocolourkeyword-only parameter.New in version 2.0: The
display_iconkeyword-only parameter was added.Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
name (
str) – The role name. Defaults to ‘new role’.permissions (
Permissions) – The permissions to have. Defaults to no permissions.colour (Union[
Colour,int]) – The colour for the role. Defaults toColour.default(). This is aliased tocoloras well.hoist (
bool) – Indicates if the role should be shown separately in the member list. Defaults toFalse.display_icon (Union[
bytes,str]) – A bytes-like object representing the icon orstrrepresenting unicode emoji that should be used as a role icon. Only PNG/JPEG is supported. This is only available to guilds that containROLE_ICONSinfeatures.mentionable (
bool) – Indicates if the role should be mentionable by others. Defaults toFalse.icon (Optional[
bytes]) – A bytes-like object representing the icon. Only PNG/JPEG is supported. Could beNoneto denote removal of the icon.emoji (Optional[
PartialEmoji]) – An emoji to show next to the role. Only unicode emojis are supported.reason (Optional[
str]) – The reason for creating this role. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to create the role.
HTTPException – Creating the role failed.
TypeError – An invalid keyword argument was given.
ValueError – unicode_emoji was the wrong type.
- Returns
The newly created role.
- Return type
- await edit_role_positions(positions, *, reason=None)¶
This function is a coroutine.
Bulk edits a list of
Rolein the guild.You must have
manage_rolesto do this.New in version 1.4.
Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.Example
positions = { bots_role: 1, # penultimate role tester_role: 2, admin_role: 6 } await guild.edit_role_positions(positions=positions)
- Parameters
- Raises
Forbidden – You do not have permissions to move the roles.
HTTPException – Moving the roles failed.
TypeError – An invalid keyword argument was given.
- Returns
A list of all the roles in the guild.
- Return type
List[
Role]
- await kick(user, *, reason=None)¶
This function is a coroutine.
Kicks a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have
kick_membersto do this.- Parameters
user (
abc.Snowflake) – The user to kick from their guild.reason (Optional[
str]) – The reason the user got kicked.
- Raises
Forbidden – You do not have the proper permissions to kick.
HTTPException – Kicking failed.
- await ban(user, *, reason=None, delete_message_days=..., delete_message_seconds=...)¶
This function is a coroutine.
Bans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have
ban_membersto do this.- Parameters
user (
abc.Snowflake) – The user to ban from their guild.delete_message_days (
int) –The number of days worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 7. Defaults to 1 day if neither
delete_message_daysnordelete_message_secondsare passed.Deprecated since version 2.0.
delete_message_seconds (
int) –The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (7 days). Defaults to 1 day if neither
delete_message_daysnordelete_message_secondsare passed.New in version 2.0.
reason (Optional[
str]) – The reason the user got banned.
- Raises
NotFound – The requested user was not found.
Forbidden – You do not have the proper permissions to ban.
HTTPException – Banning failed.
TypeError – You specified both
delete_message_daysanddelete_message_seconds.
- await unban(user, *, reason=None)¶
This function is a coroutine.
Unbans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have
ban_membersto do this.- Parameters
user (
abc.Snowflake) – The user to unban.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises
NotFound – The requested unban was not found.
Forbidden – You do not have the proper permissions to unban.
HTTPException – Unbanning failed.
- property vanity_url¶
The Discord vanity invite URL for this guild, if available.
New in version 2.0.
- Type
Optional[
str]
- await vanity_invite()¶
This function is a coroutine.
Returns the guild’s special vanity invite.
The guild must have
VANITY_URLinfeatures.You must have
manage_guildto do this.as well.- Raises
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the vanity invite failed.
- Returns
The special vanity invite. If
Nonethen the guild does not have a vanity invite set.- Return type
Optional[
Invite]
- async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)¶
Returns an asynchronous iterator that enables receiving the guild’s audit logs.
You must have
view_audit_logto do this.Examples
Getting the first 100 entries:
async for entry in guild.audit_logs(limit=100): print(f'{entry.user} did {entry.action} to {entry.target}')
Getting entries for a specific action:
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban): print(f'{entry.user} banned {entry.target}')
Getting entries made by a specific user:
entries = [entry async for entry in guild.audit_logs(limit=None, user=guild.me)] await channel.send(f'I made {len(entries)} moderation actions.')
- Parameters
limit (Optional[
int]) – The number of entries to retrieve. IfNoneretrieve all entries.before (Union[
abc.Snowflake,datetime.datetime]) – Retrieve entries before this date or entry. 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 entries after this date or entry. 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.oldest_first (
bool) – If set toTrue, return entries in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.user (
abc.Snowflake) – The moderator to filter entries from.action (
AuditLogAction) – The action to filter with.
- Raises
Forbidden – You are not allowed to fetch audit logs
HTTPException – An error occurred while fetching the audit logs.
- Yields
AuditLogEntry– The audit log entry.
- await ack()¶
This function is a coroutine.
Marks every message in this guild as read.
- Raises
HTTPException – Acking failed.
- await widget()¶
This function is a coroutine.
Returns the widget of the guild.
Note
The guild must have the widget enabled to get this information.
- Raises
Forbidden – The widget for this guild is disabled.
HTTPException – Retrieving the widget failed.
- Returns
The guild’s widget.
- Return type
- await edit_widget(*, enabled=..., channel=..., reason=None)¶
This function is a coroutine.
Edits the widget of the guild. This can also be done with
edit.You must have
manage_guildto do this.New in version 2.0.
- Parameters
- Raises
Forbidden – You do not have permission to edit the widget.
HTTPException – Editing the widget failed.
- await welcome_screen()¶
This function is a coroutine.
Returns the guild’s welcome screen.
You must have
manage_guildpermission to use this.Note
The guild must have the welcome screen enabled to get this information.
New in version 2.0.
- Raises
NotFound – The guild does not have a welcome screen.
Forbidden – You do not have
manage_guild.HTTPException – Retrieving the welcome screen failed.
- Returns
The welcome screen.
- Return type
- await edit_welcome_screen(*, description=..., welcome_channels=..., enabled=..., reason=None)¶
This function is a coroutine.
Edit the welcome screen.
Welcome channels can only accept custom emojis if
Guild.premium_tieris level 2 or above.You must have
manage_guildin the guild to do this.All parameters are optional.
New in version 2.0.
Usage:
rules_channel = guild.get_channel(12345678) announcements_channel = guild.get_channel(87654321) custom_emoji = utils.get(guild.emojis, name='loudspeaker') await welcome_screen.edit( description='This is a very cool community server!', welcome_channels=[ WelcomeChannel(channel=rules_channel, description='Read the rules!', emoji='👨🏫'), WelcomeChannel(channel=announcements_channel, description='Watch out for announcements!', emoji=custom_emoji), ] )
- Parameters
enabled (
bool) – Whether the welcome screen will be shown.description (
str) – The welcome screen’s description.welcome_channels (Optional[List[
WelcomeChannel]]) – The welcome channels (in order).reason (Optional[
str]) – The reason for editing the welcome screen. Shows up on the audit log.
- Raises
NotFound – The guild does not have a welcome screen.
HTTPException – Editing the welcome screen failed failed.
Forbidden – You don’t have permissions to edit the welcome screen.
- await applications(*, with_team=False, type=None, channel=None)¶
This function is a coroutine.
Returns the list of applications that are attached to this guild.
New in version 2.0.
- Parameters
with_team (
bool) – Whether to include the team of the application.type (
ApplicationType) – The type of application to restrict the returned applications to.
- Raises
HTTPException – Fetching the applications failed.
- Returns
The applications that belong to this guild.
- Return type
List[
PartialApplication]
This function is a coroutine.
Returns the list of premium subscriptions (boosts) for this guild.
New in version 2.0.
- Raises
Forbidden – You do not have permission to get the premium guild subscriptions.
HTTPException – Fetching the premium guild subscriptions failed.
- Returns
The premium guild subscriptions.
- Return type
List[
PremiumGuildSubscription]
This function is a coroutine.
Applies premium subscription slots to the guild (boosts the guild).
New in version 2.0.
- Parameters
*subscription_slots (
PremiumGuildSubscriptionSlot) – The subscription slots to apply.- Raises
HTTPException – Applying the premium subscription slots failed.
- await entitlements(*, with_sku=True, with_application=True, exclude_deleted=False)¶
This function is a coroutine.
Returns the list of entitlements for this guild.
New in version 2.0.
- Parameters
- Raises
HTTPException – Retrieving the entitlements failed.
- Returns
The guild’s entitlements.
- Return type
List[
Entitlement]
- await price_tiers()¶
This function is a coroutine.
Returns the list of price tiers available for use in this guild.
New in version 2.0.
- Raises
HTTPException – Fetching the price tiers failed.
- Returns
The available price tiers.
- Return type
List[
int]
- await fetch_price_tier(price_tier, /)¶
This function is a coroutine.
Returns a mapping of currency to price for the given price tier.
New in version 2.0.
- Parameters
price_tier (
int) – The price tier to retrieve.- Raises
NotFound – The price tier does not exist.
HTTPException – Fetching the price tier failed.
- Returns
The price tier mapping.
- Return type
- await chunk(channel=...)¶
This function is a coroutine.
Requests all members that belong to this guild. This is a websocket operation and can be slow.
New in version 2.0.
Note
This can only be used on guilds with less than 1000 members.
- Parameters
channel (
Snowflake) – The channel to request members from.- Raises
ClientException – This guild cannot be chunked or chunking failed. Guild is no longer available.
InvalidData – Did not receive a response from the gateway.
- Returns
The members that belong to this guild.
- Return type
List[
Member]
- await fetch_members(channels=..., *, cache=True, force_scraping=False, delay=1)¶
This function is a coroutine.
Retrieves all members that belong to this guild. This is a websocket operation and can be slow.
This does not enable you to receive events for the guild, and can be called multiple times.
New in version 2.0.
Note
If you are the owner, have either of
administrator,kick_members,ban_members, ormanage_roles, permissions will be fetched through OPcode 8 (this includes offline members). Else, they will be scraped from the member sidebar.- Parameters
channels (List[
Snowflake]) – A list of up to 5 channels to request members from. More channels make it faster. This only applies when scraping from the member sidebar.cache (
bool) – Whether to cache the members as well. The cache will not be kept updated.force_scraping (
bool) – Whether to scrape the member sidebar regardless of permissions.delay (Union[
int,float]) – The time in seconds to wait between requests. This only applies when scraping from the member sidebar.
- Raises
ClientException – Fetching members failed. Guild is no longer available.
InvalidData – Did not receive a response from the gateway.
- Returns
The members that belong to this guild (offline members may not be included).
- Return type
List[
Member]
- await query_members(query=None, *, limit=5, user_ids=None, presences=True, cache=True, subscribe=False)¶
This function is a coroutine.
Request members of this guild whose username or nickname starts with the given query. This is a websocket operation.
Note
This is preferrable to using
fetch_member()as the client uses it quite often, and you can also request presence.New in version 1.3.
Changed in version 2.0: The function now raises a
TypeErrorinstead of ValueError.- Parameters
query (Optional[
str]) – The string that the username or nickname should start with.limit (
int) – The maximum number of members to send back. This must be a number between 5 and 100.presences (
bool) –Whether to request for presences to be provided. This defaults to
True.New in version 1.6.
cache (
bool) – Whether to cache the members internally. This makes operations such asget_member()work for those that matched.user_ids (Optional[List[
int]]) –List of user IDs to search for. If the user ID is not in the guild then it won’t be returned.
New in version 1.4.
subscribe (
bool) –Whether to subscribe to the resulting members. This will keep their info and presence updated. This requires another request, and defaults to
False.New in version 2.0.
- Raises
asyncio.TimeoutError – The query timed out waiting for the members.
TypeError – Invalid parameters were passed to the function.
- Returns
The list of members that have matched the query.
- Return type
List[
Member]
- await change_voice_state(*, channel, self_mute=False, self_deaf=False, self_video=False, preferred_region=...)¶
This function is a coroutine.
Changes client’s voice state in the guild.
New in version 1.4.
- Parameters
channel (Optional[
abc.Snowflake]) – Channel the client wants to join. UseNoneto disconnect.self_mute (
bool) – Indicates if the client should be self-muted.self_deaf (
bool) – Indicates if the client should be self-deafened.self_video (
bool) – Indicates if the client is using video. Untested & unconfirmed (do not use).preferred_region (Optional[
str]) –The preferred region to connect to.
Changed in version 2.0: The type of this parameter has changed to
str.
- await request(**kwargs)¶
This function is a coroutine.
Request a guild. This is required to receive most events for large guilds.
New in version 2.0.
Note
This is done automatically by default, so you do not need to perform this operation unless you passed
request_guilds=Falseto yourClient.
- await automod_rules()¶
This function is a coroutine.
Fetches all automod rules from the guild.
You must have
Permissions.manage_guildto do this.New in version 2.0.
- Raises
- Returns
The automod rules that were fetched.
- Return type
List[
AutoModRule]
- await fetch_automod_rule(automod_rule_id, /)¶
This function is a coroutine.
Fetches an active automod rule from the guild.
You must have
Permissions.manage_guildto do this.New in version 2.0.
- await create_automod_rule(*, name, event_type, trigger, actions, enabled=False, exempt_roles=..., exempt_channels=..., reason=...)¶
This function is a coroutine.
Create an automod rule.
You must have
Permissions.manage_guildto do this.New in version 2.0.
- Parameters
name (
str) – The name of the automod rule.event_type (
AutoModRuleEventType) – The type of event that the automod rule will trigger on.trigger (
AutoModTrigger) – The trigger that will trigger the automod rule.actions (List[
AutoModRuleAction]) – The actions that will be taken when the automod rule is triggered.enabled (
bool) – Whether the automod rule is enabled. Defaults toFalse.exempt_roles (Sequence[
abc.Snowflake]) – A list of roles that will be exempt from the automod rule.exempt_channels (Sequence[
abc.Snowflake]) – A list of channels that will be exempt from the automod rule.reason (
str) – The reason for creating this automod rule. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to create an automod rule.
HTTPException – Creating the automod rule failed.
- Returns
The automod rule that was created.
- Return type
- defis_joined
- class discord.UserGuild¶
Represents a partial joined guild.
- x == y
Checks if two guilds are equal.
- x != y
Checks if two guilds are not equal.
- hash(x)
Returns the guild’s hash.
- str(x)
Returns the guild’s name.
New in version 2.0.
- features¶
A list of features that the guild has. The features that a guild can have are subject to arbitrary change by Discord.
- Type
List[
str]
- approximate_member_count¶
The approximate number of members in the guild. This is
Noneunless the guild is obtained usingClient.fetch_guilds()withwith_counts=True.- Type
Optional[
int]
- approximate_presence_count¶
The approximate number of members currently active in the guild. Offline members are excluded. This is
Noneunless the guild is obtained usingClient.fetch_guilds()withwith_counts=True.- Type
Optional[
int]
- property permissions¶
Returns the calculated permissions the current user has in the guild.
- Type
- class discord.MutualGuild¶
Represents a mutual guild between a user and the client user.
- x == y
Checks if two guilds are equal.
- x != y
Checks if two guilds are not equal.
- hash(x)
Returns the guild’s hash.
New in version 2.0.
Role¶
- asyncadd_members
- asyncdelete
- asyncedit
- asyncfetch_members
- defis_assignable
- defis_bot_managed
- defis_default
- defis_integration
- defis_premium_subscriber
- asyncremove_members
- class discord.Role¶
Represents a Discord role in a
Guild.- x == y
Checks if two roles are equal.
- x != y
Checks if two roles are not equal.
- x > y
Checks if a role is higher than another in the hierarchy.
- x < y
Checks if a role is lower than another in the hierarchy.
- x >= y
Checks if a role is higher or equal to another in the hierarchy.
- x <= y
Checks if a role is lower or equal to another in the hierarchy.
- hash(x)
Return the role’s hash.
- str(x)
Returns the role’s name.
- position¶
The position of the role. This number is usually positive. The bottom role has a position of 0.
Warning
Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.
- Type
- unicode_emoji¶
The role’s unicode emoji, if available.
Note
If
iconis notNone, it is displayed as role icon instead of the unicode emoji under this attribute.If you want the icon that a role has displayed, consider using
display_icon.New in version 2.0.
- Type
Optional[
str]
- managed¶
Indicates if the role is managed by the guild through some form of integrations such as Twitch.
- Type
bool: Whether the role is the premium subscriber, AKA “boost”, role for the guild.New in version 1.6.
- is_assignable()¶
bool: Whether the role is able to be assigned or removed by the bot.New in version 2.0.
- property permissions¶
Returns the role’s permissions.
- Type
- property icon¶
Returns the role’s icon asset, if available.
Note
If this is
None, the role might instead have unicode emoji as its icon ifunicode_emojiis notNone.If you want the icon that a role has displayed, consider using
display_icon.New in version 2.0.
- Type
Optional[
Asset]
- property display_icon¶
Returns the role’s display icon, if available.
New in version 2.0.
- property created_at¶
Returns the role’s creation time in UTC.
- Type
- await fetch_members(*, subscribe=False)¶
This function is a coroutine.
Retrieves all members with this role. This is a partial websocket operation.
New in version 2.0.
Note
This can only return up to 100 of the first members, and cannot be used on the default role.
- Parameters
subscribe (
bool) – Whether to subscribe to the resulting members. This will keep their info and presence updated. This requires another request, and defaults toFalse.- Raises
HTTPException – Fetching the members failed.
TypeError – This role is the default role.
asyncio.TimeoutError – The operation timed out.
- Returns
The members with this role.
- Return type
List[
Member]
- await add_members(*members, reason=None)¶
This function is a coroutine.
Adds a number of
Members to this role.You must have
manage_rolesto use this, and the currentRolemust appear lower in the list of roles than the highest role of the member.- Parameters
*members (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aMemberto add to the role.reason (Optional[
str]) – The reason for adding these members. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to add these members.
HTTPException – Adding members failed.
TypeError – The role is the default role.
- Returns
The list of members that were added to the role.
- Return type
List[
Member]
- await remove_members(*members, reason=None)¶
This function is a coroutine.
Removes
Members from this role.You must have
manage_rolesto use this, and the currentRolemust appear lower in the list of roles than the highest role of the member.- Parameters
*members (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aMemberto remove from the role.reason (Optional[
str]) – The reason for adding these members. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to remove these members.
HTTPException – Removing the members failed.
TypeError – The role is the default role.
- await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., display_icon=..., icon=..., unicode_emoji=..., mentionable=..., position=..., reason=...)¶
This function is a coroutine.
Edits the role.
You must have
manage_rolesto do this.All fields are optional.
Changed in version 1.4: Can now pass
inttocolourkeyword-only parameter.Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead.
New in version 2.0: The
display_icon,icon, andunicode_emojikeyword-only parameters were added.Changed in version 2.0: This function will now raise
ValueErrorinstead ofInvalidArgument.- Parameters
name (
str) – The new role name to change to.permissions (
Permissions) – The new permissions to change to.colour (Union[
Colour,int]) – The new colour to change to. (aliased to color as well)hoist (
bool) – Indicates if the role should be shown separately in the member list.display_icon (Optional[Union[
bytes,str]]) – A bytes-like object representing the icon orstrrepresenting unicode emoji that should be used as a role icon. Could beNoneto denote removal of the icon. Only PNG/JPEG is supported. This is only available to guilds that containROLE_ICONSinGuild.features.icon (Optional[
bytes]) – A bytes-like object representing the icon that should be used as a role icon. Could beNoneto denote removal of the icon. Only PNG/JPEG is supported. This is only available to guilds that containROLE_ICONSinGuild.features.unicode_emoji (Optional[
str]) – A unicode emoji that should be used as a role icon.icontakes precedence over this, but both can be set. This is only available to guilds that containROLE_ICONSinGuild.features.mentionable (
bool) – Indicates if the role should be mentionable by others.position (
int) – The new role’s position. This must be below your top role’s position or it will fail.reason (Optional[
str]) – The reason for editing this role. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to change the role.
HTTPException – Editing the role failed.
ValueError – An invalid position was given, the default role was asked to be moved, or both
display_iconandicon/unicode_emojiwere set.
- Returns
The newly edited role.
- Return type
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the role.
You must have
manage_rolesto do this.- Parameters
reason (Optional[
str]) – The reason for deleting this role. Shows up on the audit log.- Raises
Forbidden – You do not have permissions to delete the role.
HTTPException – Deleting the role failed.
- class discord.RoleTags¶
Represents tags on a role.
A role tag is a piece of extra information attached to a managed role that gives it context for the reason the role is managed.
While this can be accessed, a useful interface is also provided in the
RoleandGuildclasses as well.New in version 1.6.
- subscription_listing_id¶
The ID of this role’s subscription SKU and listing.
New in version 2.0.
- Type
Optional[
int]
bool: Whether the role is the premium subscriber, AKA “boost”, role for the guild.
ScheduledEvent¶
- class discord.ScheduledEvent¶
Represents a scheduled event in a guild.
New in version 2.0.
- x == y
Checks if two scheduled events are equal.
- x != y
Checks if two scheduled events are not equal.
- hash(x)
Returns the scheduled event’s hash.
- entity_type¶
The type of entity this event is for.
- Type
- start_time¶
The time that the scheduled event will start in UTC.
- Type
- end_time¶
The time that the scheduled event will end in UTC.
- Type
Optional[
datetime.datetime]
- privacy_level¶
The privacy level of the scheduled event.
- Type
- status¶
The status of the scheduled event.
- Type
- creator_id¶
The ID of the user that created the scheduled event.
New in version 2.0.
- Type
Optional[
int]
- property channel¶
The channel this scheduled event is in.
- Type
Optional[Union[
VoiceChannel,StageChannel]]
- await start(*, reason=None)¶
This function is a coroutine.
Starts the scheduled event.
Shorthand for:
await event.edit(status=EventStatus.active)
- Parameters
reason (Optional[
str]) – The reason for starting the scheduled event.- Raises
ValueError – The scheduled event has already started or has ended.
Forbidden – You do not have the proper permissions to start the scheduled event.
HTTPException – The scheduled event could not be started.
- Returns
The scheduled event that was started.
- Return type
- await end(*, reason=None)¶
This function is a coroutine.
Ends the scheduled event.
Shorthand for:
await event.edit(status=EventStatus.completed)
- Parameters
reason (Optional[
str]) – The reason for ending the scheduled event.- Raises
ValueError – The scheduled event is not active or has already ended.
Forbidden – You do not have the proper permissions to end the scheduled event.
HTTPException – The scheduled event could not be ended.
- Returns
The scheduled event that was ended.
- Return type
- await cancel(*, reason=None)¶
This function is a coroutine.
Cancels the scheduled event.
Shorthand for:
await event.edit(status=EventStatus.cancelled)
- Parameters
reason (Optional[
str]) – The reason for cancelling the scheduled event.- Raises
ValueError – The scheduled event is already running.
Forbidden – You do not have the proper permissions to cancel the scheduled event.
HTTPException – The scheduled event could not be cancelled.
- Returns
The scheduled event that was cancelled.
- Return type
- await edit(*, name=..., description=..., channel=..., start_time=..., end_time=..., privacy_level=..., entity_type=..., status=..., image=..., location=..., reason=None)¶
This function is a coroutine.
Edits the scheduled event.
You must have
manage_eventsto do this.- Parameters
name (
str) – The name of the scheduled event.description (
str) – The description of the scheduled event.channel (Optional[
Snowflake]) –The channel to put the scheduled event in. If the channel is a
StageInstanceorVoiceChannelthen it automatically sets the entity type.Required if the entity type is either
EntityType.voiceorEntityType.stage_instance.start_time (
datetime.datetime) – The time that the scheduled event will start. This must be a timezone-aware datetime object. Consider usingutils.utcnow().end_time (Optional[
datetime.datetime]) –The time that the scheduled event will end. This must be a timezone-aware datetime object. Consider using
utils.utcnow().If the entity type is either
EntityType.voiceorEntityType.stage_instance, the end_time can be cleared by passingNone.Required if the entity type is
EntityType.external.privacy_level (
PrivacyLevel) – The privacy level of the scheduled event.entity_type (
EntityType) – The new entity type. If the channel is aStageInstanceorVoiceChannelthen this is automatically set to the appropriate entity type.status (
EventStatus) – The new status of the scheduled event.image (Optional[
bytes]) – The new image of the scheduled event orNoneto remove the image.location (
str) –The new location of the scheduled event.
Required if the entity type is
EntityType.external.reason (Optional[
str]) – The reason for editing the scheduled event. Shows up on the audit log.
- Raises
TypeError –
imagewas not a bytes-like object, orprivacy_levelwas not aPrivacyLevel, orentity_typewas not anEntityType,statuswas not anEventStatus, or an argument was provided that was incompatible with the scheduled event’s entity type.ValueError –
start_timeorend_timewas not a timezone-aware datetime object.Forbidden – You do not have permissions to edit the scheduled event.
HTTPException – Editing the scheduled event failed.
- Returns
The edited scheduled event.
- Return type
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the scheduled event.
You must have
manage_eventsto do this.- Parameters
reason (Optional[
str]) – The reason for deleting the scheduled event. Shows up on the audit log.- Raises
Forbidden – You do not have permissions to delete the scheduled event.
HTTPException – Deleting the scheduled event failed.
- async for ... in users(*, limit=None, before=None, after=None, oldest_first=...)¶
This function is a coroutine.
Retrieves all
Userthat are subscribed to this event.- Raises
HTTPException – Retrieving the members failed.
- Returns
All subscribed users of this event.
- Return type
List[
User]
Integration¶
- class discord.Integration¶
Represents a guild integration.
New in version 1.4.
- account¶
The account linked to this integration.
- Type
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the integration.
You must have
manage_guildto do this.- Parameters
reason (
str) –The reason the integration was deleted. Shows up on the audit log.
New in version 2.0.
- Raises
Forbidden – You do not have permission to delete the integration.
HTTPException – Deleting the integration failed.
- class discord.IntegrationAccount¶
Represents an integration account.
New in version 1.4.
- class discord.BotIntegration¶
Represents a bot integration on discord.
New in version 2.0.
- account¶
The integration account information.
- Type
- application¶
The application tied to this integration. Not available in some contexts.
- Type
Optional[
IntegrationApplication]
- class discord.StreamIntegration¶
Represents a stream integration for Twitch or YouTube.
New in version 2.0.
- enable_emoticons¶
Whether emoticons should be synced for this integration (currently twitch only).
- Type
- expire_behaviour¶
The behaviour of expiring subscribers. Aliased to
expire_behavioras well.- Type
- account¶
The integration account information.
- Type
- synced_at¶
An aware UTC datetime representing when the integration was last synced.
- Type
- property expire_behavior¶
An alias for
expire_behaviour.- Type
- await edit(*, expire_behaviour=..., expire_grace_period=..., enable_emoticons=...)¶
This function is a coroutine.
Edits the integration.
You must have
manage_guildto do this.- Parameters
expire_behaviour (
ExpireBehaviour) – The behaviour when an integration subscription lapses. Aliased toexpire_behavioras well.expire_grace_period (
int) – The period (in days) where the integration will ignore lapsed subscriptions.enable_emoticons (
bool) – Where emoticons should be synced for this integration (currently twitch only).
- Raises
Forbidden – You do not have permission to edit the integration.
HTTPException – Editing the guild failed.
- await sync()¶
This function is a coroutine.
Syncs the integration.
You must have
manage_guildto do this.- Raises
Forbidden – You do not have permission to sync the integration.
HTTPException – Syncing the integration failed.
- await disable(*, reason=None)¶
This function is a coroutine.
Disables the integration.
This is an alias of
Integration.delete().You must have
manage_guildto do this.- Parameters
reason (
str) – The reason the integration was disabled. Shows up on the audit log.- Raises
Forbidden – You do not have permission to disable the integration.
HTTPException – Disabling the integration failed.
- await enable(*, reason=None)¶
This function is a coroutine.
Enables the integration.
You must have
manage_guildto do this.- Parameters
reason (
str) – The reason the integration was enabled. Shows up on the audit log.- Raises
Forbidden – You do not have permission to enable the integration.
HTTPException – Enabling the integration failed.
- asyncactivity_statistics
- asyncassets
- asyncentitlement_ticket
- asyncentitlements
- asyncprimary_store_listing
- asyncpublished_store_listings
- asyncticket
- class discord.IntegrationApplication¶
Represents a very partial application received in integration/interaction contexts.
- x == y
Checks if two applications are equal.
- x != y
Checks if two applications are not equal.
- hash(x)
Return the application’s hash.
- str(x)
Returns the application’s name.
New in version 2.0.
- type¶
The type of application.
- Type
Optional[
ApplicationType]
- primary_sku_id¶
The application’s primary SKU ID, if any. This can be an application’s game SKU, subscription SKU, etc.
- Type
Optional[
int]
- 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.
- Type
Optional[
str]
- await assets()¶
This function is a coroutine.
Retrieves the assets of this application.
- Raises
HTTPException – Retrieving the assets failed.
- Returns
The application’s assets.
- Return type
List[
ApplicationAsset]
- await published_store_listings(*, localize=True)¶
This function is a coroutine.
Retrieves all published store listings for this application.
- Parameters
localize (
bool) – Whether to localize the store listings to the current user’s locale. IfFalsethen all localizations are returned.- Raises
HTTPException – Retrieving the listings failed.
- Returns
The store listings.
- Return type
List[
StoreListing]
- await primary_store_listing(*, localize=True)¶
This function is a coroutine.
Retrieves the primary store listing of this application.
This is the public store listing of the primary SKU.
- Parameters
localize (
bool) – Whether to localize the store listings to the current user’s locale. IfFalsethen all localizations are returned.- Raises
NotFound – The application does not have a primary SKU.
HTTPException – Retrieving the store listing failed.
- Returns
The application’s primary store listing, if any.
- Return type
- await entitlements(*, exclude_consumed=True)¶
This function is a coroutine.
Retrieves the entitlements this account has granted for this application.
- Parameters
exclude_consumed (
bool) – Whether to exclude consumed entitlements.- Raises
Forbidden – You do not have permissions to fetch entitlements.
HTTPException – Fetching the entitlements failed.
- Returns
The entitlements retrieved.
- Return type
List[
Entitlement]
- await ticket()¶
This function is a coroutine.
Retrieves the license ticket for this application.
- Raises
HTTPException – Retrieving the ticket failed.
- Returns
The ticket retrieved.
- Return type
- await entitlement_ticket()¶
This function is a coroutine.
Retrieves the entitlement ticket for this application.
- Raises
HTTPException – Retrieving the ticket failed.
- Returns
The ticket retrieved.
- Return type
- await activity_statistics()¶
This function is a coroutine.
Retrieves the activity usage statistics for this application.
- Raises
HTTPException – Retrieving the statistics failed.
- Returns
The statistics retrieved.
- Return type
AutoMod¶
- class discord.AutoModRule¶
Represents an auto moderation rule.
New in version 2.0.
- trigger¶
The rule’s trigger.
- Type
- exempt_channels¶
The channels that are exempt from this rule.
- Type
List[Union[
abc.GuildChannel,Thread]]
- actions¶
The actions that are taken when this rule is triggered.
- Type
List[
AutoModRuleAction]
- is_exempt(obj, /)¶
Check if an object is exempt from the automod rule.
- Parameters
obj (
abc.Snowflake) – The role, channel, or thread to check.- Returns
Whether the object is exempt from the automod rule.
- Return type
- await edit(*, name=..., event_type=..., actions=..., trigger=..., enabled=..., exempt_roles=..., exempt_channels=..., reason=...)¶
This function is a coroutine.
Edits this auto moderation rule.
You must have
Permissions.manage_guildto edit rules.- Parameters
name (
str) – The new name to change to.event_type (
AutoModRuleEventType) – The new event type to change to.actions (List[
AutoModRuleAction]) – The new rule actions to update.trigger (
AutoModTrigger) – The new trigger to update. You can only change the trigger metadata, not the type.enabled (
bool) – Whether the rule should be enabled or not.exempt_roles (Sequence[
abc.Snowflake]) – The new roles to exempt from the rule.exempt_channels (Sequence[
abc.Snowflake]) – The new channels to exempt from the rule.reason (
str) – The reason for updating this rule. Shows up on the audit log.
- Raises
Forbidden – You do not have permission to edit this rule.
HTTPException – Editing the rule failed.
- Returns
The updated auto moderation rule.
- Return type
- await delete(*, reason=...)¶
This function is a coroutine.
Deletes the auto moderation rule.
You must have
Permissions.manage_guildto delete rules.- Parameters
reason (
str) – The reason for deleting this rule. Shows up on the audit log.- Raises
Forbidden – You do not have permissions to delete the rule.
HTTPException – Deleting the rule failed.
- asyncfetch_rule
- class discord.AutoModAction¶
Represents an action that was taken as the result of a moderation rule.
New in version 2.0.
- action¶
The action that was taken.
- Type
- message_id¶
The message ID that triggered the action. This is only available if the action is done on an edited message.
- Type
Optional[
int]
- rule_trigger_type¶
The trigger type of the rule that was triggered.
- alert_system_message_id¶
The ID of the system message that was sent to the predefined alert channel.
- Type
Optional[
int]
- property channel¶
The channel this action was taken in.
- Type
Optional[Union[
abc.GuildChannel,Thread]]
- property member¶
The member this action was taken against /who triggered this rule.
- Type
Optional[
Member]
- await fetch_rule()¶
This function is a coroutine.
Fetch the rule whose action was taken.
You must have
Permissions.manage_guildto do this.- Raises
Forbidden – You do not have permissions to view the rule.
HTTPException – Fetching the rule failed.
- Returns
The rule that was executed.
- Return type
- class discord.AutoModPresets¶
Wraps up the Discord
AutoModRulepresets.- x == y
Checks if two AutoModPresets flags are equal.
- x != y
Checks if two AutoModPresets flags are not equal.
- x | y, x |= y
Returns an AutoModPresets instance with all enabled flags from both x and y.
- x & y, x &= y
Returns an AutoModPresets instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns an AutoModPresets instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns an AutoModPresets instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs.
New in version 2.0.
- value¶
The raw value. You should query flags via the properties rather than using this raw value.
- Type
- classmethod all()¶
A factory method that creates a
AutoModPresetswith everything enabled.
- classmethod none()¶
A factory method that creates a
AutoModPresetswith everything disabled.
- class discord.AutoModRuleAction¶
Represents an auto moderation’s rule action.
Note
Only one of
channel_id,duration, orcustom_messagecan be used.New in version 2.0.
- type¶
The type of action to take. Defaults to
block_message.
- channel_id¶
The ID of the channel or thread to send the alert message to, if any. Passing this sets
typetosend_alert_message.- Type
Optional[
int]
- duration¶
The duration of the timeout to apply, if any. Has a maximum of 28 days. Passing this sets
typetotimeout.- Type
Optional[
datetime.timedelta]
- custom_message¶
A custom message which will be shown to a user when their message is blocked. Passing this sets
typetoblock_message.New in version 2.0.
- Type
Optional[
str]
- class discord.AutoModTrigger¶
Represents a trigger for an auto moderation rule.
The following table illustrates relevant attributes for each
AutoModRuleTriggerType:Type
Attributes
New in version 2.0.
- type¶
The type of trigger.
- keyword_filter¶
The list of strings that will trigger the keyword filter. Maximum of 1000. Keywords can only be up to 60 characters in length.
This could be combined with
regex_patterns.- Type
List[
str]
- regex_patterns¶
The regex pattern that will trigger the filter. The syntax is based off of Rust’s regex syntax. Maximum of 10. Regex strings can only be up to 260 characters in length.
This could be combined with
keyword_filterand/orallow_listNew in version 2.0.
- Type
List[
str]
- presets¶
The presets used with the preset keyword filter.
- Type
Member¶
- accent_color
- accent_colour
- activities
- activity
- avatar
- avatar_decoration
- banner
- bot
- call
- color
- colour
- created_at
- default_avatar
- desktop_status
- discriminator
- display_avatar
- display_banner
- display_icon
- display_name
- dm_channel
- flags
- guild
- guild_avatar
- guild_permissions
- id
- joined_at
- mention
- mobile_status
- name
- nick
- note
- pending
- premium_since
- public_flags
- raw_status
- relationship
- roles
- status
- system
- timed_out_until
- top_role
- voice
- web_status
- asyncack
- asyncack_pins
- asyncadd_roles
- asyncban
- asyncblock
- asyncconnect
- asynccreate_dm
- asyncedit
- asyncfetch_message
- defget_role
- asyncgreet
- async forhistory
- defis_blocked
- defis_friend
- defis_on_mobile
- defis_timed_out
- asynckick
- defmentioned_in
- asyncmove_to
- asyncpins
- asyncprofile
- asyncremove_friend
- asyncremove_roles
- asyncrequest_to_speak
- asyncsend
- asyncsend_friend_request
- defslash_commands
- asynctimeout
- deftyping
- asyncunban
- asyncunblock
- defuser_commands
- class discord.Member¶
Represents a Discord member to a
Guild.This implements a lot of the functionality of
User.- x == y
Checks if two members are equal. Note that this works with
Userinstances too.
- x != y
Checks if two members are not equal. Note that this works with
Userinstances too.
- hash(x)
Returns the member’s hash.
- str(x)
Returns the member’s name with the discriminator.
- joined_at¶
An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be
None.- Type
Optional[
datetime.datetime]
An aware datetime object that specifies the date and time in UTC when the member used their “Nitro boost” on the guild, if available. This could be
None.- Type
Optional[
datetime.datetime]
- timed_out_until¶
An aware datetime object that specifies the date and time in UTC that the member’s time out will expire. This will be set to
Noneif the user is not timed out.New in version 2.0.
- Type
Optional[
datetime.datetime]
- async with typing()¶
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using
await.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!')
Example Usage:
await channel.typing() # Do some computational magic for about 10 seconds await channel.send('Done!')
Changed in version 2.0: This no longer works with the
withsyntax,async withmust be used instead.Changed in version 2.0: Added functionality to
awaitthe context manager to send a typing indicator for 10 seconds.
- async for ... in slash_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the slash commands available in the channel.
Examples
Usage
async for command in channel.slash_commands(): print(command.name)
Flattening into a list
commands = [command async for command in channel.slash_commands()] # commands is now a list of SlashCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
SlashCommand– A slash command.
- async for ... in user_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the user commands available to use on the user.
Examples
Usage
async for command in user.user_commands(): print(command.name)
Flattening into a list
commands = [command async for command in user.user_commands()] # commands is now a list of UserCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
UserCommand– A user command.
- property discriminator¶
Equivalent to
User.discriminator
- property system¶
Equivalent to
User.system
- property created_at¶
Equivalent to
User.created_at
- property default_avatar¶
Equivalent to
User.default_avatar
- property avatar¶
Equivalent to
User.avatar
- property avatar_decoration¶
Equivalent to
User.avatar_decoration
- property dm_channel¶
Equivalent to
User.dm_channel
- await create_dm()¶
This function is a coroutine.
Creates a
DMChannelwith this user.This should be rarely called, as this is done transparently for most people.
- Returns
The channel that was created.
- Return type
- property public_flags¶
Equivalent to
User.public_flags
- property banner¶
Equivalent to
User.banner
- property accent_color¶
Equivalent to
User.accent_color
- property accent_colour¶
Equivalent to
User.accent_colour
- property colour¶
A property that returns a colour denoting the rendered colour for the member. If the default colour is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
color.- Type
- property color¶
A property that returns a color denoting the rendered color for the member. If the default color is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
colour.- Type
- property roles¶
A
listofRolethat the member belongs to. Note that the first element of this list is always the default ‘@everyone’ role.These roles are sorted by their position in the role hierarchy.
- Type
List[
Role]
- property display_icon¶
A property that returns the role icon that is rendered for this member. If no icon is shown then
Noneis returned.New in version 2.0.
- property display_name¶
Returns the user’s display name.
For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
- Type
- property display_avatar¶
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
- Type
- property guild_avatar¶
Returns an
Assetfor the guild avatar the member has. If unavailable,Noneis returned.New in version 2.0.
- Type
Optional[
Asset]
- property activities¶
Returns the activities that the user is currently doing.
Note
Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.
- Type
Tuple[Union[
BaseActivity,Spotify]]
- property activity¶
Returns the primary activity the user is currently doing. Could be
Noneif no activity is being done.Note
Due to a Discord API limitation, this may be
Noneif the user is listening to a song on Spotify with a title longer than 128 characters. See GH-1738 for more information.Note
A user may have multiple activities, these can be accessed under
activities.- Type
Optional[Union[
BaseActivity,Spotify]]
- mentioned_in(message)¶
Checks if the member is mentioned in the specified message.
- property top_role¶
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
- Type
- property guild_permissions¶
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use
abc.GuildChannel.permissions_for().This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.
Changed in version 2.0: Member timeouts are taken into consideration.
- Type
- property voice¶
Returns the member’s current voice state.
- Type
Optional[
VoiceState]
- property flags¶
Returns the member’s flags.
New in version 2.0.
- Type
- await ban(*, delete_message_days=..., delete_message_seconds=..., reason=None)¶
This function is a coroutine.
Bans this member. Equivalent to
Guild.ban().
- await unban(*, reason=None)¶
This function is a coroutine.
Unbans this member. Equivalent to
Guild.unban().
- await kick(*, reason=None)¶
This function is a coroutine.
Kicks this member. Equivalent to
Guild.kick().
- await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., avatar=..., banner=..., bio=..., bypass_verification=..., reason=None)¶
This function is a coroutine.
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below:
Parameter
Permission
nick
mute
deafen
roles
voice_channel
timed_out_until
bypass_verification
All parameters are optional.
Note
To upload an avatar or banner, a bytes-like object must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via
open('some_filename', 'rb')and the bytes-like object is given through the use offp.read().Changed in version 1.1: Can now pass
Nonetovoice_channelto kick a member from voice.Changed in version 2.0: The newly updated member is now optionally returned, if applicable.
- Parameters
nick (Optional[
str]) – The member’s new nickname. UseNoneto remove the nickname.mute (
bool) – Indicates if the member should be guild muted or un-muted.deafen (
bool) – Indicates if the member should be guild deafened or un-deafened.suppress (
bool) –Indicates if the member should be suppressed in stage channels.
New in version 1.7.
roles (List[
Role]) – The member’s new list of roles. This replaces the roles.voice_channel (Optional[Union[
VoiceChannel,StageChannel]]) – The voice channel to move the member to. PassNoneto kick them from voice.timed_out_until (Optional[
datetime.datetime]) –The date the member’s timeout should expire, or
Noneto remove the timeout. This must be a timezone-aware datetime object. Consider usingutils.utcnow().New in version 2.0.
avatar (Optional[
bytes]) –The member’s new guild avatar. Pass
Noneto remove the avatar. You can only change your own guild avatar.New in version 2.0.
banner (Optional[
bytes]) –The member’s new guild banner. Pass
Noneto remove the banner. You can only change your own guild banner.New in version 2.0.
bio (Optional[
str]) –The member’s new guild “about me”. Pass
Noneto remove the bio. You can only change your own guild bio.New in version 2.0.
bypass_verification (
bool) –Indicates if the member should be allowed to bypass the guild verification requirements.
New in version 2.0.
reason (Optional[
str]) – The reason for editing this member. Shows up on the audit log.
- Raises
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
TypeError – The datetime object passed to
timed_out_untilwas not timezone-aware.
- Returns
The newly updated member, if applicable. This is not returned if certain fields are passed, such as
suppress.- Return type
Optional[
Member]
- await request_to_speak()¶
This function is a coroutine.
Request to speak in the connected channel.
Only applies to stage channels.
Note
Requesting members that are not the client is equivalent to
editprovidingsuppressasFalse.New in version 1.7.
- Raises
ClientException – You are not connected to a voice channel.
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
- await move_to(channel, *, reason=None)¶
This function is a coroutine.
Moves a member to a new voice channel (they must be connected first).
You must have
move_membersto do this.This raises the same exceptions as
edit().Changed in version 1.1: Can now pass
Noneto kick a member from voice.- Parameters
channel (Optional[Union[
VoiceChannel,StageChannel]]) – The new voice channel to move the member to. PassNoneto kick them from voice.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- await timeout(until, /, *, reason=None)¶
This function is a coroutine.
Applies a time out to a member until the specified date time or for the given
datetime.timedelta.You must have
moderate_membersto do this.This raises the same exceptions as
edit().- Parameters
until (Optional[Union[
datetime.timedelta,datetime.datetime]]) – If this is adatetime.timedeltathen it represents the amount of time the member should be timed out for. If this is adatetime.datetimethen it’s when the member’s timeout should expire. IfNoneis passed then the timeout is removed. Note that the API only allows for timeouts up to 28 days.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises
TypeError – The
untilparameter was the wrong type or the datetime was not timezone-aware.
- await add_roles(*roles, reason=None, atomic=True)¶
This function is a coroutine.
Gives the member a number of
Roles.You must have
manage_rolesto use this, and the addedRoles must appear lower in the list of roles than the highest role of the member.- Parameters
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto give to the member.reason (Optional[
str]) – The reason for adding these roles. Shows up on the audit log.atomic (
bool) – Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- Raises
Forbidden – You do not have permissions to add these roles.
HTTPException – Adding roles failed.
- await remove_roles(*roles, reason=None, atomic=True)¶
This function is a coroutine.
Removes
Roles from this member.You must have
manage_rolesto use this, and the removedRoles must appear lower in the list of roles than the highest role of the member.- Parameters
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto remove from the member.reason (Optional[
str]) – The reason for removing these roles. Shows up on the audit log.atomic (
bool) – Whether to atomically remove roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- Raises
Forbidden – You do not have permissions to remove these roles.
HTTPException – Removing the roles failed.
- get_role(role_id, /)¶
Returns a role with the given ID from roles which the member has.
New in version 2.0.
- is_timed_out()¶
Returns whether this member is timed out.
New in version 2.0.
- Returns
Trueif the member is timed out.Falseotherwise.- Return type
- await send_friend_request()¶
This function is a coroutine.
Sends the member a friend request.
- Raises
Forbidden – Not allowed to send a friend request to the member.
HTTPException – Sending the friend request failed.
- await ack()¶
This function is a coroutine.
Marks every message in this channel as read.
- Raises
HTTPException – Acking the channel failed.
- await ack_pins()¶
This function is a coroutine.
Marks a channel’s pins as viewed.
- Raises
HTTPException – Acking the pinned messages failed.
- await block()¶
This function is a coroutine.
Blocks the user.
- Raises
Forbidden – Not allowed to block this user.
HTTPException – Blocking the user failed.
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, _channel=None, self_deaf=False, self_mute=False)¶
This function is a coroutine.
Connects to voice and creates a
VoiceClientto establish your connection to the voice server.- Parameters
timeout (
float) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (Type[
VoiceProtocol]) – A type that subclassesVoiceProtocolto connect with. Defaults toVoiceClient.self_mute (
bool) –Indicates if the client should be self-muted.
New in version 2.0.
self_deaf (
bool) –Indicates if the client should be self-deafened.
New in version 2.0.
- Raises
asyncio.TimeoutError – Could not connect to the voice channel in time.
ClientException – You are already connected to a voice channel.
OpusNotLoaded – The opus library has not been loaded.
- Returns
A voice client that is fully connected to the voice server.
- Return type
- property display_banner¶
Equivalent to
User.display_banner
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters
id (
int) – The message ID to look for.- 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.
- Returns
The message asked for.
- Return type
- await greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...)¶
This function is a coroutine.
Sends a sticker greeting to the destination.
A sticker greeting is used to begin a new DM or reply to a system message.
New in version 2.0.
- Parameters
sticker (Union[
GuildSticker,StickerItem]) – The sticker to greet with.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead. In the case of greeting, onlyreplied_useris considered.reference (Union[
Message,MessageReference,PartialMessage]) – A reference to theMessageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.mention_author (
bool) – If set, overrides thereplied_userattribute ofallowed_mentions.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
TypeError – The
referenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The sticker greeting that was sent.
- Return type
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an asynchronous iterator that enables receiving the destination’s message history.
You must have
read_message_historyto do this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in channel.history(limit=123)] # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. 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 messages after this date or message. 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.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields
Message– The message with the message data parsed.
- await pins()¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises
Forbidden – You do not have the permission to retrieve pinned messages.
HTTPException – Retrieving the pinned messages failed.
- Returns
The messages that are currently pinned.
- Return type
List[
Message]
- await profile(*, with_mutual_guilds=True, with_mutual_friends_count=False, with_mutual_friends=True)¶
This function is a coroutine.
A shorthand method to retrieve a
MemberProfilefor the member.- Parameters
with_mutual_guilds (
bool) –Whether to fetch mutual guilds. This fills in
MemberProfile.mutual_guilds.New in version 2.0.
with_mutual_friends_count (
bool) –Whether to fetch the number of mutual friends. This fills in
MemberProfile.mutual_friends_count.New in version 2.0.
with_mutual_friends (
bool) –Whether to fetch mutual friends. This fills in
MemberProfile.mutual_friendsandMemberProfile.mutual_friends_count, but requires an extra API call.New in version 2.0.
- Raises
Forbidden – Not allowed to fetch this profile.
HTTPException – Fetching the profile failed.
InvalidData – The member is not in this guild or has blocked you.
- Returns
The profile of the member.
- Return type
- property relationship¶
Equivalent to
User.relationship
- await remove_friend()¶
This function is a coroutine.
Removes the user as a friend.
- Raises
Forbidden – Not allowed to remove this user as a friend.
HTTPException – Removing the user as a friend failed.
- await send(content=None, *, tts=False, file=None, files=None, stickers=None, delete_after=None, nonce=..., allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, silent=False)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then a sticker or file must be sent.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (
int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. Generates one by default.delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.New in version 1.6.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
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.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate size.TypeError – You specified both
fileandfiles, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The message that was sent.
- Return type
- await unblock()¶
This function is a coroutine.
Unblocks the user.
- Raises
Forbidden – Not allowed to unblock this user.
HTTPException – Unblocking the user failed.
- accent_color
- accent_colour
- activities
- activity
- application
- avatar
- avatar_decoration
- banner
- bio
- bot
- call
- color
- colour
- connections
- created_at
- default_avatar
- desktop_status
- discriminator
- display_avatar
- display_banner
- display_bio
- display_icon
- display_name
- dm_channel
- flags
- guild_avatar
- guild_banner
- guild_bio
- guild_permissions
- guild_premium_since
- id
- mention
- mobile_status
- mutual_friends
- mutual_friends_count
- mutual_guilds
- name
- note
- premium
- premium_guild_since
- premium_since
- premium_type
- public_flags
- raw_status
- relationship
- roles
- status
- system
- top_role
- voice
- web_status
- asyncack
- asyncack_pins
- asyncadd_roles
- asyncban
- asyncblock
- asyncconnect
- asynccreate_dm
- asyncedit
- asyncfetch_message
- defget_role
- asyncgreet
- async forhistory
- defis_blocked
- defis_friend
- defis_on_mobile
- defis_timed_out
- asynckick
- defmentioned_in
- asyncmove_to
- asyncpins
- asyncprofile
- asyncremove_friend
- asyncremove_roles
- asyncrequest_to_speak
- asyncsend
- asyncsend_friend_request
- defslash_commands
- asynctimeout
- deftyping
- asyncunban
- asyncunblock
- defuser_commands
- class discord.MemberProfile¶
Represents a Discord member’s profile.
This is a
Memberwith extended attributes.- x == y
Checks if two members are equal. Note that this works with
Userinstances too.
- x != y
Checks if two members are not equal. Note that this works with
Userinstances too.
- hash(x)
Returns the member’s hash.
- str(x)
Returns the member’s name with the discriminator.
New in version 2.0.
- application¶
The application profile of the user, if it is a bot.
- Type
Optional[
ApplicationProfile]
An aware datetime object that specifies the date and time in UTC when the member used their “Nitro boost” on the guild, if available. This could be
None.Note
This is renamed from
Member.premium_sincebecause of name collisions.- Type
Optional[
datetime.datetime]
Specifies the type of premium a user has (i.e. Nitro, Nitro Classic, or Nitro Basic). Could be
Noneif the user is not premium.- Type
Optional[
PremiumType]
An aware datetime object that specifies how long a user has been premium (had Nitro).
Noneif the user is not a premium user.Note
This is not the same as
Member.premium_since. That is renamed toguild_premium_since.- Type
Optional[
datetime.datetime]
An aware datetime object that specifies when a user first Nitro boosted a guild.
- Type
Optional[
datetime.datetime]
- connections¶
The connected accounts that show up on the profile.
- Type
Optional[List[
PartialConnection]]
- mutual_guilds¶
A list of guilds that you share with the user.
Noneif you didn’t fetch mutuals.- Type
Optional[List[
MutualGuild]]
- mutual_friends¶
A list of friends that you share with the user.
Noneif you didn’t fetch mutuals.- Type
Optional[List[
User]]
- property display_banner¶
Returns the member’s display banner.
For regular members this is just their banner (if available), but if they have a guild specific banner then that is returned instead.
- Type
Optional[
Asset]
- property guild_banner¶
Returns an
Assetfor the guild banner the member has. If unavailable,Noneis returned.- Type
Optional[
Asset]
- property display_bio¶
Returns the member’s display bio.
For regular members this is just their bio (if available), but if they have a guild specific bio then that is returned instead.
- Type
Optional[
str]
- property accent_color¶
Equivalent to
User.accent_color
- property accent_colour¶
Equivalent to
User.accent_colour
- await ack()¶
This function is a coroutine.
Marks every message in this channel as read.
- Raises
HTTPException – Acking the channel failed.
- await ack_pins()¶
This function is a coroutine.
Marks a channel’s pins as viewed.
- Raises
HTTPException – Acking the pinned messages failed.
- property activities¶
Returns the activities that the user is currently doing.
Note
Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.
- Type
Tuple[Union[
BaseActivity,Spotify]]
- property activity¶
Returns the primary activity the user is currently doing. Could be
Noneif no activity is being done.Note
Due to a Discord API limitation, this may be
Noneif the user is listening to a song on Spotify with a title longer than 128 characters. See GH-1738 for more information.Note
A user may have multiple activities, these can be accessed under
activities.- Type
Optional[Union[
BaseActivity,Spotify]]
- await add_roles(*roles, reason=None, atomic=True)¶
This function is a coroutine.
Gives the member a number of
Roles.You must have
manage_rolesto use this, and the addedRoles must appear lower in the list of roles than the highest role of the member.- Parameters
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto give to the member.reason (Optional[
str]) – The reason for adding these roles. Shows up on the audit log.atomic (
bool) – Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- Raises
Forbidden – You do not have permissions to add these roles.
HTTPException – Adding roles failed.
- property avatar¶
Equivalent to
User.avatar
- property avatar_decoration¶
Equivalent to
User.avatar_decoration
- await ban(*, delete_message_days=..., delete_message_seconds=..., reason=None)¶
This function is a coroutine.
Bans this member. Equivalent to
Guild.ban().
- property banner¶
Equivalent to
User.banner
- await block()¶
This function is a coroutine.
Blocks the user.
- Raises
Forbidden – Not allowed to block this user.
HTTPException – Blocking the user failed.
- property color¶
A property that returns a color denoting the rendered color for the member. If the default color is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
colour.- Type
- property colour¶
A property that returns a colour denoting the rendered colour for the member. If the default colour is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
color.- Type
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, _channel=None, self_deaf=False, self_mute=False)¶
This function is a coroutine.
Connects to voice and creates a
VoiceClientto establish your connection to the voice server.- Parameters
timeout (
float) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (Type[
VoiceProtocol]) – A type that subclassesVoiceProtocolto connect with. Defaults toVoiceClient.self_mute (
bool) –Indicates if the client should be self-muted.
New in version 2.0.
self_deaf (
bool) –Indicates if the client should be self-deafened.
New in version 2.0.
- Raises
asyncio.TimeoutError – Could not connect to the voice channel in time.
ClientException – You are already connected to a voice channel.
OpusNotLoaded – The opus library has not been loaded.
- Returns
A voice client that is fully connected to the voice server.
- Return type
- await create_dm()¶
This function is a coroutine.
Creates a
DMChannelwith this user.This should be rarely called, as this is done transparently for most people.
- Returns
The channel that was created.
- Return type
- property created_at¶
Equivalent to
User.created_at
- property default_avatar¶
Equivalent to
User.default_avatar
- property discriminator¶
Equivalent to
User.discriminator
- property display_avatar¶
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
- Type
- property display_icon¶
A property that returns the role icon that is rendered for this member. If no icon is shown then
Noneis returned.New in version 2.0.
- property display_name¶
Returns the user’s display name.
For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
- Type
- property dm_channel¶
Equivalent to
User.dm_channel
- await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., avatar=..., banner=..., bio=..., bypass_verification=..., reason=None)¶
This function is a coroutine.
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below:
Parameter
Permission
nick
mute
deafen
roles
voice_channel
timed_out_until
bypass_verification
All parameters are optional.
Note
To upload an avatar or banner, a bytes-like object must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via
open('some_filename', 'rb')and the bytes-like object is given through the use offp.read().Changed in version 1.1: Can now pass
Nonetovoice_channelto kick a member from voice.Changed in version 2.0: The newly updated member is now optionally returned, if applicable.
- Parameters
nick (Optional[
str]) – The member’s new nickname. UseNoneto remove the nickname.mute (
bool) – Indicates if the member should be guild muted or un-muted.deafen (
bool) – Indicates if the member should be guild deafened or un-deafened.suppress (
bool) –Indicates if the member should be suppressed in stage channels.
New in version 1.7.
roles (List[
Role]) – The member’s new list of roles. This replaces the roles.voice_channel (Optional[Union[
VoiceChannel,StageChannel]]) – The voice channel to move the member to. PassNoneto kick them from voice.timed_out_until (Optional[
datetime.datetime]) –The date the member’s timeout should expire, or
Noneto remove the timeout. This must be a timezone-aware datetime object. Consider usingutils.utcnow().New in version 2.0.
avatar (Optional[
bytes]) –The member’s new guild avatar. Pass
Noneto remove the avatar. You can only change your own guild avatar.New in version 2.0.
banner (Optional[
bytes]) –The member’s new guild banner. Pass
Noneto remove the banner. You can only change your own guild banner.New in version 2.0.
bio (Optional[
str]) –The member’s new guild “about me”. Pass
Noneto remove the bio. You can only change your own guild bio.New in version 2.0.
bypass_verification (
bool) –Indicates if the member should be allowed to bypass the guild verification requirements.
New in version 2.0.
reason (Optional[
str]) – The reason for editing this member. Shows up on the audit log.
- Raises
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
TypeError – The datetime object passed to
timed_out_untilwas not timezone-aware.
- Returns
The newly updated member, if applicable. This is not returned if certain fields are passed, such as
suppress.- Return type
Optional[
Member]
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters
id (
int) – The message ID to look for.- 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.
- Returns
The message asked for.
- Return type
- property flags¶
Returns the member’s flags.
New in version 2.0.
- Type
- get_role(role_id, /)¶
Returns a role with the given ID from roles which the member has.
New in version 2.0.
- await greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...)¶
This function is a coroutine.
Sends a sticker greeting to the destination.
A sticker greeting is used to begin a new DM or reply to a system message.
New in version 2.0.
- Parameters
sticker (Union[
GuildSticker,StickerItem]) – The sticker to greet with.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead. In the case of greeting, onlyreplied_useris considered.reference (Union[
Message,MessageReference,PartialMessage]) – A reference to theMessageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.mention_author (
bool) – If set, overrides thereplied_userattribute ofallowed_mentions.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
TypeError – The
referenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The sticker greeting that was sent.
- Return type
- property guild_avatar¶
Returns an
Assetfor the guild avatar the member has. If unavailable,Noneis returned.New in version 2.0.
- Type
Optional[
Asset]
- property guild_permissions¶
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use
abc.GuildChannel.permissions_for().This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.
Changed in version 2.0: Member timeouts are taken into consideration.
- Type
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an asynchronous iterator that enables receiving the destination’s message history.
You must have
read_message_historyto do this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in channel.history(limit=123)] # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. 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 messages after this date or message. 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.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields
Message– The message with the message data parsed.
- is_timed_out()¶
Returns whether this member is timed out.
New in version 2.0.
- Returns
Trueif the member is timed out.Falseotherwise.- Return type
- await kick(*, reason=None)¶
This function is a coroutine.
Kicks this member. Equivalent to
Guild.kick().
- mentioned_in(message)¶
Checks if the member is mentioned in the specified message.
- await move_to(channel, *, reason=None)¶
This function is a coroutine.
Moves a member to a new voice channel (they must be connected first).
You must have
move_membersto do this.This raises the same exceptions as
edit().Changed in version 1.1: Can now pass
Noneto kick a member from voice.- Parameters
channel (Optional[Union[
VoiceChannel,StageChannel]]) – The new voice channel to move the member to. PassNoneto kick them from voice.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- property mutual_friends_count¶
The number of mutual friends the user has with the client user.
- Type
Optional[
int]
- await pins()¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises
Forbidden – You do not have the permission to retrieve pinned messages.
HTTPException – Retrieving the pinned messages failed.
- Returns
The messages that are currently pinned.
- Return type
List[
Message]
Indicates if the user is a premium user.
- Type
- await profile(*, with_mutual_guilds=True, with_mutual_friends_count=False, with_mutual_friends=True)¶
This function is a coroutine.
A shorthand method to retrieve a
MemberProfilefor the member.- Parameters
with_mutual_guilds (
bool) –Whether to fetch mutual guilds. This fills in
MemberProfile.mutual_guilds.New in version 2.0.
with_mutual_friends_count (
bool) –Whether to fetch the number of mutual friends. This fills in
MemberProfile.mutual_friends_count.New in version 2.0.
with_mutual_friends (
bool) –Whether to fetch mutual friends. This fills in
MemberProfile.mutual_friendsandMemberProfile.mutual_friends_count, but requires an extra API call.New in version 2.0.
- Raises
Forbidden – Not allowed to fetch this profile.
HTTPException – Fetching the profile failed.
InvalidData – The member is not in this guild or has blocked you.
- Returns
The profile of the member.
- Return type
- property public_flags¶
Equivalent to
User.public_flags
- property relationship¶
Equivalent to
User.relationship
- await remove_friend()¶
This function is a coroutine.
Removes the user as a friend.
- Raises
Forbidden – Not allowed to remove this user as a friend.
HTTPException – Removing the user as a friend failed.
- await remove_roles(*roles, reason=None, atomic=True)¶
This function is a coroutine.
Removes
Roles from this member.You must have
manage_rolesto use this, and the removedRoles must appear lower in the list of roles than the highest role of the member.- Parameters
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto remove from the member.reason (Optional[
str]) – The reason for removing these roles. Shows up on the audit log.atomic (
bool) – Whether to atomically remove roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- Raises
Forbidden – You do not have permissions to remove these roles.
HTTPException – Removing the roles failed.
- await request_to_speak()¶
This function is a coroutine.
Request to speak in the connected channel.
Only applies to stage channels.
Note
Requesting members that are not the client is equivalent to
editprovidingsuppressasFalse.New in version 1.7.
- Raises
ClientException – You are not connected to a voice channel.
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
- property roles¶
A
listofRolethat the member belongs to. Note that the first element of this list is always the default ‘@everyone’ role.These roles are sorted by their position in the role hierarchy.
- Type
List[
Role]
- await send(content=None, *, tts=False, file=None, files=None, stickers=None, delete_after=None, nonce=..., allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, silent=False)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then a sticker or file must be sent.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (
int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. Generates one by default.delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.New in version 1.6.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
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.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate size.TypeError – You specified both
fileandfiles, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The message that was sent.
- Return type
- await send_friend_request()¶
This function is a coroutine.
Sends the member a friend request.
- Raises
Forbidden – Not allowed to send a friend request to the member.
HTTPException – Sending the friend request failed.
- slash_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the slash commands available in the channel.
Examples
Usage
async for command in channel.slash_commands(): print(command.name)
Flattening into a list
commands = [command async for command in channel.slash_commands()] # commands is now a list of SlashCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
SlashCommand– A slash command.
- property system¶
Equivalent to
User.system
- await timeout(until, /, *, reason=None)¶
This function is a coroutine.
Applies a time out to a member until the specified date time or for the given
datetime.timedelta.You must have
moderate_membersto do this.This raises the same exceptions as
edit().- Parameters
until (Optional[Union[
datetime.timedelta,datetime.datetime]]) – If this is adatetime.timedeltathen it represents the amount of time the member should be timed out for. If this is adatetime.datetimethen it’s when the member’s timeout should expire. IfNoneis passed then the timeout is removed. Note that the API only allows for timeouts up to 28 days.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises
TypeError – The
untilparameter was the wrong type or the datetime was not timezone-aware.
- property top_role¶
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
- Type
- typing()¶
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using
await.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!')
Example Usage:
await channel.typing() # Do some computational magic for about 10 seconds await channel.send('Done!')
Changed in version 2.0: This no longer works with the
withsyntax,async withmust be used instead.Changed in version 2.0: Added functionality to
awaitthe context manager to send a typing indicator for 10 seconds.
- await unban(*, reason=None)¶
This function is a coroutine.
Unbans this member. Equivalent to
Guild.unban().
- await unblock()¶
This function is a coroutine.
Unblocks the user.
- Raises
Forbidden – Not allowed to unblock this user.
HTTPException – Unblocking the user failed.
- user_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the user commands available to use on the user.
Examples
Usage
async for command in user.user_commands(): print(command.name)
Flattening into a list
commands = [command async for command in user.user_commands()] # commands is now a list of UserCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
UserCommand– A user command.
- property voice¶
Returns the member’s current voice state.
- Type
Optional[
VoiceState]
VoiceState¶
- class discord.VoiceState¶
Represents a Discord user’s voice state.
- deaf¶
Indicates if the user is currently deafened by the guild.
Doesn’t apply to private channels.
- Type
- mute¶
Indicates if the user is currently muted by the guild.
Doesn’t apply to private channels.
- Type
- self_stream¶
Indicates if the user is currently streaming via ‘Go Live’ feature.
New in version 1.3.
- Type
- suppress¶
Indicates if the user is suppressed from speaking.
Only applicable to stage channels.
New in version 1.7.
- Type
- requested_to_speak_at¶
An aware datetime object that specifies the date and time in UTC that the member requested to speak. It will be
Noneif they are not requesting to speak anymore or have been accepted to speak.Only applicable to stage channels.
New in version 1.7.
- Type
Optional[
datetime.datetime]
- channel¶
The voice channel that the user is currently connected to.
Noneif the user is not currently in a voice channel.- Type
Optional[Union[
VoiceChannel,StageChannel,DMChannel,GroupChannel]]
Emoji¶
- class discord.Emoji¶
Represents a custom emoji.
Depending on the way this object was created, some of the attributes can have a value of
None.- x == y
Checks if two emoji are the same.
- x != y
Checks if two emoji are not the same.
- hash(x)
Return the emoji’s hash.
- iter(x)
Returns an iterator of
(field, value)pairs. This allows this class to be used as an iterable in list/dict/etc constructions.
- str(x)
Returns the emoji rendered for discord.
- require_colons¶
If colons are required to use this emoji in the client (:PJSalt: vs PJSalt).
- Type
- user¶
The user that created the emoji. This can only be retrieved using
Guild.fetch_emoji()and havingmanage_emojis.- Type
Optional[
User]
- property created_at¶
Returns the emoji’s creation time in UTC.
- Type
- property roles¶
A
listof roles that is allowed to use this emoji.If roles is empty, the emoji is unrestricted.
- Type
List[
Role]
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the custom emoji.
You must have
manage_emojisto do this.- Parameters
reason (Optional[
str]) – The reason for deleting this emoji. Shows up on the audit log.- Raises
Forbidden – You are not allowed to delete emojis.
HTTPException – An error occurred deleting the emoji.
- await edit(*, name=..., roles=..., reason=None)¶
This function is a coroutine.
Edits the custom emoji.
You must have
manage_emojisto do this.Changed in version 2.0: The newly updated emoji is returned.
- Parameters
- Raises
Forbidden – You are not allowed to edit emojis.
HTTPException – An error occurred editing the emoji.
- Returns
The newly updated emoji.
- Return type
- await fetch_guild()¶
This function is a coroutine.
Retrieves the guild this emoji belongs to.
- Raises
NotFound – The guild this emoji belongs to is not public.
HTTPException – An error occurred while fetching the guild.
- Returns
The guild this emoji belongs to.
- Return type
- await read()¶
This function is a coroutine.
Retrieves the content of this asset as a
bytesobject.- Raises
DiscordException – There was no internal connection state.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns
The content of the asset.
- Return type
- await save(fp, *, seek_begin=True)¶
This function is a coroutine.
Saves this asset into a file-like object.
- Parameters
fp (Union[
io.BufferedIOBase,os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.seek_begin (
bool) – Whether to seek to the beginning of the file after saving is successfully done.
- Raises
DiscordException – There was no internal connection state.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns
The number of bytes written.
- Return type
- await to_file(*, filename=..., description=None, spoiler=False)¶
This function is a coroutine.
Converts the asset into a
Filesuitable for sending viaabc.Messageable.send().New in version 2.0.
- Parameters
- Raises
DiscordException – The asset does not have an associated state.
ValueError – The asset is a unicode emoji.
TypeError – The asset is a sticker with lottie type.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns
The asset as a file suitable for sending.
- Return type
- clsPartialEmoji.from_str
- asyncfetch_guild
- defis_custom_emoji
- defis_unicode_emoji
- asyncread
- asyncsave
- asyncto_file
- class discord.PartialEmoji¶
Represents a “partial” emoji.
This model will be given in two scenarios:
“Raw” data events such as
on_raw_reaction_add()Custom emoji that the bot cannot see from e.g.
Message.reactions
- x == y
Checks if two emoji are the same.
- x != y
Checks if two emoji are not the same.
- hash(x)
Return the emoji’s hash.
- str(x)
Returns the emoji rendered for discord.
- name¶
The custom emoji name, if applicable, or the unicode codepoint of the non-custom emoji. This can be
Noneif the emoji got deleted (e.g. removing a reaction with a deleted emoji).- Type
Optional[
str]
- classmethod from_str(value)¶
Converts a Discord string representation of an emoji to a
PartialEmoji.The formats accepted are:
a:name:id<a:name:id>name:id<:name:id>
If the format does not match then it is assumed to be a unicode emoji.
New in version 2.0.
- Parameters
value (
str) – The string representation of an emoji.- Returns
The partial emoji from this string.
- Return type
- property created_at¶
Returns the emoji’s creation time in UTC, or None if Unicode emoji.
New in version 1.6.
- Type
Optional[
datetime.datetime]
- property url¶
Returns the URL of the emoji, if it is custom.
If this isn’t a custom emoji then an empty string is returned
- Type
- await read()¶
This function is a coroutine.
Retrieves the content of this asset as a
bytesobject.- Raises
DiscordException – There was no internal connection state.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
ValueError – The PartialEmoji is not a custom emoji.
- Returns
The content of the asset.
- Return type
- await fetch_guild()¶
This function is a coroutine.
Retrieves the guild this emoji belongs to.
- Raises
NotFound – The guild this emoji belongs to is not public.
HTTPException – An error occurred while fetching the guild.
ValueError – The emoji is not custom.
TypeError – The emoji does not have state available.
- Returns
The guild this emoji belongs to.
- Return type
- await save(fp, *, seek_begin=True)¶
This function is a coroutine.
Saves this asset into a file-like object.
- Parameters
fp (Union[
io.BufferedIOBase,os.PathLike]) – The file-like object to save this asset to or the filename to use. If a filename is passed then a file is created with that filename and used instead.seek_begin (
bool) – Whether to seek to the beginning of the file after saving is successfully done.
- Raises
DiscordException – There was no internal connection state.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns
The number of bytes written.
- Return type
- await to_file(*, filename=..., description=None, spoiler=False)¶
This function is a coroutine.
Converts the asset into a
Filesuitable for sending viaabc.Messageable.send().New in version 2.0.
- Parameters
- Raises
DiscordException – The asset does not have an associated state.
ValueError – The asset is a unicode emoji.
TypeError – The asset is a sticker with lottie type.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns
The asset as a file suitable for sending.
- Return type
Sticker¶
- class discord.Sticker¶
Represents a sticker.
New in version 1.6.
- str(x)
Returns the name of the sticker.
- x == y
Checks if the sticker is equal to another sticker.
- x != y
Checks if the sticker is not equal to another sticker.
- format¶
The format for the sticker’s image.
- Type
- property created_at¶
Returns the sticker’s creation time in UTC.
- Type
- class discord.StickerItem¶
Represents a sticker item.
New in version 2.0.
- str(x)
Returns the name of the sticker item.
- x == y
Checks if the sticker item is equal to another sticker item.
- x != y
Checks if the sticker item is not equal to another sticker item.
- format¶
The format for the sticker’s image.
- Type
- await fetch()¶
This function is a coroutine.
Attempts to retrieve the full sticker data of the sticker item.
- Raises
HTTPException – Retrieving the sticker failed.
- Returns
The retrieved sticker.
- Return type
Union[
StandardSticker,GuildSticker]
- await fetch_guild()¶
This function is a coroutine.
Retrieves the guild this sticker belongs to.
- Raises
NotFound – The guild this sticker belongs to is not public.
HTTPException – An error occurred while fetching the guild.
- Returns
The guild this emoji belongs to.
- Return type
- class discord.StickerPack¶
Represents a sticker pack.
New in version 2.0.
- str(x)
Returns the name of the sticker pack.
- x == y
Checks if the sticker pack is equal to another sticker pack.
- x != y
Checks if the sticker pack is not equal to another sticker pack.
- stickers¶
The stickers of this sticker pack.
- Type
List[
StandardSticker]
- cover_sticker¶
The sticker used for the cover of the sticker pack.
- Type
Optional[
StandardSticker]
- asyncpack
- class discord.StandardSticker¶
Represents a sticker that is found in a standard sticker pack.
New in version 2.0.
- str(x)
Returns the name of the sticker.
- x == y
Checks if the sticker is equal to another sticker.
- x != y
Checks if the sticker is not equal to another sticker.
- format¶
The format for the sticker’s image.
- Type
- await pack()¶
This function is a coroutine.
Retrieves the sticker pack that this sticker belongs to.
- Raises
InvalidData – The corresponding sticker pack was not found.
HTTPException – Retrieving the sticker pack failed.
- Returns
The retrieved sticker pack.
- Return type
- asyncdelete
- asyncedit
- asyncfetch_guild
- class discord.GuildSticker¶
Represents a sticker that belongs to a guild.
New in version 2.0.
- str(x)
Returns the name of the sticker.
- x == y
Checks if the sticker is equal to another sticker.
- x != y
Checks if the sticker is not equal to another sticker.
- format¶
The format for the sticker’s image.
- Type
- user¶
The user that created this sticker. This can only be retrieved using
Guild.fetch_sticker()and havingmanage_emojis_and_stickers.- Type
Optional[
User]
- guild¶
The guild that this sticker is from. Could be
Noneif the bot is not in the guild.New in version 2.0.
- Type
Optional[
Guild]
- await edit(*, name=..., description=..., emoji=..., reason=None)¶
This function is a coroutine.
Edits a
GuildStickerfor the guild.- Parameters
name (
str) – The sticker’s new name. Must be at least 2 characters.description (Optional[
str]) – The sticker’s new description. Can beNone.emoji (
str) – The name of a unicode emoji that represents the sticker’s expression.reason (
str) – The reason for editing this sticker. Shows up on the audit log.
- Raises
Forbidden – You are not allowed to edit stickers.
HTTPException – An error occurred editing the sticker.
- Returns
The newly modified sticker.
- Return type
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the custom
Stickerfrom the guild.You must have
manage_emojis_and_stickersto do this.- Parameters
reason (Optional[
str]) – The reason for deleting this sticker. Shows up on the audit log.- Raises
Forbidden – You are not allowed to delete stickers.
HTTPException – An error occurred deleting the sticker.
- await fetch_guild()¶
This function is a coroutine.
Retrieves the guild this sticker belongs to.
- Raises
NotFound – The guild this sticker belongs to is not public.
HTTPException – An error occurred while fetching the guild.
- Returns
The guild this emoji belongs to.
- Return type
GuildChannel¶
- asyncclone
- asynccreate_forum
- asynccreate_invite
- asynccreate_stage_channel
- asynccreate_text_channel
- asynccreate_voice_channel
- asyncdelete
- asyncedit
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncset_permissions
- class discord.CategoryChannel¶
Represents a Discord channel category.
These are useful to group channels to logical compartments.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the category’s hash.
- str(x)
Returns the category’s name.
- position¶
The position in the category list. This is a number that starts at 0. e.g. the top category is position 0.
- Type
- nsfw¶
If the channel is marked as “not safe for work”.
Note
To check if the channel or the guild of that channel are marked as NSFW, consider
is_nsfw()instead.- Type
- property type¶
The channel’s Discord type.
- Type
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have
manage_channelsto do this.New in version 1.1.
- Parameters
- Raises
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns
The channel that was created.
- Return type
- await edit(*, reason=None, **options)¶
This function is a coroutine.
Edits the channel.
You must have
manage_channelsto do this.Changed in version 1.3: The
overwriteskeyword-only parameter was added.Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
name (
str) – The new category’s name.position (
int) – The new category’s position.nsfw (
bool) – To mark the category as NSFW or not.reason (Optional[
str]) – The reason for editing this category. Shows up on the audit log.overwrites (
Mapping) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.
- Raises
ValueError – If position is less than 0 or greater than the number of categories.
TypeError – The overwrite information is not in proper form.
Forbidden – You do not have permissions to edit the category.
HTTPException – Editing the category failed.
- Returns
The newly edited category channel. If the edit was only positional then
Noneis returned instead.- Return type
Optional[
CategoryChannel]
- await move(**kwargs)¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have
manage_channelsto do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
beginning (
bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend,before, andafter.end (
bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning,before, andafter.before (
Snowflake) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (
Snowflake) – The channel that should be after our current channel. This is mutually exclusive withbeginning,end, andbefore.offset (
int) – The number of channels to offset the move by. For example, an offset of2withbeginning=Truewould move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning,end,before, andafterparameters.category (Optional[
Snowflake]) – The category to move this channel under. IfNoneis given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool) – Whether to sync the permissions with the category (if given).reason (
str) – The reason for the move.
- Raises
ValueError – An invalid position was given.
TypeError – A bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- property channels¶
Returns the channels that are under this category.
These are sorted by the official Discord UI, which places voice channels below the text channels.
- Type
List[
abc.GuildChannel]
- property text_channels¶
Returns the text channels that are under this category.
- Type
List[
TextChannel]
- property voice_channels¶
Returns the voice channels that are under this category.
- Type
List[
VoiceChannel]
- property stage_channels¶
Returns the stage channels that are under this category.
New in version 1.7.
- Type
List[
StageChannel]
- await create_text_channel(name, **options)¶
This function is a coroutine.
A shortcut method to
Guild.create_text_channel()to create aTextChannelin the category.- Returns
The channel that was just created.
- Return type
- await create_voice_channel(name, **options)¶
This function is a coroutine.
A shortcut method to
Guild.create_voice_channel()to create aVoiceChannelin the category.- Returns
The channel that was just created.
- Return type
- await create_stage_channel(name, **options)¶
This function is a coroutine.
A shortcut method to
Guild.create_stage_channel()to create aStageChannelin the category.New in version 1.7.
- Returns
The channel that was just created.
- Return type
- await create_forum(name, **options)¶
This function is a coroutine.
A shortcut method to
Guild.create_forum()to create aForumChannelin the category.New in version 2.0.
- Returns
The channel that was just created.
- Return type
- property category¶
The category this channel belongs to.
If there is no category then this is
None.- Type
Optional[
CategoryChannel]
- property changed_roles¶
Returns a list of roles that have been overridden from their default values in the
rolesattribute.- Type
List[
Role]
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, validate, target_type=None, target_user=None, target_application=None)¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have
create_instant_inviteto do this.- Parameters
max_age (
int) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse.unique (
bool) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalsethen it will return a previously created invite.validate (Union[
Invite,str]) –The existing channel invite to validate and return for reuse. If this invite is invalid, a new invite will be created according to the parameters and returned.
New in version 2.0.
target_type (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
New in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.New in version 2.0.
target_application: –
Optional[
Application]: The embedded application for the invite, required iftarget_typeisInviteTarget.embedded_application.New in version 2.0.
reason (Optional[
str]) – The reason for creating this invite. Shows up on the audit log.
- Raises
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns
The invite that was created.
- Return type
- property created_at¶
Returns the channel’s creation time in UTC.
- Type
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the channel.
You must have
manage_channelsto do this.- Parameters
reason (Optional[
str]) – The reason for deleting this channel. Shows up on the audit log.- Raises
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channelsto get this information.- Raises
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns
The list of invites that are currently active.
- Return type
List[
Invite]
- property jump_url¶
Returns a URL that allows the client to jump to the channel.
New in version 2.0.
- Type
- property notification_settings¶
Returns the notification settings for this channel.
If not found, an instance is created with defaults applied. This follows Discord behaviour.
New in version 2.0.
- Type
- property overwrites¶
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Roleor aMemberand the value is the overwrite as aPermissionOverwrite.Changed in version 2.0: Overwrites can now be type-aware
Objectin case of cache lookup failure- Returns
The channel’s permission overwrites.
- Return type
Dict[Union[
Role,Member,Object],PermissionOverwrite]
- overwrites_for(obj)¶
Returns the channel-specific overwrites for a member or a role.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Implicit permissions
Member timeout
If a
Roleis passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The permissions of the role used as a parameter
The default role permission overwrites
The permission overwrites of the role used as a parameter
Changed in version 2.0: The object passed in can now be a role object.
Changed in version 2.0:
objparameter is now positional-only.
- property permissions_synced¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.New in version 1.3.
- Type
- await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)¶
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
targetparameter should either be aMemberor aRolethat belongs to guild.The
overwriteparameter, if given, must either beNoneorPermissionOverwrite. For convenience, you can pass in keyword arguments denotingPermissionsattributes. If this is done, then you cannot mix the keyword arguments with theoverwriteparameter.If the
overwriteparameter isNone, then the permission overwrites are deleted.You must have
manage_rolesto do this.Note
This method replaces the old overwrites with the ones given.
Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwriteoverwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
target (Union[
Member,Role]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
TypeError – The
overwriteparameter was invalid or the target type was notRoleorMember.ValueError – The
overwriteparameter andpositionsparameters were both unset.
- asyncack
- asyncack_pins
- async forarchived_threads
- asyncclone
- asynccreate_invite
- asynccreate_thread
- asynccreate_webhook
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_message
- asyncfollow
- defget_partial_message
- defget_thread
- asyncgreet
- async forhistory
- asyncinvites
- defis_news
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncpins
- asyncpurge
- asyncsend
- asyncset_permissions
- defslash_commands
- deftyping
- defuser_commands
- asyncwebhooks
- class discord.TextChannel¶
Represents a Discord guild text channel.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns the channel’s name.
- position¶
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type
- last_message_id¶
The last message ID of the message sent to this channel. It may not point to an existing or valid message.
- Type
Optional[
int]
- last_pin_timestamp¶
When the last pinned message was pinned.
Noneif there are no pinned messages.New in version 2.0.
- Type
Optional[
datetime.datetime]
- slowmode_delay¶
The number of seconds a member must wait between sending messages in this channel. A value of
0denotes that it is disabled. Bots and users withmanage_channelsormanage_messagesbypass slowmode.- Type
- default_auto_archive_duration¶
The default auto archive duration in minutes for threads created in this channel.
New in version 2.0.
- Type
- default_thread_slowmode_delay¶
The default slowmode delay in seconds for threads created in this channel.
New in version 2.0.
- Type
- async with typing()¶
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using
await.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!')
Example Usage:
await channel.typing() # Do some computational magic for about 10 seconds await channel.send('Done!')
Changed in version 2.0: This no longer works with the
withsyntax,async withmust be used instead.Changed in version 2.0: Added functionality to
awaitthe context manager to send a typing indicator for 10 seconds.
- async for ... in slash_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the slash commands available in the channel.
Examples
Usage
async for command in channel.slash_commands(): print(command.name)
Flattening into a list
commands = [command async for command in channel.slash_commands()] # commands is now a list of SlashCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
SlashCommand– A slash command.
- async for ... in user_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the user commands available to use on the user.
Examples
Usage
async for command in user.user_commands(): print(command.name)
Flattening into a list
commands = [command async for command in user.user_commands()] # commands is now a list of UserCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
UserCommand– A user command.
- property type¶
The channel’s Discord type.
- Type
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Implicit permissions
Member timeout
If a
Roleis passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The permissions of the role used as a parameter
The default role permission overwrites
The permission overwrites of the role used as a parameter
Changed in version 2.0: The object passed in can now be a role object.
Changed in version 2.0:
objparameter is now positional-only.
- property last_message¶
Retrieves the last message from this channel in cache.
The message might not be valid or point to an existing message.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either
history()orfetch_message()with thelast_message_idattribute.- Returns
The last message in this channel or
Noneif not found.- Return type
Optional[
Message]
- await edit(*, reason=None, **options)¶
This function is a coroutine.
Edits the channel.
You must have
manage_channelsto do this.Changed in version 1.3: The
overwriteskeyword-only parameter was added.Changed in version 1.4: The
typekeyword-only parameter was added.Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
name (
str) – The new channel name.topic (
str) – The new channel’s topic.position (
int) – The new channel’s position.nsfw (
bool) – To mark the channel as NSFW or not.sync_permissions (
bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse.category (Optional[
CategoryChannel]) – The new category for this channel. Can beNoneto remove the category.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of0disables slowmode. The maximum value possible is21600.type (
ChannelType) – Change the type of this text channel. Currently, only conversion betweenChannelType.textandChannelType.newsis supported. This is only available to guilds that containNEWSinGuild.features.reason (Optional[
str]) – The reason for editing this channel. Shows up on the audit log.overwrites (
Mapping) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.default_auto_archive_duration (
int) –The new default auto archive duration in minutes for threads created in this channel. Must be one of
60,1440,4320, or10080.New in version 2.0.
default_thread_slowmode_delay (
int) –The new default slowmode delay in seconds for threads created in this channel.
New in version 2.0.
- Raises
ValueError – The new
positionis less than 0 or greater than the number of channels.TypeError – The permission overwrite information is not in proper form.
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
- Returns
The newly edited text channel. If the edit was only positional then
Noneis returned instead.- Return type
Optional[
TextChannel]
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have
manage_channelsto do this.New in version 1.1.
- Parameters
- Raises
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns
The channel that was created.
- Return type
- await delete_messages(messages, /, *, reason=None)¶
This function is a coroutine.
Deletes a list of messages. This is similar to
Message.delete()except it bulk deletes multiple messages.You must have
manage_messagesto use this (unless they’re your own).Note
Users do not have access to the message bulk-delete endpoint. Since messages are just iterated over and deleted one-by-one, it’s easy to get ratelimited using this method.
Changed in version 2.0:
messagesparameter is now positional-only.The
reasonkeyword-only parameter was added.- Parameters
messages (Iterable[
abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.reason (Optional[
str]) – The reason for deleting the messages. Shows up on the audit log.
- Raises
Forbidden – You do not have proper permissions to delete the messages.
HTTPException – Deleting the messages failed.
- await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, reason=None)¶
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check. If acheckis not provided then all messages are deleted without discrimination.Having
read_message_historyis needed to retrieve message history.Changed in version 2.0: The
reasonkeyword-only parameter was added.Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await channel.purge(limit=100, check=is_me) await channel.send(f'Deleted {len(deleted)} message(s)')
- Parameters
limit (Optional[
int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message],bool]) – The function used to check if a message should be deleted. It must take aMessageas its sole parameter.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asbeforeinhistory().after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asafterinhistory().around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asaroundinhistory().oldest_first (Optional[
bool]) – Same asoldest_firstinhistory().reason (Optional[
str]) – The reason for purging the messages. Shows up on the audit log.
- Raises
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
- Returns
The list of messages that were deleted.
- Return type
List[
Message]
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this channel.
You must have
manage_webhooksto do this.
- await create_webhook(*, name, avatar=None, reason=None)¶
This function is a coroutine.
Creates a webhook for this channel.
You must have
manage_webhooksto do this.Changed in version 1.1: Added the
reasonkeyword-only parameter.- Parameters
name (
str) – The webhook’s name.avatar (Optional[
bytes]) – A bytes-like object representing the webhook’s default avatar. This operates similarly toedit().reason (Optional[
str]) – The reason for creating this webhook. Shows up in the audit logs.
- Raises
HTTPException – Creating the webhook failed.
Forbidden – You do not have permissions to create a webhook.
- Returns
The created webhook.
- Return type
- await follow(*, destination, reason=None)¶
This function is a coroutine.
Follows a channel using a webhook.
Only news channels can be followed.
Note
The webhook returned will not provide a token to do webhook actions, as Discord does not provide it.
New in version 1.3.
Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
destination (
TextChannel) – The channel you would like to follow from.reason (Optional[
str]) –The reason for following the channel. Shows up on the destination guild’s audit log.
New in version 1.4.
- Raises
HTTPException – Following the channel failed.
Forbidden – You do not have the permissions to create a webhook.
ClientException – The channel is not a news channel.
TypeError – The destination channel is not a text channel.
- Returns
The created webhook.
- Return type
- get_partial_message(message_id, /)¶
Creates a
PartialMessagefrom the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 1.6.
Changed in version 2.0:
message_idparameter is now positional-only.- Parameters
message_id (
int) – The message ID to create a partial message for.- Returns
The partial message.
- Return type
- get_thread(thread_id, /)¶
Returns a thread with the given ID.
Note
This does not always retrieve archived threads, as they are not retained in the internal cache. Use
Guild.fetch_channel()instead.New in version 2.0.
- await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None, invitable=True, slowmode_delay=None)¶
This function is a coroutine.
Creates a thread in this text channel.
To create a public thread, you must have
create_public_threads. For a private thread,create_private_threadsis needed instead.New in version 2.0.
- Parameters
name (
str) – The name of the thread.message (Optional[
abc.Snowflake]) – A snowflake representing the message to create the thread with. IfNoneis passed then a private thread is created. Defaults toNone.auto_archive_duration (
int) –The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used.
Must be one of
60,1440,4320, or10080, if provided.type (Optional[
ChannelType]) – The type of thread to create. If amessageis passed then this parameter is ignored, as a thread created with a message is always a public thread. By default this creates a private thread if this isNone.reason (Optional[
str]) – The reason for creating a new thread. Shows up on the audit log.invitable (
bool) – Whether non-moderators can add users to the thread. Only applicable to private threads. Defaults toTrue.slowmode_delay (Optional[
int]) – Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is21600. By default no slowmode rate limit if this isNone.
- Raises
Forbidden – You do not have permissions to create a thread.
HTTPException – Starting the thread failed.
- Returns
The created thread
- Return type
- async for ... in archived_threads(*, private=False, joined=False, limit=100, before=None)¶
Returns an asynchronous iterator that iterates over all archived threads in this text channel, in order of decreasing ID for joined threads, and decreasing
Thread.archive_timestampotherwise.You must have
read_message_historyto do this. If iterating over private threads thenmanage_threadsis also required.New in version 2.0.
- Parameters
limit (Optional[
bool]) – The number of threads to retrieve. IfNone, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve archived channels before the given date or ID.private (
bool) – Whether to retrieve private archived threads.joined (
bool) – Whether to retrieve private archived threads that you’ve joined. You cannot setjoinedtoTrueandprivatetoFalse.
- Raises
Forbidden – You do not have permissions to get archived threads.
HTTPException – The request to get the archived threads failed.
ValueError –
joinedwas set toTrueandprivatewas set toFalse. You cannot retrieve public archived threads that you have joined.
- Yields
Thread– The archived threads.
- await ack()¶
This function is a coroutine.
Marks every message in this channel as read.
- Raises
HTTPException – Acking the channel failed.
- await ack_pins()¶
This function is a coroutine.
Marks a channel’s pins as viewed.
- Raises
HTTPException – Acking the pinned messages failed.
- property category¶
The category this channel belongs to.
If there is no category then this is
None.- Type
Optional[
CategoryChannel]
- property changed_roles¶
Returns a list of roles that have been overridden from their default values in the
rolesattribute.- Type
List[
Role]
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, validate, target_type=None, target_user=None, target_application=None)¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have
create_instant_inviteto do this.- Parameters
max_age (
int) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse.unique (
bool) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalsethen it will return a previously created invite.validate (Union[
Invite,str]) –The existing channel invite to validate and return for reuse. If this invite is invalid, a new invite will be created according to the parameters and returned.
New in version 2.0.
target_type (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
New in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.New in version 2.0.
target_application: –
Optional[
Application]: The embedded application for the invite, required iftarget_typeisInviteTarget.embedded_application.New in version 2.0.
reason (Optional[
str]) – The reason for creating this invite. Shows up on the audit log.
- Raises
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns
The invite that was created.
- Return type
- property created_at¶
Returns the channel’s creation time in UTC.
- Type
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the channel.
You must have
manage_channelsto do this.- Parameters
reason (Optional[
str]) – The reason for deleting this channel. Shows up on the audit log.- Raises
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters
id (
int) – The message ID to look for.- 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.
- Returns
The message asked for.
- Return type
- await greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...)¶
This function is a coroutine.
Sends a sticker greeting to the destination.
A sticker greeting is used to begin a new DM or reply to a system message.
New in version 2.0.
- Parameters
sticker (Union[
GuildSticker,StickerItem]) – The sticker to greet with.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead. In the case of greeting, onlyreplied_useris considered.reference (Union[
Message,MessageReference,PartialMessage]) – A reference to theMessageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.mention_author (
bool) – If set, overrides thereplied_userattribute ofallowed_mentions.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
TypeError – The
referenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The sticker greeting that was sent.
- Return type
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an asynchronous iterator that enables receiving the destination’s message history.
You must have
read_message_historyto do this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in channel.history(limit=123)] # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. 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 messages after this date or message. 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.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields
Message– The message with the message data parsed.
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channelsto get this information.- Raises
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns
The list of invites that are currently active.
- Return type
List[
Invite]
- property jump_url¶
Returns a URL that allows the client to jump to the channel.
New in version 2.0.
- Type
- await move(**kwargs)¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have
manage_channelsto do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
beginning (
bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend,before, andafter.end (
bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning,before, andafter.before (
Snowflake) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (
Snowflake) – The channel that should be after our current channel. This is mutually exclusive withbeginning,end, andbefore.offset (
int) – The number of channels to offset the move by. For example, an offset of2withbeginning=Truewould move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning,end,before, andafterparameters.category (Optional[
Snowflake]) – The category to move this channel under. IfNoneis given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool) – Whether to sync the permissions with the category (if given).reason (
str) – The reason for the move.
- Raises
ValueError – An invalid position was given.
TypeError – A bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- property notification_settings¶
Returns the notification settings for this channel.
If not found, an instance is created with defaults applied. This follows Discord behaviour.
New in version 2.0.
- Type
- property overwrites¶
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Roleor aMemberand the value is the overwrite as aPermissionOverwrite.Changed in version 2.0: Overwrites can now be type-aware
Objectin case of cache lookup failure- Returns
The channel’s permission overwrites.
- Return type
Dict[Union[
Role,Member,Object],PermissionOverwrite]
- overwrites_for(obj)¶
Returns the channel-specific overwrites for a member or a role.
- property permissions_synced¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.New in version 1.3.
- Type
- await pins()¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises
Forbidden – You do not have the permission to retrieve pinned messages.
HTTPException – Retrieving the pinned messages failed.
- Returns
The messages that are currently pinned.
- Return type
List[
Message]
- await send(content=None, *, tts=False, file=None, files=None, stickers=None, delete_after=None, nonce=..., allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, silent=False)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then a sticker or file must be sent.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (
int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. Generates one by default.delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.New in version 1.6.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
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.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate size.TypeError – You specified both
fileandfiles, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The message that was sent.
- Return type
- await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)¶
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
targetparameter should either be aMemberor aRolethat belongs to guild.The
overwriteparameter, if given, must either beNoneorPermissionOverwrite. For convenience, you can pass in keyword arguments denotingPermissionsattributes. If this is done, then you cannot mix the keyword arguments with theoverwriteparameter.If the
overwriteparameter isNone, then the permission overwrites are deleted.You must have
manage_rolesto do this.Note
This method replaces the old overwrites with the ones given.
Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwriteoverwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
target (Union[
Member,Role]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
TypeError – The
overwriteparameter was invalid or the target type was notRoleorMember.ValueError – The
overwriteparameter andpositionsparameters were both unset.
- asyncack
- asyncack_pins
- asyncclone
- asyncconnect
- asynccreate_invite
- asynccreate_webhook
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_message
- defget_partial_message
- asyncgreet
- async forhistory
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncpins
- asyncpurge
- asyncsend
- asyncset_permissions
- defslash_commands
- deftyping
- defuser_commands
- asyncwebhooks
- class discord.VoiceChannel¶
Represents a Discord guild voice channel.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns the channel’s name.
- nsfw¶
If the channel is marked as “not safe for work” or “age restricted”.
New in version 2.0.
- Type
- position¶
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type
- rtc_region¶
The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.New in version 1.7.
Changed in version 2.0: The type of this attribute has changed to
str.- Type
Optional[
str]
- video_quality_mode¶
The camera video quality for the voice channel’s participants.
New in version 2.0.
- Type
- last_message_id¶
The last message ID of the message sent to this channel. It may not point to an existing or valid message.
New in version 2.0.
- Type
Optional[
int]
- last_pin_timestamp¶
When the last pinned message was pinned.
Noneif there are no pinned messages.New in version 2.0.
- Type
Optional[
datetime.datetime]
- slowmode_delay¶
The number of seconds a member must wait between sending messages in this channel. A value of
0denotes that it is disabled. Bots and users withmanage_channelsormanage_messagesbypass slowmode.New in version 2.0.
- Type
- async with typing()¶
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using
await.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!')
Example Usage:
await channel.typing() # Do some computational magic for about 10 seconds await channel.send('Done!')
Changed in version 2.0: This no longer works with the
withsyntax,async withmust be used instead.Changed in version 2.0: Added functionality to
awaitthe context manager to send a typing indicator for 10 seconds.
- async for ... in slash_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the slash commands available in the channel.
Examples
Usage
async for command in channel.slash_commands(): print(command.name)
Flattening into a list
commands = [command async for command in channel.slash_commands()] # commands is now a list of SlashCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
SlashCommand– A slash command.
- async for ... in user_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the user commands available to use on the user.
Examples
Usage
async for command in user.user_commands(): print(command.name)
Flattening into a list
commands = [command async for command in user.user_commands()] # commands is now a list of UserCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
UserCommand– A user command.
- property type¶
The channel’s Discord type.
- Type
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have
manage_channelsto do this.New in version 1.1.
- Parameters
- Raises
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns
The channel that was created.
- Return type
- await edit(*, reason=None, **options)¶
This function is a coroutine.
Edits the channel.
You must have
manage_channelsto do this.Changed in version 1.3: The
overwriteskeyword-only parameter was added.Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
Changed in version 2.0: The
regionparameter now acceptsstrinstead of an enum.Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
name (
str) – The new channel’s name.bitrate (
int) – The new channel’s bitrate.nsfw (
bool) – To mark the channel as NSFW or not.user_limit (
int) – The new channel’s user limit.position (
int) – The new channel’s position.sync_permissions (
bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse.category (Optional[
CategoryChannel]) – The new category for this channel. Can beNoneto remove the category.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of0disables slowmode. The maximum value possible is21600.reason (Optional[
str]) – The reason for editing this channel. Shows up on the audit log.overwrites (
Mapping) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.rtc_region (Optional[
str]) –The new region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.New in version 1.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
New in version 2.0.
- Raises
TypeError – If the permission overwrite information is not in proper form.
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
- Returns
The newly edited voice channel. If the edit was only positional then
Noneis returned instead.- Return type
Optional[
VoiceChannel]
- await ack()¶
This function is a coroutine.
Marks every message in this channel as read.
- Raises
HTTPException – Acking the channel failed.
- await ack_pins()¶
This function is a coroutine.
Marks a channel’s pins as viewed.
- Raises
HTTPException – Acking the pinned messages failed.
- property category¶
The category this channel belongs to.
If there is no category then this is
None.- Type
Optional[
CategoryChannel]
- property changed_roles¶
Returns a list of roles that have been overridden from their default values in the
rolesattribute.- Type
List[
Role]
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, _channel=None, self_deaf=False, self_mute=False)¶
This function is a coroutine.
Connects to voice and creates a
VoiceClientto establish your connection to the voice server.- Parameters
timeout (
float) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (Type[
VoiceProtocol]) – A type that subclassesVoiceProtocolto connect with. Defaults toVoiceClient.self_mute (
bool) –Indicates if the client should be self-muted.
New in version 2.0.
self_deaf (
bool) –Indicates if the client should be self-deafened.
New in version 2.0.
- Raises
asyncio.TimeoutError – Could not connect to the voice channel in time.
ClientException – You are already connected to a voice channel.
OpusNotLoaded – The opus library has not been loaded.
- Returns
A voice client that is fully connected to the voice server.
- Return type
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, validate, target_type=None, target_user=None, target_application=None)¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have
create_instant_inviteto do this.- Parameters
max_age (
int) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse.unique (
bool) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalsethen it will return a previously created invite.validate (Union[
Invite,str]) –The existing channel invite to validate and return for reuse. If this invite is invalid, a new invite will be created according to the parameters and returned.
New in version 2.0.
target_type (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
New in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.New in version 2.0.
target_application: –
Optional[
Application]: The embedded application for the invite, required iftarget_typeisInviteTarget.embedded_application.New in version 2.0.
reason (Optional[
str]) – The reason for creating this invite. Shows up on the audit log.
- Raises
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns
The invite that was created.
- Return type
- await create_webhook(*, name, avatar=None, reason=None)¶
This function is a coroutine.
Creates a webhook for this channel.
You must have
manage_webhooksto do this.New in version 2.0.
- Parameters
name (
str) – The webhook’s name.avatar (Optional[
bytes]) – A bytes-like object representing the webhook’s default avatar. This operates similarly toedit().reason (Optional[
str]) – The reason for creating this webhook. Shows up in the audit logs.
- Raises
HTTPException – Creating the webhook failed.
Forbidden – You do not have permissions to create a webhook.
- Returns
The created webhook.
- Return type
- property created_at¶
Returns the channel’s creation time in UTC.
- Type
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the channel.
You must have
manage_channelsto do this.- Parameters
reason (Optional[
str]) – The reason for deleting this channel. Shows up on the audit log.- Raises
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await delete_messages(messages, /, *, reason=None)¶
This function is a coroutine.
Deletes a list of messages. This is similar to
Message.delete()except it bulk deletes multiple messages.You must have
manage_messagesto use this (unless they’re your own).Note
Users do not have access to the message bulk-delete endpoint. Since messages are just iterated over and deleted one-by-one, it’s easy to get ratelimited using this method.
New in version 2.0.
- Parameters
messages (Iterable[
abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.reason (Optional[
str]) – The reason for deleting the messages. Shows up on the audit log.
- Raises
Forbidden – You do not have proper permissions to delete the messages.
HTTPException – Deleting the messages failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters
id (
int) – The message ID to look for.- 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.
- Returns
The message asked for.
- Return type
- get_partial_message(message_id, /)¶
Creates a
PartialMessagefrom the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 2.0.
- Parameters
message_id (
int) – The message ID to create a partial message for.- Returns
The partial message.
- Return type
- await greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...)¶
This function is a coroutine.
Sends a sticker greeting to the destination.
A sticker greeting is used to begin a new DM or reply to a system message.
New in version 2.0.
- Parameters
sticker (Union[
GuildSticker,StickerItem]) – The sticker to greet with.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead. In the case of greeting, onlyreplied_useris considered.reference (Union[
Message,MessageReference,PartialMessage]) – A reference to theMessageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.mention_author (
bool) – If set, overrides thereplied_userattribute ofallowed_mentions.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
TypeError – The
referenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The sticker greeting that was sent.
- Return type
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an asynchronous iterator that enables receiving the destination’s message history.
You must have
read_message_historyto do this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in channel.history(limit=123)] # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. 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 messages after this date or message. 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.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields
Message– The message with the message data parsed.
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channelsto get this information.- Raises
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns
The list of invites that are currently active.
- Return type
List[
Invite]
- property jump_url¶
Returns a URL that allows the client to jump to the channel.
New in version 2.0.
- Type
- property last_message¶
Retrieves the last message from this channel in cache.
The message might not be valid or point to an existing message.
New in version 2.0.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either
history()orfetch_message()with thelast_message_idattribute.- Returns
The last message in this channel or
Noneif not found.- Return type
Optional[
Message]
- property members¶
Returns all members that are currently inside this voice channel.
- Type
List[
Member]
- await move(**kwargs)¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have
manage_channelsto do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
beginning (
bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend,before, andafter.end (
bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning,before, andafter.before (
Snowflake) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (
Snowflake) – The channel that should be after our current channel. This is mutually exclusive withbeginning,end, andbefore.offset (
int) – The number of channels to offset the move by. For example, an offset of2withbeginning=Truewould move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning,end,before, andafterparameters.category (Optional[
Snowflake]) – The category to move this channel under. IfNoneis given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool) – Whether to sync the permissions with the category (if given).reason (
str) – The reason for the move.
- Raises
ValueError – An invalid position was given.
TypeError – A bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- property notification_settings¶
Returns the notification settings for this channel.
If not found, an instance is created with defaults applied. This follows Discord behaviour.
New in version 2.0.
- Type
- property overwrites¶
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Roleor aMemberand the value is the overwrite as aPermissionOverwrite.Changed in version 2.0: Overwrites can now be type-aware
Objectin case of cache lookup failure- Returns
The channel’s permission overwrites.
- Return type
Dict[Union[
Role,Member,Object],PermissionOverwrite]
- overwrites_for(obj)¶
Returns the channel-specific overwrites for a member or a role.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Implicit permissions
Member timeout
If a
Roleis passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The permissions of the role used as a parameter
The default role permission overwrites
The permission overwrites of the role used as a parameter
Changed in version 2.0: The object passed in can now be a role object.
Changed in version 2.0:
objparameter is now positional-only.
- property permissions_synced¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.New in version 1.3.
- Type
- await pins()¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises
Forbidden – You do not have the permission to retrieve pinned messages.
HTTPException – Retrieving the pinned messages failed.
- Returns
The messages that are currently pinned.
- Return type
List[
Message]
- await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, reason=None)¶
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check. If acheckis not provided then all messages are deleted without discrimination.Having
read_message_historyis needed to retrieve message history.New in version 2.0.
Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await channel.purge(limit=100, check=is_me) await channel.send(f'Deleted {len(deleted)} message(s)')
- Parameters
limit (Optional[
int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message],bool]) – The function used to check if a message should be deleted. It must take aMessageas its sole parameter.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asbeforeinhistory().after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asafterinhistory().around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asaroundinhistory().oldest_first (Optional[
bool]) – Same asoldest_firstinhistory().reason (Optional[
str]) – The reason for purging the messages. Shows up on the audit log.
- Raises
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
- Returns
The list of messages that were deleted.
- Return type
List[
Message]
- property scheduled_events¶
Returns all scheduled events for this channel.
New in version 2.0.
- Type
List[
ScheduledEvent]
- await send(content=None, *, tts=False, file=None, files=None, stickers=None, delete_after=None, nonce=..., allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, silent=False)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then a sticker or file must be sent.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (
int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. Generates one by default.delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.New in version 1.6.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
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.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate size.TypeError – You specified both
fileandfiles, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The message that was sent.
- Return type
- await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)¶
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
targetparameter should either be aMemberor aRolethat belongs to guild.The
overwriteparameter, if given, must either beNoneorPermissionOverwrite. For convenience, you can pass in keyword arguments denotingPermissionsattributes. If this is done, then you cannot mix the keyword arguments with theoverwriteparameter.If the
overwriteparameter isNone, then the permission overwrites are deleted.You must have
manage_rolesto do this.Note
This method replaces the old overwrites with the ones given.
Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwriteoverwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
target (Union[
Member,Role]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
TypeError – The
overwriteparameter was invalid or the target type was notRoleorMember.ValueError – The
overwriteparameter andpositionsparameters were both unset.
- property voice_states¶
Returns a mapping of member IDs who have voice states in this channel.
New in version 1.3.
Note
This function is intentionally low level to replace
memberswhen the member cache is unavailable.- Returns
The mapping of member ID to a voice state.
- Return type
Mapping[
int,VoiceState]
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this channel.
You must have
manage_webhooksto do this.New in version 2.0.
- bitrate
- category
- category_id
- changed_roles
- created_at
- guild
- id
- instance
- jump_url
- last_message
- last_message_id
- last_pin_timestamp
- listeners
- members
- mention
- moderators
- name
- notification_settings
- nsfw
- overwrites
- permissions_synced
- position
- requesting_to_speak
- rtc_region
- scheduled_events
- slowmode_delay
- speakers
- topic
- type
- user_limit
- video_quality_mode
- voice_states
- asyncack
- asyncack_pins
- asyncclone
- asyncconnect
- asynccreate_instance
- asynccreate_invite
- asynccreate_webhook
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_instance
- asyncfetch_message
- defget_partial_message
- asyncgreet
- async forhistory
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncpins
- asyncpurge
- asyncsend
- asyncset_permissions
- defslash_commands
- deftyping
- defuser_commands
- asyncwebhooks
- class discord.StageChannel¶
Represents a Discord guild stage channel.
New in version 1.7.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns the channel’s name.
- nsfw¶
If the channel is marked as “not safe for work” or “age restricted”.
New in version 2.0.
- Type
- position¶
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type
- rtc_region¶
The region for the stage channel’s voice communication. A value of
Noneindicates automatic voice region detection.- Type
Optional[
str]
- video_quality_mode¶
The camera video quality for the stage channel’s participants.
New in version 2.0.
- Type
- last_message_id¶
The last message ID of the message sent to this channel. It may not point to an existing or valid message.
New in version 2.0.
- Type
Optional[
int]
- last_pin_timestamp¶
When the last pinned message was pinned.
Noneif there are no pinned messages.New in version 2.0.
- Type
Optional[
datetime.datetime]
- slowmode_delay¶
The number of seconds a member must wait between sending messages in this channel. A value of
0denotes that it is disabled. Bots and users withmanage_channelsormanage_messagesbypass slowmode.New in version 2.0.
- Type
- property requesting_to_speak¶
A list of members who are requesting to speak in the stage channel.
- Type
List[
Member]
- property speakers¶
A list of members who have been permitted to speak in the stage channel.
New in version 2.0.
- Type
List[
Member]
- property listeners¶
A list of members who are listening in the stage channel.
New in version 2.0.
- Type
List[
Member]
- property moderators¶
A list of members who are moderating the stage channel.
New in version 2.0.
- Type
List[
Member]
- property type¶
The channel’s Discord type.
- Type
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have
manage_channelsto do this.New in version 1.1.
- Parameters
- Raises
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns
The channel that was created.
- Return type
- property instance¶
The running stage instance of the stage channel.
New in version 2.0.
- Type
Optional[
StageInstance]
- await create_instance(*, topic, privacy_level=..., send_start_notification=False, reason=None)¶
This function is a coroutine.
Create a stage instance.
You must have
manage_channelsto do this.New in version 2.0.
- Parameters
topic (
str) – The stage instance’s topic.privacy_level (
PrivacyLevel) – The stage instance’s privacy level. Defaults toPrivacyLevel.guild_only.send_start_notification (
bool) – Whether to send a start notification. This sends a push notification to @everyone ifTrue. Defaults toFalse. You must havemention_everyoneto do this.reason (
str) – The reason the stage instance was created. Shows up on the audit log.
- Raises
TypeError – If the
privacy_levelparameter is not the proper type.Forbidden – You do not have permissions to create a stage instance.
HTTPException – Creating a stage instance failed.
- Returns
The newly created stage instance.
- Return type
- await fetch_instance()¶
This function is a coroutine.
Gets the running
StageInstance.New in version 2.0.
- Raises
NotFound – The stage instance or channel could not be found.
HTTPException – Getting the stage instance failed.
- Returns
The stage instance.
- Return type
- await edit(*, reason=None, **options)¶
This function is a coroutine.
Edits the channel.
You must have
manage_channelsto do this.Changed in version 2.0: The
topicparameter must now be set viacreate_instance.Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
Changed in version 2.0: The
regionparameter now acceptsstrinstead of an enum.Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
name (
str) – The new channel’s name.position (
int) – The new channel’s position.nsfw (
bool) – To mark the channel as NSFW or not.sync_permissions (
bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse.category (Optional[
CategoryChannel]) – The new category for this channel. Can beNoneto remove the category.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of0disables slowmode. The maximum value possible is21600.reason (Optional[
str]) – The reason for editing this channel. Shows up on the audit log.overwrites (
Mapping) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.rtc_region (Optional[
str]) – The new region for the stage channel’s voice communication. A value ofNoneindicates automatic voice region detection.video_quality_mode (
VideoQualityMode) –The camera video quality for the stage channel’s participants.
New in version 2.0.
- Raises
ValueError – If the permission overwrite information is not in proper form.
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
- Returns
The newly edited stage channel. If the edit was only positional then
Noneis returned instead.- Return type
Optional[
StageChannel]
- await ack()¶
This function is a coroutine.
Marks every message in this channel as read.
- Raises
HTTPException – Acking the channel failed.
- await ack_pins()¶
This function is a coroutine.
Marks a channel’s pins as viewed.
- Raises
HTTPException – Acking the pinned messages failed.
- property category¶
The category this channel belongs to.
If there is no category then this is
None.- Type
Optional[
CategoryChannel]
- property changed_roles¶
Returns a list of roles that have been overridden from their default values in the
rolesattribute.- Type
List[
Role]
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, _channel=None, self_deaf=False, self_mute=False)¶
This function is a coroutine.
Connects to voice and creates a
VoiceClientto establish your connection to the voice server.- Parameters
timeout (
float) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (Type[
VoiceProtocol]) – A type that subclassesVoiceProtocolto connect with. Defaults toVoiceClient.self_mute (
bool) –Indicates if the client should be self-muted.
New in version 2.0.
self_deaf (
bool) –Indicates if the client should be self-deafened.
New in version 2.0.
- Raises
asyncio.TimeoutError – Could not connect to the voice channel in time.
ClientException – You are already connected to a voice channel.
OpusNotLoaded – The opus library has not been loaded.
- Returns
A voice client that is fully connected to the voice server.
- Return type
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, validate, target_type=None, target_user=None, target_application=None)¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have
create_instant_inviteto do this.- Parameters
max_age (
int) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse.unique (
bool) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalsethen it will return a previously created invite.validate (Union[
Invite,str]) –The existing channel invite to validate and return for reuse. If this invite is invalid, a new invite will be created according to the parameters and returned.
New in version 2.0.
target_type (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
New in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.New in version 2.0.
target_application: –
Optional[
Application]: The embedded application for the invite, required iftarget_typeisInviteTarget.embedded_application.New in version 2.0.
reason (Optional[
str]) – The reason for creating this invite. Shows up on the audit log.
- Raises
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns
The invite that was created.
- Return type
- await create_webhook(*, name, avatar=None, reason=None)¶
This function is a coroutine.
Creates a webhook for this channel.
You must have
manage_webhooksto do this.New in version 2.0.
- Parameters
name (
str) – The webhook’s name.avatar (Optional[
bytes]) – A bytes-like object representing the webhook’s default avatar. This operates similarly toedit().reason (Optional[
str]) – The reason for creating this webhook. Shows up in the audit logs.
- Raises
HTTPException – Creating the webhook failed.
Forbidden – You do not have permissions to create a webhook.
- Returns
The created webhook.
- Return type
- property created_at¶
Returns the channel’s creation time in UTC.
- Type
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the channel.
You must have
manage_channelsto do this.- Parameters
reason (Optional[
str]) – The reason for deleting this channel. Shows up on the audit log.- Raises
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await delete_messages(messages, /, *, reason=None)¶
This function is a coroutine.
Deletes a list of messages. This is similar to
Message.delete()except it bulk deletes multiple messages.You must have
manage_messagesto use this (unless they’re your own).Note
Users do not have access to the message bulk-delete endpoint. Since messages are just iterated over and deleted one-by-one, it’s easy to get ratelimited using this method.
New in version 2.0.
- Parameters
messages (Iterable[
abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.reason (Optional[
str]) – The reason for deleting the messages. Shows up on the audit log.
- Raises
Forbidden – You do not have proper permissions to delete the messages.
HTTPException – Deleting the messages failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters
id (
int) – The message ID to look for.- 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.
- Returns
The message asked for.
- Return type
- get_partial_message(message_id, /)¶
Creates a
PartialMessagefrom the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 2.0.
- Parameters
message_id (
int) – The message ID to create a partial message for.- Returns
The partial message.
- Return type
- await greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...)¶
This function is a coroutine.
Sends a sticker greeting to the destination.
A sticker greeting is used to begin a new DM or reply to a system message.
New in version 2.0.
- Parameters
sticker (Union[
GuildSticker,StickerItem]) – The sticker to greet with.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead. In the case of greeting, onlyreplied_useris considered.reference (Union[
Message,MessageReference,PartialMessage]) – A reference to theMessageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.mention_author (
bool) – If set, overrides thereplied_userattribute ofallowed_mentions.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
TypeError – The
referenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The sticker greeting that was sent.
- Return type
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an asynchronous iterator that enables receiving the destination’s message history.
You must have
read_message_historyto do this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in channel.history(limit=123)] # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. 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 messages after this date or message. 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.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields
Message– The message with the message data parsed.
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channelsto get this information.- Raises
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns
The list of invites that are currently active.
- Return type
List[
Invite]
- property jump_url¶
Returns a URL that allows the client to jump to the channel.
New in version 2.0.
- Type
- property last_message¶
Retrieves the last message from this channel in cache.
The message might not be valid or point to an existing message.
New in version 2.0.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either
history()orfetch_message()with thelast_message_idattribute.- Returns
The last message in this channel or
Noneif not found.- Return type
Optional[
Message]
- property members¶
Returns all members that are currently inside this voice channel.
- Type
List[
Member]
- await move(**kwargs)¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have
manage_channelsto do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
beginning (
bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend,before, andafter.end (
bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning,before, andafter.before (
Snowflake) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (
Snowflake) – The channel that should be after our current channel. This is mutually exclusive withbeginning,end, andbefore.offset (
int) – The number of channels to offset the move by. For example, an offset of2withbeginning=Truewould move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning,end,before, andafterparameters.category (Optional[
Snowflake]) – The category to move this channel under. IfNoneis given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool) – Whether to sync the permissions with the category (if given).reason (
str) – The reason for the move.
- Raises
ValueError – An invalid position was given.
TypeError – A bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- property notification_settings¶
Returns the notification settings for this channel.
If not found, an instance is created with defaults applied. This follows Discord behaviour.
New in version 2.0.
- Type
- property overwrites¶
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Roleor aMemberand the value is the overwrite as aPermissionOverwrite.Changed in version 2.0: Overwrites can now be type-aware
Objectin case of cache lookup failure- Returns
The channel’s permission overwrites.
- Return type
Dict[Union[
Role,Member,Object],PermissionOverwrite]
- overwrites_for(obj)¶
Returns the channel-specific overwrites for a member or a role.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Implicit permissions
Member timeout
If a
Roleis passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The permissions of the role used as a parameter
The default role permission overwrites
The permission overwrites of the role used as a parameter
Changed in version 2.0: The object passed in can now be a role object.
Changed in version 2.0:
objparameter is now positional-only.
- property permissions_synced¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.New in version 1.3.
- Type
- await pins()¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises
Forbidden – You do not have the permission to retrieve pinned messages.
HTTPException – Retrieving the pinned messages failed.
- Returns
The messages that are currently pinned.
- Return type
List[
Message]
- await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, reason=None)¶
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check. If acheckis not provided then all messages are deleted without discrimination.Having
read_message_historyis needed to retrieve message history.New in version 2.0.
Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await channel.purge(limit=100, check=is_me) await channel.send(f'Deleted {len(deleted)} message(s)')
- Parameters
limit (Optional[
int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message],bool]) – The function used to check if a message should be deleted. It must take aMessageas its sole parameter.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asbeforeinhistory().after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asafterinhistory().around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asaroundinhistory().oldest_first (Optional[
bool]) – Same asoldest_firstinhistory().reason (Optional[
str]) – The reason for purging the messages. Shows up on the audit log.
- Raises
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
- Returns
The list of messages that were deleted.
- Return type
List[
Message]
- property scheduled_events¶
Returns all scheduled events for this channel.
New in version 2.0.
- Type
List[
ScheduledEvent]
- await send(content=None, *, tts=False, file=None, files=None, stickers=None, delete_after=None, nonce=..., allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, silent=False)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then a sticker or file must be sent.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (
int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. Generates one by default.delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.New in version 1.6.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
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.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate size.TypeError – You specified both
fileandfiles, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The message that was sent.
- Return type
- await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)¶
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
targetparameter should either be aMemberor aRolethat belongs to guild.The
overwriteparameter, if given, must either beNoneorPermissionOverwrite. For convenience, you can pass in keyword arguments denotingPermissionsattributes. If this is done, then you cannot mix the keyword arguments with theoverwriteparameter.If the
overwriteparameter isNone, then the permission overwrites are deleted.You must have
manage_rolesto do this.Note
This method replaces the old overwrites with the ones given.
Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwriteoverwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
target (Union[
Member,Role]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
TypeError – The
overwriteparameter was invalid or the target type was notRoleorMember.ValueError – The
overwriteparameter andpositionsparameters were both unset.
- slash_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the slash commands available in the channel.
Examples
Usage
async for command in channel.slash_commands(): print(command.name)
Flattening into a list
commands = [command async for command in channel.slash_commands()] # commands is now a list of SlashCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
SlashCommand– A slash command.
- typing()¶
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using
await.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!')
Example Usage:
await channel.typing() # Do some computational magic for about 10 seconds await channel.send('Done!')
Changed in version 2.0: This no longer works with the
withsyntax,async withmust be used instead.Changed in version 2.0: Added functionality to
awaitthe context manager to send a typing indicator for 10 seconds.
- user_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the user commands available to use on the user.
Examples
Usage
async for command in user.user_commands(): print(command.name)
Flattening into a list
commands = [command async for command in user.user_commands()] # commands is now a list of UserCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
UserCommand– A user command.
- property voice_states¶
Returns a mapping of member IDs who have voice states in this channel.
New in version 1.3.
Note
This function is intentionally low level to replace
memberswhen the member cache is unavailable.- Returns
The mapping of member ID to a voice state.
- Return type
Mapping[
int,VoiceState]
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this channel.
You must have
manage_webhooksto do this.New in version 2.0.
- available_tags
- category
- category_id
- changed_roles
- created_at
- default_auto_archive_duration
- default_layout
- default_reaction_emoji
- default_sort_order
- default_thread_slowmode_delay
- flags
- guild
- id
- jump_url
- last_message_id
- mention
- name
- notification_settings
- nsfw
- overwrites
- permissions_synced
- position
- slowmode_delay
- threads
- topic
- type
- async forarchived_threads
- asyncclone
- asynccreate_invite
- asynccreate_tag
- asynccreate_thread
- asynccreate_webhook
- asyncdelete
- asyncedit
- defget_tag
- defget_thread
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncset_permissions
- asyncwebhooks
- class discord.ForumChannel¶
Represents a Discord guild forum channel.
- x == y
Checks if two forums are equal.
- x != y
Checks if two forums are not equal.
- hash(x)
Returns the forum’s hash.
- str(x)
Returns the forum’s name.
New in version 2.0.
- topic¶
The forum’s topic.
Noneif it doesn’t exist. Called “Guidelines” in the UI. Can be up to 4096 characters long.- Type
Optional[
str]
- position¶
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type
- last_message_id¶
The last thread ID that was created on this forum. This technically also coincides with the message ID that started the thread that was created. It may not point to an existing or valid thread or message.
- Type
Optional[
int]
- slowmode_delay¶
The number of seconds a member must wait between creating threads in this forum. A value of
0denotes that it is disabled. Bots and users withmanage_channelsormanage_messagesbypass slowmode.- Type
- default_auto_archive_duration¶
The default auto archive duration in minutes for threads created in this forum.
- Type
- default_thread_slowmode_delay¶
The default slowmode delay in seconds for threads created in this forum.
- Type
- default_reaction_emoji¶
The default reaction emoji for threads created in this forum to show in the add reaction button.
- Type
Optional[
PartialEmoji]
- default_layout¶
The default layout for posts in this forum channel. Defaults to
ForumLayoutType.not_set.- Type
- default_sort_order¶
The default sort order for posts in this forum channel.
- Type
Optional[
ForumOrderType]
- property type¶
The channel’s Discord type.
- Type
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Implicit permissions
Member timeout
If a
Roleis passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The permissions of the role used as a parameter
The default role permission overwrites
The permission overwrites of the role used as a parameter
Changed in version 2.0: The object passed in can now be a role object.
Changed in version 2.0:
objparameter is now positional-only.
- get_thread(thread_id, /)¶
Returns a thread with the given ID.
Note
This does not always retrieve archived threads, as they are not retained in the internal cache. Use
Guild.fetch_channel()instead.
- property flags¶
The flags associated with this forum.
- Type
- get_tag(tag_id, /)¶
Returns the tag with the given ID.
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have
manage_channelsto do this.New in version 1.1.
- Parameters
- Raises
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns
The channel that was created.
- Return type
- await edit(*, reason=None, **options)¶
This function is a coroutine.
Edits the forum.
You must have
manage_channelsto do this.- Parameters
name (
str) – The new forum name.topic (
str) – The new forum’s topic.position (
int) – The new forum’s position.nsfw (
bool) – To mark the forum as NSFW or not.sync_permissions (
bool) – Whether to sync permissions with the forum’s new or pre-existing category. Defaults toFalse.category (Optional[
CategoryChannel]) – The new category for this forum. Can beNoneto remove the category.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this forum, in seconds. A value of0disables slowmode. The maximum value possible is21600.type (
ChannelType) – Change the type of this text forum. Currently, only conversion betweenChannelType.textandChannelType.newsis supported. This is only available to guilds that containNEWSinGuild.features.reason (Optional[
str]) – The reason for editing this forum. Shows up on the audit log.overwrites (
Mapping) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the forum.default_auto_archive_duration (
int) – The new default auto archive duration in minutes for threads created in this channel. Must be one of60,1440,4320, or10080.available_tags (Sequence[
ForumTag]) – The new available tags for this forum.default_thread_slowmode_delay (
int) – The new default slowmode delay for threads in this channel.default_reaction_emoji (Optional[Union[
Emoji,PartialEmoji,str]]) – The new default reaction emoji for threads in this channel.default_layout (
ForumLayoutType) – The new default layout for posts in this forum.default_sort_order (Optional[
ForumOrderType]) – The new default sort order for posts in this forum.require_tag (
bool) – Whether to require a tag for threads in this channel or not.
- Raises
ValueError – The new
positionis less than 0 or greater than the number of channels.TypeError – The permission overwrite information is not in proper form or a type is not the expected type.
Forbidden – You do not have permissions to edit the forum.
HTTPException – Editing the forum failed.
- Returns
The newly edited forum channel. If the edit was only positional then
Noneis returned instead.- Return type
Optional[
ForumChannel]
- await create_tag(*, name, emoji, moderated=False, reason=None)¶
This function is a coroutine.
Creates a new tag in this forum.
You must have
manage_channelsto do this.- Parameters
name (
str) – The name of the tag. Can only be up to 20 characters.emoji (Union[
str,PartialEmoji]) – The emoji to use for the tag.moderated (
bool) – Whether the tag can only be applied by moderators.reason (Optional[
str]) – The reason for creating this tag. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to create a tag in this forum.
HTTPException – Creating the tag failed.
- Returns
The newly created tag.
- Return type
- await create_thread(*, name, auto_archive_duration=..., slowmode_delay=None, content=None, tts=False, file=..., files=..., stickers=..., allowed_mentions=..., mention_author=..., applied_tags=..., suppress_embeds=False, reason=None)¶
This function is a coroutine.
Creates a thread in this forum.
This thread is a public thread with the initial message given. Currently in order to start a thread in this forum, the user needs
send_messages.You must send at least one of
content,embed,embeds,file,files, orviewto create a thread in a forum, since forum channels must have a starter message.- Parameters
name (
str) – The name of the thread.auto_archive_duration (
int) –The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used.
Must be one of
60,1440,4320, or10080, if provided.slowmode_delay (Optional[
int]) – Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is21600. By default no slowmode rate limit if this isNone.content (Optional[
str]) – The content of the message to send with the thread.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.mention_author (
bool) – If set, overrides thereplied_userattribute ofallowed_mentions.applied_tags (List[
discord.ForumTag]) – A list of tags to apply to the thread.stickers (Sequence[Union[
GuildSticker,StickerItem]]) – A list of stickers to upload. Must be a maximum of 3.suppress_embeds (
bool) – Whether to suppress embeds for the message. This sends the message without any embeds if set toTrue.reason (
str) – The reason for creating a new thread. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to create a thread.
HTTPException – Starting the thread failed.
ValueError – The
filesorembedslist is not of the appropriate size.TypeError – You specified both
fileandfiles, or you specified bothembedandembeds.
- Returns
The created thread with the created message. This is also accessible as a namedtuple with
threadandmessagefields.- Return type
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this channel.
You must have
manage_webhooksto do this.
- await create_webhook(*, name, avatar=None, reason=None)¶
This function is a coroutine.
Creates a webhook for this channel.
You must have
manage_webhooksto do this.- Parameters
name (
str) – The webhook’s name.avatar (Optional[
bytes]) – A bytes-like object representing the webhook’s default avatar. This operates similarly toedit().reason (Optional[
str]) – The reason for creating this webhook. Shows up in the audit logs.
- Raises
HTTPException – Creating the webhook failed.
Forbidden – You do not have permissions to create a webhook.
- Returns
The created webhook.
- Return type
- async for ... in archived_threads(*, limit=100, before=None)¶
Returns an asynchronous iterator that iterates over all archived threads in this forum in order of decreasing
Thread.archive_timestamp.You must have
read_message_historyto do this.- Parameters
limit (Optional[
bool]) – The number of threads to retrieve. IfNone, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve archived channels before the given date or ID.
- Raises
Forbidden – You do not have permissions to get archived threads.
HTTPException – The request to get the archived threads failed.
- Yields
Thread– The archived threads.
- property category¶
The category this channel belongs to.
If there is no category then this is
None.- Type
Optional[
CategoryChannel]
- property changed_roles¶
Returns a list of roles that have been overridden from their default values in the
rolesattribute.- Type
List[
Role]
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, validate, target_type=None, target_user=None, target_application=None)¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have
create_instant_inviteto do this.- Parameters
max_age (
int) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse.unique (
bool) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalsethen it will return a previously created invite.validate (Union[
Invite,str]) –The existing channel invite to validate and return for reuse. If this invite is invalid, a new invite will be created according to the parameters and returned.
New in version 2.0.
target_type (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
New in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.New in version 2.0.
target_application: –
Optional[
Application]: The embedded application for the invite, required iftarget_typeisInviteTarget.embedded_application.New in version 2.0.
reason (Optional[
str]) – The reason for creating this invite. Shows up on the audit log.
- Raises
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns
The invite that was created.
- Return type
- property created_at¶
Returns the channel’s creation time in UTC.
- Type
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the channel.
You must have
manage_channelsto do this.- Parameters
reason (Optional[
str]) – The reason for deleting this channel. Shows up on the audit log.- Raises
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channelsto get this information.- Raises
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns
The list of invites that are currently active.
- Return type
List[
Invite]
- property jump_url¶
Returns a URL that allows the client to jump to the channel.
New in version 2.0.
- Type
- await move(**kwargs)¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have
manage_channelsto do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
beginning (
bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend,before, andafter.end (
bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning,before, andafter.before (
Snowflake) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (
Snowflake) – The channel that should be after our current channel. This is mutually exclusive withbeginning,end, andbefore.offset (
int) – The number of channels to offset the move by. For example, an offset of2withbeginning=Truewould move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning,end,before, andafterparameters.category (Optional[
Snowflake]) – The category to move this channel under. IfNoneis given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool) – Whether to sync the permissions with the category (if given).reason (
str) – The reason for the move.
- Raises
ValueError – An invalid position was given.
TypeError – A bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- property notification_settings¶
Returns the notification settings for this channel.
If not found, an instance is created with defaults applied. This follows Discord behaviour.
New in version 2.0.
- Type
- property overwrites¶
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Roleor aMemberand the value is the overwrite as aPermissionOverwrite.Changed in version 2.0: Overwrites can now be type-aware
Objectin case of cache lookup failure- Returns
The channel’s permission overwrites.
- Return type
Dict[Union[
Role,Member,Object],PermissionOverwrite]
- overwrites_for(obj)¶
Returns the channel-specific overwrites for a member or a role.
- property permissions_synced¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.New in version 1.3.
- Type
- await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)¶
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
targetparameter should either be aMemberor aRolethat belongs to guild.The
overwriteparameter, if given, must either beNoneorPermissionOverwrite. For convenience, you can pass in keyword arguments denotingPermissionsattributes. If this is done, then you cannot mix the keyword arguments with theoverwriteparameter.If the
overwriteparameter isNone, then the permission overwrites are deleted.You must have
manage_rolesto do this.Note
This method replaces the old overwrites with the ones given.
Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwriteoverwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
target (Union[
Member,Role]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
TypeError – The
overwriteparameter was invalid or the target type was notRoleorMember.ValueError – The
overwriteparameter andpositionsparameters were both unset.
PrivateChannel¶
- asyncaccept
- asyncack
- asyncack_pins
- asyncclose
- asyncconnect
- asyncdecline
- asyncfetch_message
- defget_partial_message
- asyncgreet
- async forhistory
- defis_accepted
- defis_message_request
- defis_spam
- defpermissions_for
- asyncpins
- asyncsend
- defslash_commands
- deftyping
- defuser_commands
- class discord.DMChannel¶
Represents a Discord direct message channel.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns a string representation of the channel
- me¶
The user presenting yourself.
- Type
- last_message_id¶
The last message ID of the message sent to this channel. It may not point to an existing or valid message.
New in version 2.0.
- Type
Optional[
int]
- last_pin_timestamp¶
When the last pinned message was pinned.
Noneif there are no pinned messages.New in version 2.0.
- Type
Optional[
datetime.datetime]
- async with typing()¶
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using
await.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!')
Example Usage:
await channel.typing() # Do some computational magic for about 10 seconds await channel.send('Done!')
Changed in version 2.0: This no longer works with the
withsyntax,async withmust be used instead.Changed in version 2.0: Added functionality to
awaitthe context manager to send a typing indicator for 10 seconds.
- async for ... in slash_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the slash commands available in the channel.
Examples
Usage
async for command in channel.slash_commands(): print(command.name)
Flattening into a list
commands = [command async for command in channel.slash_commands()] # commands is now a list of SlashCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
SlashCommand– A slash command.
- async for ... in user_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the user commands available to use on the user.
Examples
Usage
async for command in user.user_commands(): print(command.name)
Flattening into a list
commands = [command async for command in user.user_commands()] # commands is now a list of UserCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
UserCommand– A user command.
- property notification_settings¶
Returns the notification settings for this channel.
If not found, an instance is created with defaults applied. This follows Discord behaviour.
New in version 2.0.
- Type
- property call¶
The channel’s currently active call.
- Type
Optional[
PrivateCall]
- property type¶
The channel’s Discord type.
- Type
- property created_at¶
Returns the direct message channel’s creation time in UTC.
- Type
- property guild¶
The guild this DM channel belongs to. Always
None.This is mainly provided for compatibility purposes in duck typing.
New in version 2.0.
- Type
Optional[
Guild]
- property jump_url¶
Returns a URL that allows the client to jump to the channel.
New in version 2.0.
- Type
- property last_message¶
Retrieves the last message from this channel in cache.
The message might not be valid or point to an existing message.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either
history()orfetch_message()with thelast_message_idattribute.- Returns
The last message in this channel or
Noneif not found.- Return type
Optional[
Message]
- property requested_at¶
Returns the message request’s creation time in UTC, if applicable.
New in version 2.0.
- Type
Optional[
datetime.datetime]
- is_message_request()¶
bool: Indicates if the direct message is/was a message request.New in version 2.0.
- is_accepted()¶
bool: Indicates if the message request is accepted. For regular direct messages, this is alwaysTrue.New in version 2.0.
- permissions_for(obj=None, /)¶
Handles permission resolution for a
User.This function is there for compatibility with other channel types.
Actual direct messages do not really have the concept of permissions.
This returns all the Text related permissions set to
Trueexcept:send_tts_messages: You cannot send TTS messages in a DM.manage_messages: You cannot delete others messages in a DM.create_private_threads: There are no threads in a DM.create_public_threads: There are no threads in a DM.manage_threads: There are no threads in a DM.send_messages_in_threads: There are no threads in a DM.
Changed in version 2.0:
objparameter is now positional-only.Changed in version 2.0: Thread related permissions are now set to
False.- Parameters
obj (
Snowflake) – The user to check permissions for. This parameter is ignored but kept for compatibility with otherpermissions_formethods.- Returns
The resolved permissions.
- Return type
- get_partial_message(message_id, /)¶
Creates a
PartialMessagefrom the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 1.6.
Changed in version 2.0:
message_idparameter is now positional-only.- Parameters
message_id (
int) – The message ID to create a partial message for.- Returns
The partial message.
- Return type
- await close()¶
This function is a coroutine.
Closes/”deletes” the channel.
In reality, if you recreate a DM with the same user, all your message history will be there.
- Raises
HTTPException – Closing the channel failed.
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, ring=True)¶
This function is a coroutine.
Connects to voice and creates a
VoiceClientto establish your connection to the voice server.- Parameters
timeout (
float) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (Type[
VoiceProtocol]) – A type that subclassesVoiceProtocolto connect with. Defaults toVoiceClient.ring (
bool) – Whether to ring the other member(s) to join the call, if starting a new call. Defaults toTrue.
- Raises
asyncio.TimeoutError – Could not connect to the voice channel in time.
ClientException – You are already connected to a voice channel.
OpusNotLoaded – The opus library has not been loaded.
- Returns
A voice client that is fully connected to the voice server.
- Return type
- await accept()¶
This function is a coroutine.
Accepts a message request.
- Raises
HTTPException – Accepting the message request failed.
TypeError – The channel is not a message request or the request is already accepted.
- await decline()¶
This function is a coroutine.
Declines a message request. This closes the channel.
- Raises
HTTPException – Declining the message request failed.
TypeError – The channel is not a message request or the request is already accepted.
- await ack()¶
This function is a coroutine.
Marks every message in this channel as read.
- Raises
HTTPException – Acking the channel failed.
- await ack_pins()¶
This function is a coroutine.
Marks a channel’s pins as viewed.
- Raises
HTTPException – Acking the pinned messages failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters
id (
int) – The message ID to look for.- 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.
- Returns
The message asked for.
- Return type
- await greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...)¶
This function is a coroutine.
Sends a sticker greeting to the destination.
A sticker greeting is used to begin a new DM or reply to a system message.
New in version 2.0.
- Parameters
sticker (Union[
GuildSticker,StickerItem]) – The sticker to greet with.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead. In the case of greeting, onlyreplied_useris considered.reference (Union[
Message,MessageReference,PartialMessage]) – A reference to theMessageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.mention_author (
bool) – If set, overrides thereplied_userattribute ofallowed_mentions.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
TypeError – The
referenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The sticker greeting that was sent.
- Return type
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an asynchronous iterator that enables receiving the destination’s message history.
You must have
read_message_historyto do this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in channel.history(limit=123)] # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. 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 messages after this date or message. 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.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields
Message– The message with the message data parsed.
- await pins()¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises
Forbidden – You do not have the permission to retrieve pinned messages.
HTTPException – Retrieving the pinned messages failed.
- Returns
The messages that are currently pinned.
- Return type
List[
Message]
- await send(content=None, *, tts=False, file=None, files=None, stickers=None, delete_after=None, nonce=..., allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, silent=False)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then a sticker or file must be sent.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (
int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. Generates one by default.delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.New in version 1.6.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
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.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate size.TypeError – You specified both
fileandfiles, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The message that was sent.
- Return type
- asyncack
- asyncack_pins
- asyncadd_recipients
- asyncclose
- asyncconnect
- asynccreate_invite
- asyncedit
- asyncfetch_message
- asyncgreet
- async forhistory
- asyncinvites
- asyncleave
- defpermissions_for
- asyncpins
- asyncremove_recipients
- asyncsend
- defslash_commands
- deftyping
- defuser_commands
- class discord.GroupChannel¶
Represents a Discord group channel.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns a string representation of the channel
- last_message_id¶
The last message ID of the message sent to this channel. It may not point to an existing or valid message.
New in version 2.0.
- Type
Optional[
int]
- last_pin_timestamp¶
When the last pinned message was pinned.
Noneif there are no pinned messages.New in version 2.0.
- Type
Optional[
datetime.datetime]
- me¶
The user presenting yourself.
- Type
- managed¶
Whether the group channel is managed by an application.
This restricts the operations that can be performed on the channel, and means
ownerwill usually beNone.New in version 2.0.
- Type
- nicks¶
A mapping of users to their respective nicknames in the group channel.
New in version 2.0.
- async with typing()¶
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using
await.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!')
Example Usage:
await channel.typing() # Do some computational magic for about 10 seconds await channel.send('Done!')
Changed in version 2.0: This no longer works with the
withsyntax,async withmust be used instead.Changed in version 2.0: Added functionality to
awaitthe context manager to send a typing indicator for 10 seconds.
- async for ... in slash_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the slash commands available in the channel.
Examples
Usage
async for command in channel.slash_commands(): print(command.name)
Flattening into a list
commands = [command async for command in channel.slash_commands()] # commands is now a list of SlashCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
SlashCommand– A slash command.
- async for ... in user_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the user commands available to use on the user.
Examples
Usage
async for command in user.user_commands(): print(command.name)
Flattening into a list
commands = [command async for command in user.user_commands()] # commands is now a list of UserCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
UserCommand– A user command.
- property notification_settings¶
Returns the notification settings for this channel.
If not found, an instance is created with defaults applied. This follows Discord behaviour.
New in version 2.0.
- Type
- property call¶
The channel’s currently active call.
- Type
Optional[
PrivateCall]
- property type¶
The channel’s Discord type.
- Type
- property guild¶
The guild this group channel belongs to. Always
None.This is mainly provided for compatibility purposes in duck typing.
New in version 2.0.
- Type
Optional[
Guild]
- property created_at¶
Returns the channel’s creation time in UTC.
- Type
- property jump_url¶
Returns a URL that allows the client to jump to the channel.
New in version 2.0.
- Type
- property last_message¶
Retrieves the last message from this channel in cache.
The message might not be valid or point to an existing message.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either
history()orfetch_message()with thelast_message_idattribute.- Returns
The last message in this channel or
Noneif not found.- Return type
Optional[
Message]
- permissions_for(obj, /)¶
Handles permission resolution for a
User.This function is there for compatibility with other channel types.
Actual direct messages do not really have the concept of permissions.
If a recipient, this returns all the Text related permissions set to
Trueexcept:send_tts_messages: You cannot send TTS messages in a DM.manage_messages: You cannot delete others messages in a DM.create_private_threads: There are no threads in a DM.create_public_threads: There are no threads in a DM.manage_threads: There are no threads in a DM.send_messages_in_threads: There are no threads in a DM.
This also checks the kick_members permission if the user is the owner.
Changed in version 2.0:
objparameter is now positional-only.Changed in version 2.0: Thread related permissions are now set to
False, and managed channel permissions are taken into account.- Parameters
obj (
Snowflake) – The user to check permissions for.- Returns
The resolved permissions for the user.
- Return type
- await add_recipients(*recipients, nicks=None)¶
This function is a coroutine.
Adds recipients to this group.
A group can only have a maximum of 10 members. Attempting to add more ends up in an exception. To add a recipient to the group, you must have a relationship with the user of type
RelationshipType.friend.- Parameters
*recipients (
Snowflake) – An argument list of users to add to this group. If the user is of typeObject, then thenickattribute is used as the nickname for the added recipient.nicks (Optional[Dict[
Snowflake,str]]) –A mapping of user IDs to nicknames to use for the added recipients.
New in version 2.0.
- Raises
Forbidden – You do not have permissions to add a recipient to this group.
HTTPException – Adding a recipient to this group failed.
- await remove_recipients(*recipients)¶
This function is a coroutine.
Removes recipients from this group.
- Parameters
*recipients (
Snowflake) – An argument list of users to remove from this group.- Raises
Forbidden – You do not have permissions to remove a recipient from this group.
HTTPException – Removing a recipient from this group failed.
- await edit(*, name=..., icon=..., owner=...)¶
This function is a coroutine.
Edits the group.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
- Parameters
name (Optional[
str]) – The new name to change the group to. Could beNoneto remove the name.icon (Optional[
bytes]) – A bytes-like object representing the new icon. Could beNoneto remove the icon.owner (
Snowflake) –The new owner of the group.
New in version 2.0.
- Raises
HTTPException – Editing the group failed.
- await leave(*, silent=False)¶
This function is a coroutine.
Leave the group.
If you are the only one in the group, this deletes it as well.
There is an alias for this called
close().- Parameters
silent (
bool) – Whether to leave the group without sending a leave message.- Raises
HTTPException – Leaving the group failed.
- await close(*, silent=False)¶
This function is a coroutine.
Leave the group.
If you are the only one in the group, this deletes it as well.
This is an alias of
leave().- Parameters
silent (
bool) – Whether to leave the group without sending a leave message.- Raises
HTTPException – Leaving the group failed.
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
New in version 2.0.
- Raises
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns
The list of invites that are currently active.
- Return type
List[
Invite]
- await create_invite(*, max_age=86400)¶
This function is a coroutine.
Creates an instant invite from a group channel.
New in version 2.0.
- Parameters
max_age (
int) – How long the invite should last in seconds. Defaults to 86400. Does not support 0.- Raises
HTTPException – Invite creation failed.
- Returns
The invite that was created.
- Return type
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, ring=True)¶
This function is a coroutine.
Connects to voice and creates a
VoiceClientto establish your connection to the voice server.- Parameters
timeout (
float) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (Type[
VoiceProtocol]) – A type that subclassesVoiceProtocolto connect with. Defaults toVoiceClient.ring (
bool) – Whether to ring the other member(s) to join the call, if starting a new call. Defaults toTrue.
- Raises
asyncio.TimeoutError – Could not connect to the voice channel in time.
ClientException – You are already connected to a voice channel.
OpusNotLoaded – The opus library has not been loaded.
- Returns
A voice client that is fully connected to the voice server.
- Return type
- await ack()¶
This function is a coroutine.
Marks every message in this channel as read.
- Raises
HTTPException – Acking the channel failed.
- await ack_pins()¶
This function is a coroutine.
Marks a channel’s pins as viewed.
- Raises
HTTPException – Acking the pinned messages failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters
id (
int) – The message ID to look for.- 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.
- Returns
The message asked for.
- Return type
- await greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...)¶
This function is a coroutine.
Sends a sticker greeting to the destination.
A sticker greeting is used to begin a new DM or reply to a system message.
New in version 2.0.
- Parameters
sticker (Union[
GuildSticker,StickerItem]) – The sticker to greet with.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead. In the case of greeting, onlyreplied_useris considered.reference (Union[
Message,MessageReference,PartialMessage]) – A reference to theMessageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.mention_author (
bool) – If set, overrides thereplied_userattribute ofallowed_mentions.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
TypeError – The
referenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The sticker greeting that was sent.
- Return type
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an asynchronous iterator that enables receiving the destination’s message history.
You must have
read_message_historyto do this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in channel.history(limit=123)] # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. 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 messages after this date or message. 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.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields
Message– The message with the message data parsed.
- await pins()¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises
Forbidden – You do not have the permission to retrieve pinned messages.
HTTPException – Retrieving the pinned messages failed.
- Returns
The messages that are currently pinned.
- Return type
List[
Message]
- await send(content=None, *, tts=False, file=None, files=None, stickers=None, delete_after=None, nonce=..., allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, silent=False)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then a sticker or file must be sent.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (
int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. Generates one by default.delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.New in version 1.6.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
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.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate size.TypeError – You specified both
fileandfiles, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The message that was sent.
- Return type
PartialMessageable¶
- asyncack
- asyncack_pins
- asyncfetch_message
- defget_partial_message
- asyncgreet
- async forhistory
- defpermissions_for
- asyncpins
- asyncsend
- defslash_commands
- deftyping
- defuser_commands
- class discord.PartialMessageable¶
Represents a partial messageable to aid with working messageable channels when only a channel ID is present.
The only way to construct this class is through
Client.get_partial_messageable().Note that this class is trimmed down and has no rich attributes.
New in version 2.0.
- x == y
Checks if two partial messageables are equal.
- x != y
Checks if two partial messageables are not equal.
- hash(x)
Returns the partial messageable’s hash.
- type¶
The channel type associated with this partial messageable, if given.
- Type
Optional[
ChannelType]
- await ack()¶
This function is a coroutine.
Marks every message in this channel as read.
- Raises
HTTPException – Acking the channel failed.
- await ack_pins()¶
This function is a coroutine.
Marks a channel’s pins as viewed.
- Raises
HTTPException – Acking the pinned messages failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters
id (
int) – The message ID to look for.- 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.
- Returns
The message asked for.
- Return type
- await greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...)¶
This function is a coroutine.
Sends a sticker greeting to the destination.
A sticker greeting is used to begin a new DM or reply to a system message.
New in version 2.0.
- Parameters
sticker (Union[
GuildSticker,StickerItem]) – The sticker to greet with.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead. In the case of greeting, onlyreplied_useris considered.reference (Union[
Message,MessageReference,PartialMessage]) – A reference to theMessageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.mention_author (
bool) – If set, overrides thereplied_userattribute ofallowed_mentions.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
TypeError – The
referenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The sticker greeting that was sent.
- Return type
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an asynchronous iterator that enables receiving the destination’s message history.
You must have
read_message_historyto do this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in channel.history(limit=123)] # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. 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 messages after this date or message. 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.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields
Message– The message with the message data parsed.
- await pins()¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises
Forbidden – You do not have the permission to retrieve pinned messages.
HTTPException – Retrieving the pinned messages failed.
- Returns
The messages that are currently pinned.
- Return type
List[
Message]
- await send(content=None, *, tts=False, file=None, files=None, stickers=None, delete_after=None, nonce=..., allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, silent=False)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then a sticker or file must be sent.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (
int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. Generates one by default.delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.New in version 1.6.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
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.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate size.TypeError – You specified both
fileandfiles, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The message that was sent.
- Return type
- slash_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the slash commands available in the channel.
Examples
Usage
async for command in channel.slash_commands(): print(command.name)
Flattening into a list
commands = [command async for command in channel.slash_commands()] # commands is now a list of SlashCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
SlashCommand– A slash command.
- typing()¶
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using
await.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!')
Example Usage:
await channel.typing() # Do some computational magic for about 10 seconds await channel.send('Done!')
Changed in version 2.0: This no longer works with the
withsyntax,async withmust be used instead.Changed in version 2.0: Added functionality to
awaitthe context manager to send a typing indicator for 10 seconds.
- user_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the user commands available to use on the user.
Examples
Usage
async for command in user.user_commands(): print(command.name)
Flattening into a list
commands = [command async for command in user.user_commands()] # commands is now a list of UserCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
UserCommand– A user command.
- property created_at¶
Returns the channel’s creation time in UTC.
- Type
- permissions_for(obj=None, /)¶
Handles permission resolution for a
User.This function is there for compatibility with other channel types.
Since partial messageables cannot reasonably have the concept of permissions, this will always return
Permissions.none().- Parameters
obj (
User) – The user to check permissions for. This parameter is ignored but kept for compatibility with otherpermissions_formethods.- Returns
The resolved permissions.
- Return type
- get_partial_message(message_id, /)¶
Creates a
PartialMessagefrom the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
- Parameters
message_id (
int) – The message ID to create a partial message for.- Returns
The partial message.
- Return type
Thread¶
- applied_tags
- archive_timestamp
- archived
- auto_archive_duration
- category
- category_id
- channel
- created_at
- flags
- guild
- id
- invitable
- jump_url
- last_message
- last_message_id
- last_pin_timestamp
- locked
- me
- member_count
- members
- mention
- message_count
- name
- owner
- owner_id
- parent
- parent_id
- slowmode_delay
- starter_message
- type
- asyncack
- asyncack_pins
- asyncadd_tags
- asyncadd_user
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_members
- asyncfetch_message
- defget_partial_message
- asyncgreet
- async forhistory
- defis_news
- defis_nsfw
- defis_private
- asyncjoin
- asyncleave
- defpermissions_for
- asyncpins
- asyncpurge
- asyncremove_tags
- asyncremove_user
- asyncsend
- defslash_commands
- deftyping
- defuser_commands
- class discord.Thread¶
Represents a Discord thread.
- x == y
Checks if two threads are equal.
- x != y
Checks if two threads are not equal.
- hash(x)
Returns the thread’s hash.
- str(x)
Returns the thread’s name.
New in version 2.0.
- parent_id¶
The ID of the parent
TextChannelorForumChannelthis thread belongs to.- Type
- last_message_id¶
The last message ID of the message sent to this thread. It may not point to an existing or valid message.
- Type
Optional[
int]
- last_pin_timestamp¶
When the last pinned message was pinned.
Noneif there are no pinned messages.- Type
Optional[
datetime.datetime]
- slowmode_delay¶
The number of seconds a member must wait between sending messages in this thread. A value of
0denotes that it is disabled. Bots and users withmanage_channelsormanage_messagesbypass slowmode.- Type
- invitable¶
Whether non-moderators can add other non-moderators to this thread. This is always
Truefor public threads.- Type
- auto_archive_duration¶
The duration in minutes until the thread is automatically archived due to inactivity. Usually a value of 60, 1440, 4320 and 10080.
- Type
- archive_timestamp¶
An aware timestamp of when the thread’s archived status was last updated in UTC.
- Type
- async with typing()¶
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using
await.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(20) await channel.send('Done!')
Example Usage:
await channel.typing() # Do some computational magic for about 10 seconds await channel.send('Done!')
Changed in version 2.0: This no longer works with the
withsyntax,async withmust be used instead.Changed in version 2.0: Added functionality to
awaitthe context manager to send a typing indicator for 10 seconds.
- async for ... in slash_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the slash commands available in the channel.
Examples
Usage
async for command in channel.slash_commands(): print(command.name)
Flattening into a list
commands = [command async for command in channel.slash_commands()] # commands is now a list of SlashCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
SlashCommand– A slash command.
- async for ... in user_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the user commands available to use on the user.
Examples
Usage
async for command in user.user_commands(): print(command.name)
Flattening into a list
commands = [command async for command in user.user_commands()] # commands is now a list of UserCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
UserCommand– A user command.
- property type¶
The channel’s Discord type.
- Type
- property parent¶
The parent channel this thread belongs to.
There is an alias for this named
channel.- Type
Optional[Union[
ForumChannel,TextChannel]]
- property channel¶
The parent channel this thread belongs to.
This is an alias of
parent.- Type
Optional[Union[
ForumChannel,TextChannel]]
- property flags¶
The flags associated with this thread.
- Type
- property created_at¶
Returns the thread’s creation time in UTC.
Note
This may be inaccurate for threads created before January 9th, 2022.
- Type
- property members¶
A list of thread members in this thread.
Initial members are not provided by Discord. You must call
fetch_members().- Type
List[
ThreadMember]
- property starter_message¶
Returns the thread starter message from the cache.
The message might not be cached, valid, or point to an existing message.
Note that the thread starter message ID is the same ID as the thread.
- Returns
The thread starter message or
Noneif not found.- Return type
Optional[
Message]
- property last_message¶
Returns the last message from this thread from the cache.
The message might not be valid or point to an existing message.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either
history()orfetch_message()with thelast_message_idattribute.- Returns
The last message in this channel or
Noneif not found.- Return type
Optional[
Message]
- property category¶
The category channel the parent channel belongs to, if applicable.
- Raises
ClientException – The parent channel was not cached and returned
None.- Returns
The parent channel’s category.
- Return type
Optional[
CategoryChannel]
- property category_id¶
The category channel ID the parent channel belongs to, if applicable.
- Raises
ClientException – The parent channel was not cached and returned
None.- Returns
The parent channel’s category ID.
- Return type
Optional[
int]
- property me¶
A thread member representing yourself, if you’ve joined the thread.
This might not be available.
- Type
Optional[
ThreadMember]
- is_private()¶
bool: Whether the thread is a private thread.A private thread is only viewable by those that have been explicitly invited or have
manage_threads.
- is_news()¶
bool: Whether the thread is a news thread.A news thread is a thread that has a parent that is a news channel, i.e.
TextChannel.is_news()isTrue.
- is_nsfw()¶
bool: Whether the thread is NSFW or not.An NSFW thread is a thread that has a parent that is an NSFW channel, i.e.
TextChannel.is_nsfw()isTrue.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.Since threads do not have their own permissions, they mostly inherit them from the parent channel with some implicit permissions changed.
- Parameters
obj (Union[
Member,Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.- Raises
ClientException – The parent channel was not cached and returned
None- Returns
The resolved permissions for the member or role.
- Return type
- await delete_messages(messages, /, *, reason=None)¶
This function is a coroutine.
Deletes a list of messages. This is similar to
Message.delete()except it bulk deletes multiple messages.You must have
manage_messagesto use this (unless they’re your own).Note
Users do not have access to the message bulk-delete endpoint. Since messages are just iterated over and deleted one-by-one, it’s easy to get ratelimited using this method.
- Parameters
messages (Iterable[
abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.reason (Optional[
str]) – The reason for deleting the messages. Shows up on the audit log.
- Raises
Forbidden – You do not have proper permissions to delete the messages.
HTTPException – Deleting the messages failed.
- await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, reason=None)¶
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check. If acheckis not provided then all messages are deleted without discrimination.Having
read_message_historyis needed to retrieve message history.Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await channel.purge(limit=100, check=is_me) await channel.send(f'Deleted {len(deleted)} message(s)')
- Parameters
limit (Optional[
int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message],bool]) – The function used to check if a message should be deleted. It must take aMessageas its sole parameter.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asbeforeinhistory().after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asafterinhistory().around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asaroundinhistory().oldest_first (Optional[
bool]) – Same asoldest_firstinhistory().reason (Optional[
str]) – The reason for purging the messages. Shows up on the audit log.
- Raises
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
- Returns
The list of messages that were deleted.
- Return type
List[
Message]
- await edit(*, name=..., archived=..., locked=..., invitable=..., pinned=..., slowmode_delay=..., auto_archive_duration=..., applied_tags=..., reason=None)¶
This function is a coroutine.
Edits the thread.
Editing the thread requires
Permissions.manage_threads. The thread creator can also editname,archivedorauto_archive_duration. Note that if the thread is locked then only those withPermissions.manage_threadscan unarchive a thread.The thread must be unarchived to be edited.
- Parameters
name (
str) – The new name of the thread.archived (
bool) – Whether to archive the thread or not.locked (
bool) – Whether to lock the thread or not.pinned (
bool) – Whether to pin the thread or not. This only works if the thread is part of a forum.invitable (
bool) – Whether non-moderators can add other non-moderators to this thread. Only available for private threads.auto_archive_duration (
int) – The new duration in minutes before a thread is automatically archived for inactivity. Must be one of60,1440,4320, or10080.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this thread, in seconds. A value of0disables slowmode. The maximum value possible is21600.applied_tags (Sequence[
ForumTag]) – The new tags to apply to the thread. There can only be up to 5 tags applied to a thread.reason (Optional[
str]) – The reason for editing this thread. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to edit the thread.
HTTPException – Editing the thread failed.
- Returns
The newly edited thread.
- Return type
- await add_tags(*tags, reason=None)¶
This function is a coroutine.
Adds the given forum tags to a thread.
You must have
manage_threadsto use this or the thread must be owned by you.Tags that have
ForumTag.moderatedset toTruerequiremanage_threadsto be added.The maximum number of tags that can be added to a thread is 5.
The parent channel must be a
ForumChannel.- Parameters
*tags (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aForumTagto add to the thread.reason (Optional[
str]) – The reason for adding these tags.
- Raises
Forbidden – You do not have permissions to add these tags.
HTTPException – Adding tags failed.
- await remove_tags(*tags, reason=None)¶
This function is a coroutine.
Remove the given forum tags to a thread.
You must have
manage_threadsto use this or the thread must be owned by you.The parent channel must be a
ForumChannel.- Parameters
*tags (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aForumTagto remove to the thread.reason (Optional[
str]) – The reason for removing these tags.
- Raises
Forbidden – You do not have permissions to remove these tags.
HTTPException – Removing tags failed.
- await join()¶
This function is a coroutine.
Joins this thread.
You must have
send_messages_in_threadsto join a thread. If the thread is private,manage_threadsis also needed.- Raises
Forbidden – You do not have permissions to join the thread.
HTTPException – Joining the thread failed.
- await leave()¶
This function is a coroutine.
Leaves this thread.
- Raises
HTTPException – Leaving the thread failed.
- await add_user(user, /)¶
This function is a coroutine.
Adds a user to this thread.
You must have
send_messages_in_threadsto add a user to a thread. If the thread is private andinvitableisFalsethenmanage_messagesis required to add a user to the thread.- Parameters
user (
abc.Snowflake) – The user to add to the thread.- Raises
Forbidden – You do not have permissions to add the user to the thread.
HTTPException – Adding the user to the thread failed.
- await remove_user(user, /)¶
This function is a coroutine.
Removes a user from this thread.
You must have
manage_threadsor be the creator of the thread to remove a user.- Parameters
user (
abc.Snowflake) – The user to remove from the thread.- Raises
Forbidden – You do not have permissions to remove the user from the thread.
HTTPException – Removing the user from the thread failed.
- await fetch_members()¶
This function is a coroutine.
Retrieves all
ThreadMemberthat are in this thread, along with their respectiveMember.- Raises
InvalidData – Discord didn’t respond with the members.
- Returns
All thread members in the thread.
- Return type
List[
ThreadMember]
- await delete()¶
This function is a coroutine.
Deletes this thread.
You must have
manage_threadsto delete threads.- Raises
Forbidden – You do not have permissions to delete this thread.
HTTPException – Deleting the thread failed.
- get_partial_message(message_id, /)¶
Creates a
PartialMessagefrom the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
- Parameters
message_id (
int) – The message ID to create a partial message for.- Returns
The partial message.
- Return type
- await ack()¶
This function is a coroutine.
Marks every message in this channel as read.
- Raises
HTTPException – Acking the channel failed.
- await ack_pins()¶
This function is a coroutine.
Marks a channel’s pins as viewed.
- Raises
HTTPException – Acking the pinned messages failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters
id (
int) – The message ID to look for.- 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.
- Returns
The message asked for.
- Return type
- await greet(sticker, *, allowed_mentions=..., reference=..., mention_author=...)¶
This function is a coroutine.
Sends a sticker greeting to the destination.
A sticker greeting is used to begin a new DM or reply to a system message.
New in version 2.0.
- Parameters
sticker (Union[
GuildSticker,StickerItem]) – The sticker to greet with.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead. In the case of greeting, onlyreplied_useris considered.reference (Union[
Message,MessageReference,PartialMessage]) – A reference to theMessageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.mention_author (
bool) – If set, overrides thereplied_userattribute ofallowed_mentions.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
TypeError – The
referenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The sticker greeting that was sent.
- Return type
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an asynchronous iterator that enables receiving the destination’s message history.
You must have
read_message_historyto do this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = [message async for message in channel.history(limit=123)] # messages is now a list of Message...
All parameters are optional.
- Parameters
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. 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 messages after this date or message. 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.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. 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. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields
Message– The message with the message data parsed.
- await pins()¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises
Forbidden – You do not have the permission to retrieve pinned messages.
HTTPException – Retrieving the pinned messages failed.
- Returns
The messages that are currently pinned.
- Return type
List[
Message]
- await send(content=None, *, tts=False, file=None, files=None, stickers=None, delete_after=None, nonce=..., allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, silent=False)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then a sticker or file must be sent.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (
int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. Generates one by default.delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messageto which you are replying, this can be created usingto_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.New in version 1.6.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
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.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate size.TypeError – You specified both
fileandfiles, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- Returns
The message that was sent.
- Return type
- class discord.ThreadMember¶
Represents a Discord thread member.
- x == y
Checks if two thread members are equal.
- x != y
Checks if two thread members are not equal.
- hash(x)
Returns the thread member’s hash.
- str(x)
Returns the thread member’s name.
New in version 2.0.
- joined_at¶
The time the member joined the thread in UTC. Only reliably available for yourself or members joined while the user is connected to the gateway.
- Type
Optional[
datetime.datetime]
- flags¶
The thread member’s flags. Will be its own class in the future. Only reliably available for yourself or members joined while the user is connected to the gateway.
- Type
- property member¶
The member this
ThreadMemberrepresents. If the member is not cached then this will beNone.- Type
Optional[
Member]
StageInstance¶
- class discord.StageInstance¶
Represents a stage instance of a stage channel in a guild.
New in version 2.0.
- x == y
Checks if two stage instances are equal.
- x != y
Checks if two stage instances are not equal.
- hash(x)
Returns the stage instance’s hash.
- privacy_level¶
The privacy level of the stage instance.
- Type
- scheduled_event_id¶
The ID of scheduled event that belongs to the stage instance if any.
New in version 2.0.
- Type
Optional[
int]
- property discoverable¶
Whether the stage instance is discoverable.
- channel¶
The channel that stage instance is running in.
- Type
Optional[
StageChannel]
- scheduled_event¶
The scheduled event that belongs to the stage instance.
- Type
Optional[
ScheduledEvent]
- await edit(*, topic=..., privacy_level=..., reason=None)¶
This function is a coroutine.
Edits the stage instance.
You must have
manage_channelsto do this.- Parameters
topic (
str) – The stage instance’s new topic.privacy_level (
PrivacyLevel) – The stage instance’s new privacy level.reason (
str) – The reason the stage instance was edited. Shows up on the audit log.
- Raises
TypeError – If the
privacy_levelparameter is not the proper type.Forbidden – You do not have permissions to edit the stage instance.
HTTPException – Editing a stage instance failed.
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the stage instance.
You must have
manage_channelsto do this.- Parameters
reason (
str) – The reason the stage instance was deleted. Shows up on the audit log.- Raises
Forbidden – You do not have permissions to delete the stage instance.
HTTPException – Deleting the stage instance failed.
Call¶
- asyncchange_region
- asyncfetch_message
- defvoice_state_for
- class discord.PrivateCall¶
Represents the actual group call from Discord.
This is accompanied with a
CallMessagedenoting the information.New in version 1.9.
Denotes if this call is unavailable.
- Type
- region¶
The region the call is being hosted at.
Changed in version 2.0: The type of this attribute has changed to
str.- Type
- property ringing¶
A list of users that are currently being rung to join the call.
- Type
List[
abc.User]
- property initiator¶
Returns the user that started the call. Returns
Noneif the message is not cached.- Type
Optional[
abc.User]
- property connected¶
Returns whether you’re in the call (this does not mean you’re in the call through the library).
- Type
- property voice_states¶
Returns a mapping of user IDs who have voice states in this call.
- Type
Mapping[
int,VoiceState]
- await fetch_message()¶
This function is a coroutine.
Fetches and caches the message associated with this call.
- Raises
HTTPException – Retrieving the message failed.
- Returns
The message associated with this call.
- Return type
- await change_region(region)¶
This function is a coroutine.
Changes the channel’s voice region.
- Parameters
region (
str) –A region to change the voice region to.
Changed in version 2.0: The type of this parameter has changed to
str.- Raises
HTTPException – Failed to change the channel’s voice region.
- voice_state_for(user)¶
Retrieves the
VoiceStatefor a specifiedUser.If the
Userhas no voice state then this function returnsNone.- Parameters
user (
User) – The user to retrieve the voice state for.- Returns
The voice state associated with this user.
- Return type
Optional[
VoiceState]
- asyncchange_region
- asyncfetch_message
- defvoice_state_for
- class discord.GroupCall¶
Represents a Discord group call.
This is accompanied with a
CallMessagedenoting the information.- channel¶
The channel the group call is in.
- Type
Denotes if this group call is unavailable.
- Type
- region¶
The region the group call is being hosted in.
Changed in version 2.0: The type of this attribute has changed to
str.- Type
- await change_region(region)¶
This function is a coroutine.
Changes the channel’s voice region.
- Parameters
region (
str) –A region to change the voice region to.
Changed in version 2.0: The type of this parameter has changed to
str.- Raises
HTTPException – Failed to change the channel’s voice region.
- property connected¶
Returns whether you’re in the call (this does not mean you’re in the call through the library).
- Type
- await fetch_message()¶
This function is a coroutine.
Fetches and caches the message associated with this call.
- Raises
HTTPException – Retrieving the message failed.
- Returns
The message associated with this call.
- Return type
- property initiator¶
Returns the user that started the call. Returns
Noneif the message is not cached.- Type
Optional[
abc.User]
- property ringing¶
A list of users that are currently being rung to join the call.
- Type
List[
abc.User]
- voice_state_for(user)¶
Retrieves the
VoiceStatefor a specifiedUser.If the
Userhas no voice state then this function returnsNone.- Parameters
user (
User) – The user to retrieve the voice state for.- Returns
The voice state associated with this user.
- Return type
Optional[
VoiceState]
- property voice_states¶
Returns a mapping of user IDs who have voice states in this call.
- Type
Mapping[
int,VoiceState]
- class discord.CallMessage¶
Represents a group call message from Discord.
This is only received in cases where the message type is equivalent to
MessageType.call.- ended_timestamp¶
An aware UTC datetime object that represents the time that the call has ended.
- Type
Optional[
datetime.datetime]
- property channel¶
The private channel associated with this message.
- Type
- property duration¶
Queries the duration of the call.
If the call has not ended then the current duration will be returned.
- Returns
The timedelta object representing the duration.
- Return type
Message¶
- activity
- application
- application_id
- attachments
- author
- call
- channel
- channel_mentions
- clean_content
- components
- content
- created_at
- edited_at
- embeds
- flags
- guild
- id
- interaction
- jump_url
- mention_everyone
- mentions
- nonce
- pinned
- position
- raw_channel_mentions
- raw_mentions
- raw_role_mentions
- reactions
- reference
- role_mentions
- role_subscription
- stickers
- system_content
- tts
- type
- webhook_id
- asyncack
- asyncadd_files
- asyncadd_reaction
- asyncclear_reaction
- asyncclear_reactions
- asynccreate_thread
- asyncdelete
- asyncedit
- asyncfetch
- asyncgreet
- defis_system
- defmessage_commands
- asyncpin
- asyncpublish
- asyncremove_attachments
- asyncremove_reaction
- asyncreply
- defto_reference
- asyncunpin
- class discord.Message¶
Represents a message from Discord.
- x == y
Checks if two messages are equal.
- x != y
Checks if two messages are not equal.
- hash(x)
Returns the message’s hash.
- tts¶
Specifies if the message was done with text-to-speech. This can only be accurately received in
on_message()due to a discord limitation.- Type
- type¶
The type of message. In most cases this should not be checked, but it is helpful in cases where it might be a system message for
system_content.- Type
- author¶
A
Memberthat sent the message. Ifchannelis a private channel or the user has the left the guild, then it is aUserinstead.
- nonce¶
The value used by Discord clients to verify that the message is successfully sent. This is not stored long term within Discord’s servers and is only used ephemerally.
- channel¶
The
TextChannelorThreadthat the message was sent from. Could be aDMChannelorGroupChannelif it’s a private message.- Type
Union[
TextChannel,StageChannel,VoiceChannel,Thread,DMChannel,GroupChannel]
- call¶
The call that the message refers to. This is only applicable to messages of type
MessageType.call.- Type
Optional[
CallMessage]
- reference¶
The message that this message references. This is only applicable to messages of type
MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.New in version 1.5.
- Type
Optional[
MessageReference]
- mention_everyone¶
Specifies if the message mentions everyone.
Note
This does not check if the
@everyoneor the@heretext is in the message itself. Rather this boolean indicates if either the@everyoneor the@heretext is in the message and it did end up mentioning.- Type
- mentions¶
A list of
Memberthat were mentioned. If the message is in a private message then the list will be ofUserinstead. For messages that are not of typeMessageType.default, this array can be used to aid in system messages. For more information, seesystem_content.Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
- Type
List[
abc.User]
- channel_mentions¶
A list of
abc.GuildChannelorThreadthat were mentioned. If the message is in a private message then the list is always empty.- Type
List[Union[
abc.GuildChannel,Thread]]
- role_mentions¶
A list of
Rolethat were mentioned. If the message is in a private message then the list is always empty.- Type
List[
Role]
- webhook_id¶
If this message was sent by a webhook, then this is the webhook ID’s that sent this message.
- Type
Optional[
int]
- attachments¶
A list of attachments given to a message.
- Type
List[
Attachment]
- flags¶
Extra features of the message.
New in version 1.3.
- Type
- reactions¶
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
- Type
List[
Reaction]
- activity¶
The activity associated with this message. Sent with Rich-Presence related messages that for example, request joining, spectating, or listening to or with another member.
It is a dictionary with the following optional keys:
type: An integer denoting the type of message activity being requested.party_id: The party ID associated with the party.
- Type
Optional[
dict]
- application¶
The rich presence enabled application associated with this message.
Changed in version 2.0: Type is now
IntegrationApplicationinstead ofdict.- Type
Optional[
IntegrationApplication]
- stickers¶
A list of sticker items given to the message.
New in version 1.6.
- Type
List[
StickerItem]
- components¶
A list of components in the message.
New in version 2.0.
- Type
List[Union[
ActionRow,Button,SelectMenu]]
- role_subscription¶
The data of the role subscription purchase or renewal that prompted this
MessageType.role_subscription_purchasemessage.New in version 2.0.
- Type
Optional[
RoleSubscriptionInfo]
- application_id¶
The application ID of the application that created this message if this message was sent by an application-owned webhook or an interaction.
New in version 2.0.
- Type
Optional[
int]
- position¶
A generally increasing integer with potentially gaps or duplicates that represents the approximate position of the message in a thread.
New in version 2.0.
- Type
Optional[
int]
- interaction¶
The interaction that this message is a response to.
New in version 2.0.
- Type
Optional[
Interaction]
- async for ... in message_commands(query=None, *, limit=None, command_ids=None, application=None, with_applications=True)¶
Returns a asynchronous iterator of the message commands available to use on the message.
Examples
Usage
async for command in message.message_commands(): print(command.name)
Flattening into a list
commands = [command async for command in message.message_commands()] # commands is now a list of MessageCommand...
All parameters are optional.
- Parameters
query (Optional[
str]) –The query to search for. Specifying this limits results to 25 commands max.
This parameter is faked if
applicationis specified.limit (Optional[
int]) –The maximum number of commands to send back. Defaults to 0 if
command_idsis passed, else 25. IfNone, returns all commands.This parameter is faked if
applicationis specified.command_ids (Optional[List[
int]]) –List of up to 100 command IDs to search for. If the command doesn’t exist, it won’t be returned.
If
limitis passed alongside this parameter, this parameter will serve as a “preferred commands” list. This means that the endpoint will return the found commands + up tolimitmore, if available.application (Optional[
Snowflake]) – Whether to return this application’s commands. Always set to DM recipient in a private channel context.with_applications (
bool) – Whether to include applications in the response. Defaults toTrue.
- Raises
TypeError – Both query and command_ids are passed. Attempted to fetch commands in a DM with a non-bot user.
ValueError – The limit was not greater than or equal to 0.
HTTPException – Getting the commands failed.
Forbidden – You do not have permissions to get the commands.
HTTPException – The request to get the commands failed.
- Yields
MessageCommand– A message command.
- raw_mentions¶
A property that returns an array of user IDs matched with the syntax of
<@user_id>in the message content.This allows you to receive the user IDs of mentioned users even in a private message context.
- Type
List[
int]
- await ack()¶
This function is a coroutine.
Marks this message as read.
- Raises
HTTPException – Acking failed.
- await add_reaction(emoji, /)¶
This function is a coroutine.
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild
Emoji.You must have
read_message_historyto do this. If nobody else has reacted to the message using this emoji,add_reactionsis required.Changed in version 2.0:
emojiparameter is now positional-only.Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
emoji (Union[
Emoji,Reaction,PartialEmoji,str]) – The emoji to react with.- Raises
HTTPException – Adding the reaction failed.
Forbidden – You do not have the proper permissions to react to the message.
NotFound – The emoji you specified was not found.
TypeError – The emoji parameter is invalid.
- await clear_reaction(emoji)¶
This function is a coroutine.
Clears a specific reaction from the message.
The emoji may be a unicode emoji or a custom guild
Emoji.You must have
manage_messagesto do this.New in version 1.3.
Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
emoji (Union[
Emoji,Reaction,PartialEmoji,str]) – The emoji to clear.- Raises
HTTPException – Clearing the reaction failed.
Forbidden – You do not have the proper permissions to clear the reaction.
NotFound – The emoji you specified was not found.
TypeError – The emoji parameter is invalid.
- await clear_reactions()¶
This function is a coroutine.
Removes all the reactions from the message.
You must have
manage_messagesto do this.- Raises
HTTPException – Removing the reactions failed.
Forbidden – You do not have the proper permissions to remove all the reactions.
- await create_thread(*, name, auto_archive_duration=..., slowmode_delay=None, reason=None)¶
This function is a coroutine.
Creates a public thread from this message.
You must have
create_public_threadsin order to create a public thread from a message.The channel this message belongs in must be a
TextChannel.New in version 2.0.
- Parameters
name (
str) – The name of the thread.auto_archive_duration (
int) –The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used.
Must be one of
60,1440,4320, or10080, if provided.slowmode_delay (Optional[
int]) – Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is21600. By default no slowmode rate limit if this isNone.reason (Optional[
str]) – The reason for creating a new thread. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to create a thread.
HTTPException – Creating the thread failed.
ValueError – This message does not have guild info attached.
- Returns
The created thread.
- Return type
- await delete(*, delay=None)¶
This function is a coroutine.
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you must have
manage_messages.Changed in version 1.1: Added the new
delaykeyword-only parameter.- Parameters
delay (Optional[
float]) – If provided, the number of seconds to wait in the background before deleting the message. If the deletion fails then it is silently ignored.- Raises
Forbidden – You do not have proper permissions to delete the message.
NotFound – The message was deleted already
HTTPException – Deleting the message failed.
- await fetch()¶
This function is a coroutine.
Fetches the partial message to a full
Message.- Raises
NotFound – The message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- Returns
The full message.
- Return type
- await greet(sticker, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.greet()to reply to theMessagewith a sticker greeting.New in version 2.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
- Returns
The sticker greeting that was sent.
- Return type
- await pin(*, reason=None)¶
This function is a coroutine.
Pins the message.
You must have
manage_messagesto do this in a non-private channel context.- Parameters
reason (Optional[
str]) –The reason for pinning the message. Shows up on the audit log.
New in version 1.4.
- Raises
Forbidden – You do not have permissions to pin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Pinning the message failed, probably due to the channel having more than 50 pinned messages.
- await publish()¶
This function is a coroutine.
Publishes this message to the channel’s followers.
The message must have been sent in a news channel. You must have
send_messagesto do this.If the message is not your own then
manage_messagesis also needed.- Raises
Forbidden – You do not have the proper permissions to publish this message or the channel is not a news channel.
HTTPException – Publishing the message failed.
- raw_channel_mentions¶
A property that returns an array of channel IDs matched with the syntax of
<#channel_id>in the message content.- Type
List[
int]
- await remove_reaction(emoji, member)¶
This function is a coroutine.
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild
Emoji.If the reaction is not your own (i.e.
memberparameter is not you) thenmanage_messagesis needed.The
memberparameter must represent a member and meet theabc.Snowflakeabc.Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
emoji (Union[
Emoji,Reaction,PartialEmoji,str]) – The emoji to remove.member (
abc.Snowflake) – The member for which to remove the reaction.
- Raises
HTTPException – Removing the reaction failed.
Forbidden – You do not have the proper permissions to remove the reaction.
NotFound – The member or emoji you specified was not found.
TypeError – The emoji parameter is invalid.
- await reply(content=None, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.send()to reply to theMessage.New in version 1.6.
Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate sizeTypeError – You specified both
fileandfiles.
- Returns
The message that was sent.
- Return type
- to_reference(*, fail_if_not_exists=True)¶
Creates a
MessageReferencefrom the current message.New in version 1.6.
- Parameters
fail_if_not_exists (
bool) –Whether replying using the message reference should raise
HTTPExceptionif the message no longer exists or Discord could not fetch the message.New in version 1.7.
- Returns
The reference to this message.
- Return type
- await unpin(*, reason=None)¶
This function is a coroutine.
Unpins the message.
You must have
manage_messagesto do this in a non-private channel context.- Parameters
reason (Optional[
str]) –The reason for unpinning the message. Shows up on the audit log.
New in version 1.4.
- Raises
Forbidden – You do not have permissions to unpin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Unpinning the message failed.
- raw_role_mentions¶
A property that returns an array of role IDs matched with the syntax of
<@&role_id>in the message content.- Type
List[
int]
- clean_content¶
A property that returns the content in a “cleaned up” manner. This basically means that mentions are transformed into the way the client shows it. e.g.
<#id>will transform into#name.This will also transform @everyone and @here mentions into non-mentions.
Note
This does not affect markdown. If you want to escape or remove markdown then use
utils.escape_markdown()orutils.remove_markdown()respectively, along with this function.- Type
- property created_at¶
The message’s creation time in UTC.
- Type
- property edited_at¶
An aware UTC datetime object containing the edited time of the message.
- Type
Optional[
datetime.datetime]
- is_system()¶
bool: Whether the message is a system message.A system message is a message that is constructed entirely by the Discord API in response to something.
New in version 1.3.
- system_content¶
A property that returns the content that is rendered regardless of the
Message.type.In the case of
MessageType.defaultandMessageType.reply, this just returns the regularMessage.content. Otherwise this returns an English message denoting the contents of the system message.- Type
- await edit(content=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=...)¶
This function is a coroutine.
Edits the message.
The content must be able to be transformed into a string via
str(content).Changed in version 1.3: The
suppresskeyword-only parameter was added.Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The new content to replace the message with. Could beNoneto remove the content.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.Note
New files will always appear after current attachments.
New in version 2.0.
suppress (
bool) – Whether to suppress embeds for the message. This removes all the embeds if set toTrue. If set toFalsethis brings the embeds back if they were suppressed. Using this parameter requiresmanage_messages.delete_after (Optional[
float]) – If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.allowed_mentions (Optional[
AllowedMentions]) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
- Raises
HTTPException – Editing the message failed.
Forbidden – Tried to suppress a message without permissions or edit a message that isn’t yours.
- Returns
The newly edited message.
- Return type
- await add_files(*files)¶
This function is a coroutine.
Adds new files to the end of the message attachments.
New in version 2.0.
- Parameters
*files (
File) – New files to add to the message.- Raises
HTTPException – Editing the message failed.
Forbidden – Tried to edit a message that isn’t yours.
- Returns
The newly edited message.
- Return type
- await remove_attachments(*attachments)¶
This function is a coroutine.
Removes attachments from the message.
New in version 2.0.
- Parameters
*attachments (
Attachment) – Attachments to remove from the message.- Raises
HTTPException – Editing the message failed.
Forbidden – Tried to edit a message that isn’t yours.
- Returns
The newly edited message.
- Return type
- asyncack
- asyncadd_reaction
- asyncclear_reaction
- asyncclear_reactions
- asynccreate_thread
- asyncdelete
- asyncedit
- asyncfetch
- asyncgreet
- asyncpin
- asyncpublish
- asyncremove_reaction
- asyncreply
- defto_reference
- asyncunpin
- class discord.PartialMessage¶
Represents a partial message to aid with working messages when only a message and channel ID are present.
There are two ways to construct this class. The first one is through the constructor itself, and the second is via the following:
Note that this class is trimmed down and has no rich attributes.
New in version 1.6.
- x == y
Checks if two partial messages are equal.
- x != y
Checks if two partial messages are not equal.
- hash(x)
Returns the partial message’s hash.
- channel¶
The channel associated with this partial message.
- Type
Union[
PartialMessageable,TextChannel,StageChannel,VoiceChannel,Thread,DMChannel]
- property created_at¶
The partial message’s creation time in UTC.
- Type
- await fetch()¶
This function is a coroutine.
Fetches the partial message to a full
Message.- Raises
NotFound – The message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- Returns
The full message.
- Return type
- await delete(*, delay=None)¶
This function is a coroutine.
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you must have
manage_messages.Changed in version 1.1: Added the new
delaykeyword-only parameter.- Parameters
delay (Optional[
float]) – If provided, the number of seconds to wait in the background before deleting the message. If the deletion fails then it is silently ignored.- Raises
Forbidden – You do not have proper permissions to delete the message.
NotFound – The message was deleted already
HTTPException – Deleting the message failed.
- await edit(content=..., attachments=..., delete_after=None, allowed_mentions=...)¶
This function is a coroutine.
Edits the message.
The content must be able to be transformed into a string via
str(content).Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
content (Optional[
str]) – The new content to replace the message with. Could beNoneto remove the content.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.Note
New files will always appear after current attachments.
New in version 2.0.
delete_after (Optional[
float]) – If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.allowed_mentions (Optional[
AllowedMentions]) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.New in version 1.4.
- Raises
HTTPException – Editing the message failed.
Forbidden – Tried to suppress a message without permissions or edited a message’s content or embed that isn’t yours.
TypeError – You specified both
embedandembeds
- Returns
The newly edited message.
- Return type
- await publish()¶
This function is a coroutine.
Publishes this message to the channel’s followers.
The message must have been sent in a news channel. You must have
send_messagesto do this.If the message is not your own then
manage_messagesis also needed.- Raises
Forbidden – You do not have the proper permissions to publish this message or the channel is not a news channel.
HTTPException – Publishing the message failed.
- await pin(*, reason=None)¶
This function is a coroutine.
Pins the message.
You must have
manage_messagesto do this in a non-private channel context.- Parameters
reason (Optional[
str]) –The reason for pinning the message. Shows up on the audit log.
New in version 1.4.
- Raises
Forbidden – You do not have permissions to pin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Pinning the message failed, probably due to the channel having more than 50 pinned messages.
- await unpin(*, reason=None)¶
This function is a coroutine.
Unpins the message.
You must have
manage_messagesto do this in a non-private channel context.- Parameters
reason (Optional[
str]) –The reason for unpinning the message. Shows up on the audit log.
New in version 1.4.
- Raises
Forbidden – You do not have permissions to unpin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Unpinning the message failed.
- await add_reaction(emoji, /)¶
This function is a coroutine.
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild
Emoji.You must have
read_message_historyto do this. If nobody else has reacted to the message using this emoji,add_reactionsis required.Changed in version 2.0:
emojiparameter is now positional-only.Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
emoji (Union[
Emoji,Reaction,PartialEmoji,str]) – The emoji to react with.- Raises
HTTPException – Adding the reaction failed.
Forbidden – You do not have the proper permissions to react to the message.
NotFound – The emoji you specified was not found.
TypeError – The emoji parameter is invalid.
- await remove_reaction(emoji, member)¶
This function is a coroutine.
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild
Emoji.If the reaction is not your own (i.e.
memberparameter is not you) thenmanage_messagesis needed.The
memberparameter must represent a member and meet theabc.Snowflakeabc.Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
emoji (Union[
Emoji,Reaction,PartialEmoji,str]) – The emoji to remove.member (
abc.Snowflake) – The member for which to remove the reaction.
- Raises
HTTPException – Removing the reaction failed.
Forbidden – You do not have the proper permissions to remove the reaction.
NotFound – The member or emoji you specified was not found.
TypeError – The emoji parameter is invalid.
- await clear_reaction(emoji)¶
This function is a coroutine.
Clears a specific reaction from the message.
The emoji may be a unicode emoji or a custom guild
Emoji.You must have
manage_messagesto do this.New in version 1.3.
Changed in version 2.0: This function will now raise
TypeErrorinstead ofInvalidArgument.- Parameters
emoji (Union[
Emoji,Reaction,PartialEmoji,str]) – The emoji to clear.- Raises
HTTPException – Clearing the reaction failed.
Forbidden – You do not have the proper permissions to clear the reaction.
NotFound – The emoji you specified was not found.
TypeError – The emoji parameter is invalid.
- await clear_reactions()¶
This function is a coroutine.
Removes all the reactions from the message.
You must have
manage_messagesto do this.- Raises
HTTPException – Removing the reactions failed.
Forbidden – You do not have the proper permissions to remove all the reactions.
- await create_thread(*, name, auto_archive_duration=..., slowmode_delay=None, reason=None)¶
This function is a coroutine.
Creates a public thread from this message.
You must have
create_public_threadsin order to create a public thread from a message.The channel this message belongs in must be a
TextChannel.New in version 2.0.
- Parameters
name (
str) – The name of the thread.auto_archive_duration (
int) –The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used.
Must be one of
60,1440,4320, or10080, if provided.slowmode_delay (Optional[
int]) – Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is21600. By default no slowmode rate limit if this isNone.reason (Optional[
str]) – The reason for creating a new thread. Shows up on the audit log.
- Raises
Forbidden – You do not have permissions to create a thread.
HTTPException – Creating the thread failed.
ValueError – This message does not have guild info attached.
- Returns
The created thread.
- Return type
- await ack()¶
This function is a coroutine.
Marks this message as read.
- Raises
HTTPException – Acking failed.
- await reply(content=None, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.send()to reply to theMessage.New in version 1.6.
Changed in version 2.0: This function will now raise
TypeErrororValueErrorinstead ofInvalidArgument.- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
ValueError – The
fileslist is not of the appropriate sizeTypeError – You specified both
fileandfiles.
- Returns
The message that was sent.
- Return type
- await greet(sticker, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.greet()to reply to theMessagewith a sticker greeting.New in version 2.0.
- Raises
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message, or this is not a valid greet context.
- Returns
The sticker greeting that was sent.
- Return type
- to_reference(*, fail_if_not_exists=True)¶
Creates a
MessageReferencefrom the current message.New in version 1.6.
- Parameters
fail_if_not_exists (
bool) –Whether replying using the message reference should raise
HTTPExceptionif the message no longer exists or Discord could not fetch the message.New in version 1.7.
- Returns
The reference to this message.
- Return type
- defis_spoiler
- asyncread
- asyncsave
- asyncto_file
- class discord.Attachment¶
Represents an attachment from Discord.
- str(x)
Returns the URL of the attachment.
- x == y
Checks if the attachment is equal to another attachment.
- x != y
Checks if the attachment is not equal to another attachment.
- hash(x)
Returns the hash of the attachment.
Changed in version 1.7: Attachment can now be casted to
strand is hashable.- height¶
The attachment’s height, in pixels. Only applicable to images and videos.
- Type
Optional[
int]
- url¶
The attachment URL. If the message this attachment was attached to is deleted, then this will 404.
- Type
- proxy_url¶
The proxy URL. This is a cached version of the
urlin the case of images. When the message is deleted, this URL might be valid for a few minutes or not valid at all.- Type
- content_type¶
The attachment’s media type
New in version 1.7.
- Type
Optional[
str]
- description¶
The attachment’s description. Only applicable to images.
New in version 2.0.
- Type
Optional[
str]
- await save(fp, *, seek_begin=True, use_cached=False)¶
This function is a coroutine.
Saves this attachment into a file-like object.
- Parameters
fp (Union[
io.BufferedIOBase,os.PathLike]) – The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead.seek_begin (
bool) – Whether to seek to the beginning of the file after saving is successfully done.use_cached (
bool) – Whether to useproxy_urlrather thanurlwhen downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.
- Raises
HTTPException – Saving the attachment failed.
NotFound – The attachment was deleted.
- Returns
The number of bytes written.
- Return type
- await read(*, use_cached=False)¶
This function is a coroutine.
Retrieves the content of this attachment as a
bytesobject.New in version 1.1.
- Parameters
use_cached (
bool) – Whether to useproxy_urlrather thanurlwhen downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.- Raises
HTTPException – Downloading the attachment failed.
Forbidden – You do not have permissions to access this attachment
NotFound – The attachment was deleted.
- Returns
The contents of the attachment.
- Return type
- await to_file(*, filename=..., description=..., use_cached=False, spoiler=False)¶
This function is a coroutine.
Converts the attachment into a
Filesuitable for sending viaabc.Messageable.send().New in version 1.3.
- Parameters
filename (Optional[
str]) –The filename to use for the file. If not specified then the filename of the attachment is used instead.
New in version 2.0.
description (Optional[
str]) –The description to use for the file. If not specified then the description of the attachment is used instead.
New in version 2.0.
use_cached (
bool) –Whether to use
proxy_urlrather thanurlwhen downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.New in version 1.4.
spoiler (
bool) –Whether the file is a spoiler.
New in version 1.4.
- Raises
HTTPException – Downloading the attachment failed.
Forbidden – You do not have permissions to access this attachment
NotFound – The attachment was deleted.
- Returns
The attachment as a file suitable for sending.
- Return type
- class discord.MessageReference¶
Represents a reference to a
Message.New in version 1.5.
Changed in version 1.6: This class can now be constructed by users.
- fail_if_not_exists¶
Whether replying to the referenced message should raise
HTTPExceptionif the message no longer exists or Discord could not fetch the message.New in version 1.7.
- Type
- resolved¶
The message that this reference resolved to. If this is
Nonethen the original message was not fetched either due to the Discord API not attempting to resolve it or it not being available at the time of creation. If the message was resolved at a prior point but has since been deleted then this will be of typeDeletedReferencedMessage.Currently, this is mainly the replied to message when a user replies to a message.
New in version 1.6.
- Type
Optional[Union[
Message,DeletedReferencedMessage]]
- classmethod from_message(message, *, fail_if_not_exists=True)¶
Creates a
MessageReferencefrom an existingMessage.New in version 1.6.
- Parameters
message (
Message) – The message to be converted into a reference.fail_if_not_exists (
bool) –Whether replying to the referenced message should raise
HTTPExceptionif the message no longer exists or Discord could not fetch the message.New in version 1.7.
- Returns
A reference to the message.
- Return type
- class discord.DeletedReferencedMessage¶
A special sentinel type given when the resolved message reference points to a deleted message.
The purpose of this class is to separate referenced messages that could not be fetched and those that were previously fetched but have since been deleted.
New in version 1.6.
- class discord.RoleSubscriptionInfo¶
Represents a message’s role subscription information.
This is currently only attached to messages of type
MessageType.role_subscription_purchase.New in version 2.0.
- role_subscription_listing_id¶
The ID of the SKU and listing that the user is subscribed to.
- Type
- total_months_subscribed¶
The cumulative number of months that the user has been subscribed for.
- Type
Reaction¶
- class discord.Reaction¶
Represents a reaction to a message.
Depending on the way this object was created, some of the attributes can have a value of
None.- x == y
Checks if two reactions are equal. This works by checking if the emoji is the same. So two messages with the same reaction will be considered “equal”.
- x != y
Checks if two reactions are not equal.
- hash(x)
Returns the reaction’s hash.
- str(x)
Returns the string form of the reaction’s emoji.
- emoji¶
The reaction emoji. May be a custom emoji, or a unicode emoji.
- Type
Union[
Emoji,PartialEmoji,str]
- await remove(user)¶
This function is a coroutine.
Remove the reaction by the provided
Userfrom the message.If the reaction is not your own (i.e.
userparameter is not you) thenmanage_messagesis needed.The
userparameter must represent a user or member and meet theabc.Snowflakeabc.- Parameters
user (
abc.Snowflake) – The user or member from which to remove the reaction.- Raises
HTTPException – Removing the reaction failed.
Forbidden – You do not have the proper permissions to remove the reaction.
NotFound – The user you specified, or the reaction’s message was not found.
- await clear()¶
This function is a coroutine.
Clears this reaction from the message.
You must have
manage_messagesto do this.New in version 1.3.
Changed in version 2.0: This function will now raise
ValueErrorinstead ofInvalidArgument.- Raises
HTTPException – Clearing the reaction failed.
Forbidden – You do not have the proper permissions to clear the reaction.
NotFound – The emoji you specified was not found.
TypeError – The emoji parameter is invalid.
- async for ... in users(*, limit=None, after=None)¶
Returns an asynchronous iterator representing the users that have reacted to the message.
The
afterparameter must represent a member and meet theabc.Snowflakeabc.Changed in version 2.0:
limitandafterparameters are now keyword-only.Examples
Usage
# I do not actually recommend doing this async for user in reaction.users(): await channel.send(f'{user} has reacted with {reaction.emoji}!')
Flattening into a list:
users = [user async for user in reaction.users()] # users is now a list of User... winner = random.choice(users) await channel.send(f'{winner} has won the raffle.')
- Parameters
limit (Optional[
int]) – The maximum number of results to return. If not provided, returns all the users who reacted to the message.after (Optional[
abc.Snowflake]) – For pagination, reactions are sorted by member.
- Raises
HTTPException – Getting the users for the reaction failed.
- Yields
Union[
User,Member] – The member (if retrievable) or the user that has reacted to this message. The case where it can be aMemberis in a guild message context. Sometimes it can be aUserif the member has left the guild.
Interaction¶
- class discord.Interaction¶
Represents an interaction.
New in version 2.0.
- x == y
Checks if two interactions are equal.
- x != y
Checks if two interactions are not equal.
- hash(x)
Return the interaction’s hash.
- str(x)
Returns a string representation of the interaction, if any.
- type¶
The type of interaction.
- Type
- channel¶
The channel this interaction originated from.
- Type
Union[
TextChannel,VoiceChannel,Thread,DMChannel]
- user¶
The
Memberwho initiated the interaction. Ifchannelis a private channel or the user has the left the guild, then it is aUserinstead.
- successful¶
Whether the interaction succeeded. If this is your interaction, this is not immediately available. It is filled when Discord notifies us about the outcome of the interaction.
- Type
- modal¶
The modal that is in response to this interaction. This is not immediately available and is filled when the modal is dispatched.
- Type
Optional[
Modal]
Modal¶
- asyncsubmit
- class discord.Modal¶
Represents a modal from the Discord Bot UI Kit.
New in version 2.0.
- x == y
Checks if two modals are equal.
- x != y
Checks if two modals are not equal.
- hash(x)
Return the modal’s hash.
- str(x)
Returns the modal’s title.
- application¶
The application that sent the modal.
- await submit()¶
This function is a coroutine.
Submits the modal.
All required components must be already answered.
- Raises
InvalidData – Didn’t receive a response from Discord (doesn’t mean the interaction failed).
NotFound – The originating message was not found.
HTTPException – Choosing the options failed.
- Returns
The interaction that was created.
- Return type
Component¶
- class discord.Component¶
Represents a Discord Bot UI Kit Component.
Currently, the only components supported by Discord are:
New in version 2.0.
- property type¶
The type of component.
- Type
- class discord.ActionRow¶
Represents a Discord Bot UI Kit Action Row.
This is a component that holds up to 5 children components in a row.
This inherits from
Component.New in version 2.0.
- children¶
The children components that this holds, if any.
- Type
List[Union[
Button,SelectMenu,TextInput]]
- property type¶
The type of component.
- Type
- class discord.Button¶
Represents a button from the Discord Bot UI Kit.
This inherits from
Component.New in version 2.0.
- style¶
The style of the button.
- Type
- custom_id¶
The ID of the button that gets received during an interaction. If this button is for a URL, it does not have a custom ID.
- Type
Optional[
str]
- emoji¶
The emoji of the button, if available.
- Type
Optional[
PartialEmoji]
- property type¶
The type of component.
- Type
- await click()¶
This function is a coroutine.
Clicks the button.
- Raises
InvalidData – Didn’t receive a response from Discord (doesn’t mean the interaction failed).
NotFound – The originating message was not found.
HTTPException – Clicking the button failed.
- Returns
The button’s URL or the interaction that was created.
- Return type
Union[
str,Interaction]
- asyncchoose
- class discord.SelectMenu¶
Represents a select menu from the Discord Bot UI Kit.
A select menu is functionally the same as a dropdown, however on mobile it renders a bit differently.
New in version 2.0.
- options¶
A list of options that can be selected in this menu.
- Type
List[
SelectOption]
- property type¶
The type of component.
- Type
- await choose(*options)¶
This function is a coroutine.
Chooses the given options from the select menu.
- Raises
InvalidData – Didn’t receive a response from Discord (doesn’t mean the interaction failed).
NotFound – The originating message was not found.
HTTPException – Choosing the options failed.
- Returns
The interaction that was created.
- Return type
- class discord.SelectOption¶
Represents a select menu’s option.
New in version 2.0.
- label¶
The label of the option. This is displayed to users. Can only be up to 100 characters.
- Type
- value¶
The value of the option. This is not displayed to users. If not provided when constructed then it defaults to the label. Can only be up to 100 characters.
- Type
- description¶
An additional description of the option, if any. Can only be up to 100 characters.
- Type
Optional[
str]
- emoji¶
The emoji of the option, if available.
- Type
Optional[
PartialEmoji]
- defanswer
- class discord.TextInput¶
Represents a text input from the Discord Bot UI Kit.
New in version 2.0.
- property type¶
The type of component.
- Type
- property value¶
The current value of the text input. Defaults to
default.This can be set to change the answer to the text input.
- Type
Optional[
str]
- answer(value, /)¶
A shorthand method to answer the text input.
- Parameters
value (Optional[
str]) – The value to set the answer to.- Raises
ValueError – The answer is shorter than
min_lengthor longer thanmax_length.
ApplicationCommand¶
- class discord.UserCommand¶
Represents a user command.
New in version 2.0.
- x == y
Checks if two commands are equal.
- x != y
Checks if two commands are not equal.
- hash(x)
Return the command’s hash.
- str(x)
Returns the command’s name.
- type¶
The type of application command. This will always be
AppCommandType.user.- Type
- application¶
The application this command belongs to. Only available if requested.
- Type
Optional[
IntegrationApplication]
- guild_id¶
The ID of the guild this command is registered in. A value of
Nonedenotes that it is a global command.- Type
Optional[
int]
- await __call__(user=None, *, channel=None)¶
This function is a coroutine.
Use the user command.
- Parameters
user (Optional[
User]) – The user to use the command on. Overridestarget_user. Required iftarget_useris not set.channel (Optional[
abc.Messageable]) – The channel to use the command on. Overridestarget_channel. Required iftarget_channelis not set.
- Returns
The interaction that was created.
- Return type
- property target_user¶
The user this application command will be used on.
You can set this in order to use this command on a different user without re-fetching it.
- Type
Optional[
Snowflake]
- property default_member_permissions¶
The default permissions required to use this command.
Note
This may be overrided on a guild-by-guild basis.
- Type
Optional[
Permissions]
- is_group()¶
Query whether this command is a group.
- Returns
Whether this command is a group.
- Return type
- property target_channel¶
The channel this application command will be used on.
You can set this in order to use this command in a different channel without re-fetching it.
- Type
Optional[
abc.Messageable]
- class discord.MessageCommand¶
Represents a message command.
New in version 2.0.
- x == y
Checks if two commands are equal.
- x != y
Checks if two commands are not equal.
- hash(x)
Return the command’s hash.
- str(x)
Returns the command’s name.
- type¶
The type of application command. This will always be
AppCommandType.message.- Type
- application¶
The application this command belongs to. Only available if requested.
- Type
Optional[
IntegrationApplication]
- guild_id¶
The ID of the guild this command is registered in. A value of
Nonedenotes that it is a global command.- Type
Optional[
int]
- await __call__(message=None, *, channel=None)¶
This function is a coroutine.
Use the message command.
- Parameters
message (Optional[
Message]) – The message to use the command on. Overridestarget_message. Required iftarget_messageis not set.channel (Optional[
abc.Messageable]) – The channel to use the command on. Overridestarget_channel. Required iftarget_channelis not set.
- Returns
The interaction that was created.
- Return type
- property target_message¶
The message this application command will be used on.
You can set this in order to use this command on a different message without re-fetching it.
- Type
Optional[
Message]
- property default_member_permissions¶
The default permissions required to use this command.
Note
This may be overrided on a guild-by-guild basis.
- Type
Optional[
Permissions]
- is_group()¶
Query whether this command is a group.
- Returns
Whether this command is a group.
- Return type
- property target_channel¶
The channel this application command will be used on.
You can set this in order to use this command in a different channel without re-fetching it.
- Type
Optional[
abc.Messageable]
- class discord.SlashCommand¶
Represents a slash command.
New in version 2.0.
- x == y
Checks if two commands are equal.
- x != y
Checks if two commands are not equal.
- hash(x)
Return the command’s hash.
- str(x)
Returns the command’s name.
- type¶
The type of application command.
- Type
- application¶
The application this command belongs to. Only available if requested.
- Type
Optional[
IntegrationApplication]
- guild_id¶
The ID of the guild this command is registered in. A value of
Nonedenotes that it is a global command.- Type
Optional[
int]
- children¶
The command’s subcommands. If a command has subcommands, it is a group and cannot be used.
- Type
List[
SubCommand]
- await __call__(channel=None, /, **kwargs)¶
This function is a coroutine.
Use the slash command.
- Parameters
channel (Optional[
abc.Messageable]) – The channel to use the command on. Overridestarget_channel. Required iftarget_channelis not set.**kwargs (Any) – The options to use. These will be casted to the correct type. If an option has choices, they are automatically converted from name to value for you.
- Raises
TypeError – Attempted to use a group.
- Returns
The interaction that was created.
- Return type
- is_group()¶
Query whether this command is a group.
- Returns
Whether this command is a group.
- Return type
- property default_member_permissions¶
The default permissions required to use this command.
Note
This may be overrided on a guild-by-guild basis.
- Type
Optional[
Permissions]
- property target_channel¶
The channel this application command will be used on.
You can set this in order to use this command in a different channel without re-fetching it.
- Type
Optional[
abc.Messageable]
- class discord.SubCommand¶
Represents a slash command child.
New in version 2.0.
This could be a subcommand, or a subgroup.
- str(x)
Returns the command’s name.
- type¶
The type of application command. Always
AppCommandType.chat_input.- Type
- parent¶
The parent command.
- Type
Union[
SlashCommand,SubCommand]
- children¶
The subcommand’s subcommands. If a subcommand has subcommands, it is a group and cannot be used.
- Type
List[
SubCommand]
- await __call__(channel=None, /, **kwargs)¶
This function is a coroutine.
Use the sub command.
- Parameters
channel (Optional[
abc.Messageable]) – The channel to use the command on. Overridestarget_channel. Required iftarget_channelis not set.**kwargs (Any) – The options to use. These will be casted to the correct type. If an option has choices, they are automatically converted from name to value for you.
- Raises
TypeError – Attempted to use a group.
- Returns
The interaction that was created.
- Return type
- property qualified_name¶
Returns the fully qualified command name. The qualified name includes the parent name as well. For example, in a command like
/foo barthe qualified name isfoo bar.- Type
- property guild_id¶
The ID of the guild this command is registered in. A value of
Nonedenotes that it is a global command.- Type
Optional[
int]
- is_group()¶
Query whether this command is a group.
- Returns
Whether this command is a group.
- Return type
- property application¶
The application this command belongs to. Only available if requested.
- Type
Optional[
IntegrationApplication]
- property target_channel¶
The channel this command will be used on.
You can set this in order to use this command on a different channel without re-fetching it.
- Type
Optional[
abc.Messageable]
- property default_member_permissions¶
The default permissions required to use this command.
Note
This may be overrided on a guild-by-guild basis.
- Type
Optional[
Permissions]
- class discord.Option¶
Represents a command option.
New in version 2.0.
- str(x)
Returns the option’s name.
- type¶
The type of option.
- Type
- min_value¶
Minimum value of the option. Only applicable to
AppCommandOptionType.integerandAppCommandOptionType.number.
- max_value¶
Maximum value of the option. Only applicable to
AppCommandOptionType.integerandAppCommandOptionType.number.
- choices¶
A list of possible choices to choose from. If these are present, you must choose one from them.
Only applicable to
AppCommandOptionType.string,AppCommandOptionType.integer, andAppCommandOptionType.number.- Type
List[
OptionChoice]
- channel_types¶
A list of channel types that you can choose from. If these are present, you must choose a channel that is one of these types.
Only applicable to
AppCommandOptionType.channel.- Type
List[
ChannelType]
- autocomplete¶
Whether the option autocompletes.
Only applicable to
AppCommandOptionType.string,AppCommandOptionType.integer, andAppCommandOptionType.number. AlwaysFalseifchoicesare present.- Type
Invite¶
- asyncaccept
- asyncdelete
- defset_scheduled_event
- asyncuse
- class discord.Invite¶
Represents a Discord
Guildorabc.GuildChannelinvite.Depending on the way this object was created, some of the attributes can have a value of
None.- x == y
Checks if two invites are equal.
- x != y
Checks if two invites are not equal.
- hash(x)
Returns the invite hash.
- str(x)
Returns the invite URL.
The following table illustrates what methods will obtain the attributes:
Attribute
Method
Client.fetch_invite()withwith_countsenabledClient.fetch_invite()withwith_countsenabledIf it’s not in the table above then it is available by all methods.
- max_age¶
How long before the invite expires in seconds. A value of
0indicates that it doesn’t expire.- Type
Optional[
int]
- type¶
The type of invite.
New in version 2.0.
- Type
- guild¶
The guild the invite is for. Can be
Noneif not a guild invite.- Type
Optional[Union[
Guild,Object,PartialInviteGuild]]
- created_at¶
An aware UTC datetime object denoting the time the invite was created.
- Type
Optional[
datetime.datetime]
- temporary¶
Indicates that the invite grants temporary membership. If
True, members who joined via this invite will be kicked upon disconnect.- Type
Optional[
bool]
- max_uses¶
How many times the invite can be used. A value of
0indicates that it has unlimited uses.- Type
Optional[
int]
- approximate_presence_count¶
The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded.
- Type
Optional[
int]
- expires_at¶
The expiration date of the invite. If the value is
None(unless received throughClient.fetch_invite()withwith_expirationdisabled), the invite will never expire.New in version 2.0.
- Type
Optional[
datetime.datetime]
- channel¶
The channel the invite is for. Can be
Noneif not a guild invite.- Type
Optional[Union[
abc.GuildChannel,GroupChannel,Object,PartialInviteChannel]]
- target_type¶
The type of target for the voice channel invite.
New in version 2.0.
- Type
- target_user¶
The user whose stream to display for this invite, if any.
New in version 2.0.
- Type
Optional[
User]
- target_application¶
The embedded application the invite targets, if any.
New in version 2.0.
- Type
Optional[
PartialApplication]
- scheduled_event¶
The scheduled event associated with this invite, if any.
New in version 2.0.
- Type
Optional[
ScheduledEvent]
- scheduled_event_id¶
The ID of the scheduled event associated with this invite, if any.
New in version 2.0.
- Type
Optional[
int]
- welcome_screen¶
The guild’s welcome screen, if available.
New in version 2.0.
- Type
Optional[
WelcomeScreen]
- new_member¶
Whether the user was not previously a member of the guild.
New in version 2.0.
Note
This is only possibly
Truein accepted invite objects (i.e. the objects received fromaccept()anduse()).- Type
- show_verification_form¶
Whether the user should be shown the guild’s member verification form.
New in version 2.0.
Note
This is only possibly
Truein accepted invite objects (i.e. the objects received fromaccept()anduse()).- Type
- set_scheduled_event(scheduled_event, /)¶
Sets the scheduled event for this invite.
New in version 2.0.
- await use()¶
This function is a coroutine.
Uses the invite. Either joins a guild, joins a group DM, or adds a friend.
There is an alias for this called
accept().New in version 1.9.
- Raises
HTTPException – Using the invite failed.
- Returns
The accepted invite.
- Return type
- await accept()¶
This function is a coroutine.
Uses the invite. Either joins a guild, joins a group DM, or adds a friend.
This is an alias of
use().New in version 1.9.
- Raises
HTTPException – Using the invite failed.
- Returns
The accepted invite.
- Return type
- await delete(*, reason=None)¶
This function is a coroutine.
Revokes the instant invite.
In a guild context, you must have
manage_channelsto do this.Changed in version 2.0: The function now returns the deleted invite.
- Parameters
reason (Optional[
str]) –The reason for deleting this invite. Shows up on the audit log.
Only applicable to guild invites.
- Raises
Forbidden – You do not have permissions to revoke invites.
NotFound – The invite is invalid or expired.
HTTPException – Revoking the invite failed.
- Returns
The deleted invite.
- Return type
- class discord.PartialInviteGuild¶
Represents a “partial” invite guild.
This model will be given when the user is not part of the guild the
Inviteresolves to.- x == y
Checks if two partial guilds are the same.
- x != y
Checks if two partial guilds are not the same.
- hash(x)
Return the partial guild’s hash.
- str(x)
Returns the partial guild’s name.
- verification_level¶
The partial guild’s verification level.
- Type
- features¶
A list of features the guild has. See
Guild.featuresfor more information.- Type
List[
str]
- vanity_url_code¶
The partial guild’s vanity URL code, if available.
New in version 2.0.
- Type
Optional[
str]
The number of “boosts” the partial guild currently has.
New in version 2.0.
- Type
- property created_at¶
Returns the guild’s creation time in UTC.
- Type
- class discord.PartialInviteChannel¶
Represents a “partial” invite channel.
This model will be given when the user is not part of the guild or group channel the
Inviteresolves to.- x == y
Checks if two partial channels are the same.
- x != y
Checks if two partial channels are not the same.
- hash(x)
Return the partial channel’s hash.
- str(x)
Returns the partial channel’s name.
- type¶
The partial channel’s type.
- Type
- recipients¶
The partial channel’s recipient names. This is only applicable to group DMs.
New in version 2.0.
- Type
Optional[List[
str]]
- property created_at¶
Returns the channel’s creation time in UTC.
- Type
- property icon¶
Returns the channel’s icon asset if available.
Only applicable to channels of type
ChannelType.group.New in version 2.0.
- Type
Optional[
Asset]
Template¶
- asynccreate_guild
- asyncdelete
- asyncedit
- asyncsync
- class discord.Template¶
Represents a Discord template.
New in version 1.4.
- created_at¶
An aware datetime in UTC representing when the template was created.
- Type
- updated_at¶
An aware datetime in UTC representing when the template was last updated. This is referred to as “last synced” in the official Discord client.
- Type
- source_guild¶
The guild snapshot that represents the data that this template currently holds.
- Type
- await create_guild(name, icon=...)¶
This function is a coroutine.
Creates a
Guildusing the template.Changed in version 2.0: The
regionparameter has been removed.Changed in version 2.0: This function will now raise
ValueErrorinstead ofInvalidArgument.- Parameters
name (
str) – The name of the guild.icon (
bytes) – The bytes-like object representing the icon. SeeClientUser.edit()for more details on what is expected.
- 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 sync()¶
This function is a coroutine.
Sync the template to the guild’s current state.
You must have
manage_guildin the source guild to do this.New in version 1.7.
Changed in version 2.0: The template is no longer edited in-place, instead it is returned.
- Raises
HTTPException – Editing the template failed.
Forbidden – You don’t have permissions to edit the template.
NotFound – This template does not exist.
- Returns
The newly edited template.
- Return type
- await edit(*, name=..., description=...)¶
This function is a coroutine.
Edit the template metadata.
You must have
manage_guildin the source guild to do this.New in version 1.7.
Changed in version 2.0: The template is no longer edited in-place, instead it is returned.
- Parameters
- Raises
HTTPException – Editing the template failed.
Forbidden – You don’t have permissions to edit the template.
NotFound – This template does not exist.
- Returns
The newly edited template.
- Return type
- await delete()¶
This function is a coroutine.
Delete the template.
You must have
manage_guildin the source guild to do this.New in version 1.7.
- Raises
HTTPException – Editing the template failed.
Forbidden – You don’t have permissions to edit the template.
NotFound – This template does not exist.
Widget¶
- asyncfetch_invite
- class discord.Widget¶
Represents a
Guildwidget.- x == y
Checks if two widgets are the same.
- x != y
Checks if two widgets are not the same.
- str(x)
Returns the widget’s JSON URL.
- channels¶
The accessible voice channels in the guild.
- Type
List[
WidgetChannel]
- members¶
The online members in the guild. Offline members do not appear in the widget.
Note
Due to a Discord limitation, if this data is available the users will be “anonymized” with linear IDs and discriminator information being incorrect. Likewise, the number of members retrieved is capped.
- Type
List[
WidgetMember]
- presence_count¶
The approximate number of online members in the guild. Offline members are not included in this count.
New in version 2.0.
- Type
- property created_at¶
Returns the member’s creation time in UTC.
- Type
- await fetch_invite(*, with_counts=True)¶
This function is a coroutine.
Retrieves an
Invitefrom the widget’s invite URL. This is the same asClient.fetch_invite(); the invite code is abstracted away.- Parameters
with_counts (
bool) – Whether to include count information in the invite. This fills theInvite.approximate_member_countandInvite.approximate_presence_countfields.- Returns
The invite from the widget’s invite URL, if available.
- Return type
Optional[
Invite]
- class discord.WidgetChannel¶
Represents a “partial” widget channel.
- x == y
Checks if two partial channels are the same.
- x != y
Checks if two partial channels are not the same.
- hash(x)
Return the partial channel’s hash.
- str(x)
Returns the partial channel’s name.
- property created_at¶
Returns the channel’s creation time in UTC.
- Type
- defmentioned_in
- class discord.WidgetMember¶
Represents a “partial” member of the widget’s guild.
- x == y
Checks if two widget members are the same.
- x != y
Checks if two widget members are not the same.
- hash(x)
Return the widget member’s hash.
- str(x)
Returns the widget member’s
name#discriminator.
- activity¶
The member’s activity.
- Type
Optional[Union[
BaseActivity,Spotify]]
- connected_channel¶
Which channel the member is connected to.
- Type
Optional[
WidgetChannel]
- 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_decoration¶
Returns an
Assetfor the avatar decoration the user has.If the user does not have a avatar decoration,
Noneis returned.New in version 2.0.
- Type
Optional[
Asset]
- 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 default_avatar¶
Returns the default avatar for a given user. This is calculated by the user’s discriminator.
- 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_banner¶
Returns the user’s banner asset, if available.
This is the same as
bannerand is here for compatibility.New in version 2.0.
- Type
Optional[
Asset]
- mentioned_in(message)¶
Checks if the user is mentioned in the specified message.
- note¶
Returns an object representing the user’s note.
New in version 2.0.
Note
The underlying note is cached and updated from gateway events.
- Type
- property public_flags¶
The publicly available flags the user has.
- Type
- property voice¶
Returns the user’s current voice state.
- Type
Optional[
VoiceState]
WelcomeScreen¶
- asyncedit
- class discord.WelcomeScreen¶
Represents a
Guild’s welcome screen.New in version 2.0.
- bool(b)
Returns whether the welcome screen is enabled.
- guild¶
The guild the welcome screen is for.
- Type
Union[
Guild,PartialInviteGuild]
- welcome_channels¶
The channels shown on the welcome screen.
- Type
List[
WelcomeChannel]
- await edit(*, description=..., welcome_channels=..., enabled=..., reason=None)¶
This function is a coroutine.
Edit the welcome screen.
Welcome channels can only accept custom emojis if
Guild.premium_tieris level 2 or above.You must have
manage_guildin the guild to do this.All parameters are optional.
Usage:
rules_channel = guild.get_channel(12345678) announcements_channel = guild.get_channel(87654321) custom_emoji = utils.get(guild.emojis, name='loudspeaker') await welcome_screen.edit( description='This is a very cool community server!', welcome_channels=[ WelcomeChannel(channel=rules_channel, description='Read the rules!', emoji='👨🏫'), WelcomeChannel(channel=announcements_channel, description='Watch out for announcements!', emoji=custom_emoji), ] )
- Parameters
enabled (
bool) – Whether the welcome screen will be shown.description (
str) – The welcome screen’s description.welcome_channels (Optional[List[
WelcomeChannel]]) – The welcome channels (in order).reason (Optional[
str]) – The reason for editing the welcome screen. Shows up on the audit log.
- Raises
HTTPException – Editing the welcome screen failed failed.
Forbidden – You don’t have permissions to edit the welcome screen.
- class discord.WelcomeChannel¶
Represents a channel shown on a
WelcomeScreen.New in version 2.0.
- channel¶
The channel that is being shown.
- Type
- emoji¶
The emoji shown under the description.
- Type
Optional[Union[
PartialEmoji,Emoji]
RawEvent¶
- class discord.RawMessageDeleteEvent¶
Represents the event payload for a
on_raw_message_delete()event.
- class discord.RawBulkMessageDeleteEvent¶
Represents the event payload for a
on_raw_bulk_message_delete()event.
- class discord.RawMessageUpdateEvent¶
Represents the payload for a
on_raw_message_edit()event.- guild_id¶
The guild ID where the message got updated, if applicable.
New in version 1.7.
- Type
Optional[
int]
- cached_message¶
The cached message, if found in the internal message cache. Represents the message before it is modified by the data in
RawMessageUpdateEvent.data.- Type
Optional[
Message]
- class discord.RawReactionActionEvent¶
Represents the payload for a
on_raw_reaction_add()oron_raw_reaction_remove()event.- emoji¶
The custom or unicode emoji being used.
- Type
- class discord.RawReactionClearEvent¶
Represents the payload for a
on_raw_reaction_clear()event.
- class discord.RawReactionClearEmojiEvent¶
Represents the payload for a
on_raw_reaction_clear_emoji()event.New in version 1.3.
- emoji¶
The custom or unicode emoji being removed.
- Type
- class discord.RawIntegrationDeleteEvent¶
Represents the payload for a
on_raw_integration_delete()event.New in version 2.0.
- class discord.RawThreadMembersUpdate¶
Represents the payload for a
on_raw_thread_member_remove()event.New in version 2.0.
- class discord.RawThreadDeleteEvent¶
Represents the payload for a
on_raw_thread_delete()event.New in version 2.0.
- thread_type¶
The channel type of the deleted thread.
- Type
- thread¶
The thread, if it could be found in the internal cache.
- Type
Optional[
discord.Thread]
Data Classes¶
Some classes are just there to be data containers, this lists them.
Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes.
Nearly all classes here have __slots__ defined which means that it is impossible to have dynamic attributes to the data classes.
The only exception to this rule is Object, which is made with
dynamic attributes in mind.
Object¶
- class discord.Object¶
Represents a generic Discord object.
The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in strange order and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
- x == y
Checks if two objects are equal.
- x != y
Checks if two objects are not equal.
- hash(x)
Returns the object’s hash.
- type¶
The discord.py model type of the object, if not specified, defaults to this class.
Note
In instances where there are multiple applicable types, use a shared base class. for example, both
MemberandUserare subclasses ofabc.User.New in version 2.0.
- Type
Type[
abc.Snowflake]
- property created_at¶
Returns the snowflake’s creation time in UTC.
- Type
Embed¶
- clsEmbed.from_dict
- defadd_field
- defclear_fields
- defcopy
- definsert_field_at
- defremove_author
- defremove_field
- defremove_footer
- defset_author
- defset_field_at
- defset_footer
- defset_image
- defset_thumbnail
- defto_dict
- class discord.Embed¶
Represents a Discord embed.
- len(x)
Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
- bool(b)
Returns whether the embed has any data set.
New in version 2.0.
- x == y
Checks if two embeds are equal.
New in version 2.0.
For ease of use, all parameters that expect a
strare implicitly casted tostrfor you.Changed in version 2.0:
Embed.Emptyhas been removed in favour ofNone.- title¶
The title of the embed. This can be set during initialisation. Can only be up to 256 characters.
- Type
Optional[
str]
- type¶
The type of embed. Usually “rich”. This can be set during initialisation. Possible strings for embed types can be found on discord’s api docs
- Type
- description¶
The description of the embed. This can be set during initialisation. Can only be up to 4096 characters.
- Type
Optional[
str]
- timestamp¶
The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.
- Type
Optional[
datetime.datetime]
- colour¶
The colour code of the embed. Aliased to
coloras well. This can be set during initialisation.
- classmethod from_dict(data)¶
Converts a
dictto aEmbedprovided it is in the format that Discord expects it to be in.You can find out about this format in the official Discord documentation.
- Parameters
data (
dict) – The dictionary to convert into an embed.
- copy()¶
Returns a shallow copy of the embed.
Returns an
EmbedProxydenoting the footer contents.See
set_footer()for possible values you can access.If the attribute has no value then
Noneis returned.
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
- Parameters
text (
str) – The footer text. Can only be up to 2048 characters.icon_url (
str) – The URL of the footer icon. Only HTTP(S) is supported. Inline attachment URLs are also supported, see How do I use a local image file for an embed image?.
Clears embed’s footer information.
This function returns the class instance to allow for fluent-style chaining.
New in version 2.0.
- property image¶
Returns an
EmbedProxydenoting the image contents.Possible attributes you can access are:
urlproxy_urlwidthheight
If the attribute has no value then
Noneis returned.
- set_image(*, url)¶
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
- Parameters
url (
str) – The source URL for the image. Only HTTP(S) is supported. Inline attachment URLs are also supported, see How do I use a local image file for an embed image?.
- property thumbnail¶
Returns an
EmbedProxydenoting the thumbnail contents.Possible attributes you can access are:
urlproxy_urlwidthheight
If the attribute has no value then
Noneis returned.
- set_thumbnail(*, url)¶
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing
Noneremoves the thumbnail.- Parameters
url (
str) – The source URL for the thumbnail. Only HTTP(S) is supported. Inline attachment URLs are also supported, see How do I use a local image file for an embed image?.
- property video¶
Returns an
EmbedProxydenoting the video contents.Possible attributes include:
urlfor the video URL.heightfor the video height.widthfor the video width.
If the attribute has no value then
Noneis returned.
- property provider¶
Returns an
EmbedProxydenoting the provider contents.The only attributes that might be accessed are
nameandurl.If the attribute has no value then
Noneis returned.
- property author¶
Returns an
EmbedProxydenoting the author contents.See
set_author()for possible values you can access.If the attribute has no value then
Noneis returned.
- set_author(*, name, url=None, icon_url=None)¶
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
- Parameters
name (
str) – The name of the author. Can only be up to 256 characters.url (
str) – The URL for the author.icon_url (
str) – The URL of the author icon. Only HTTP(S) is supported. Inline attachment URLs are also supported, see How do I use a local image file for an embed image?.
- remove_author()¶
Clears embed’s author information.
This function returns the class instance to allow for fluent-style chaining.
New in version 1.4.
- property fields¶
Returns a
listofEmbedProxydenoting the field contents.See
add_field()for possible values you can access.If the attribute has no value then
Noneis returned.- Type
List[
EmbedProxy]
- add_field(*, name, value, inline=True)¶
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
- insert_field_at(index, *, name, value, inline=True)¶
Inserts a field before a specified index to the embed.
This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
New in version 1.2.
- clear_fields()¶
Removes all fields from this embed.
- remove_field(index)¶
Removes a field at a specified index.
If the index is invalid or out of bounds then the error is silently swallowed.
Note
When deleting a field by index, the index of the other fields shift to fill the gap just like a regular list.
- Parameters
index (
int) – The index of the field to remove.
- set_field_at(index, *, name, value, inline=True)¶
Modifies a field to the embed object.
The index must point to a valid pre-existing field. Can only be up to 25 fields.
This function returns the class instance to allow for fluent-style chaining.
- Parameters
- Raises
IndexError – An invalid index was provided.
- to_dict()¶
Converts this embed object into a dict.
AllowedMentions¶
- class discord.AllowedMentions¶
A class that represents what mentions are allowed in a message.
This class can be set during
Clientinitialisation to apply to every message sent. It can also be applied on a per message basis viaabc.Messageable.send()for more fine-grained control.- users¶
Controls the users being mentioned. If
True(the default) then users are mentioned based on the message content. IfFalsethen users are not mentioned at all. If a list ofabc.Snowflakeis given then only the users provided will be mentioned, provided those users are in the message content.- Type
Union[
bool, Sequence[abc.Snowflake]]
- roles¶
Controls the roles being mentioned. If
True(the default) then roles are mentioned based on the message content. IfFalsethen roles are not mentioned at all. If a list ofabc.Snowflakeis given then only the roles provided will be mentioned, provided those roles are in the message content.- Type
Union[
bool, Sequence[abc.Snowflake]]
- replied_user¶
Whether to mention the author of the message being replied to. Defaults to
True.New in version 1.6.
- Type
- classmethod all()¶
A factory method that returns a
AllowedMentionswith all fields explicitly set toTrueNew in version 1.5.
- classmethod none()¶
A factory method that returns a
AllowedMentionswith all fields set toFalseNew in version 1.5.
File¶
- class discord.File¶
A parameter object used for
abc.Messageable.send()for sending file objects.Note
File objects are single use and are not meant to be reused in multiple
abc.Messageable.send()s.- fp¶
A file-like object opened in binary mode and read mode or a filename representing a file in the hard drive to open.
Note
If the file-like object passed is opened via
openthen the modes ‘rb’ should be used.To pass binary data, consider usage of
io.BytesIO.- Type
Union[
os.PathLike,io.BufferedIOBase]
- spoiler¶
Whether the attachment is a spoiler. If left unspecified, the
filenameis used to determine if the file is a spoiler.- Type
Colour¶
- clsColour.blue
- clsColour.blurple
- clsColour.brand_green
- clsColour.brand_red
- clsColour.dark_blue
- clsColour.dark_embed
- clsColour.dark_gold
- clsColour.dark_gray
- clsColour.dark_green
- clsColour.dark_grey
- clsColour.dark_magenta
- clsColour.dark_orange
- clsColour.dark_purple
- clsColour.dark_red
- clsColour.dark_teal
- clsColour.dark_theme
- clsColour.darker_gray
- clsColour.darker_grey
- clsColour.default
- clsColour.from_hsv
- clsColour.from_rgb
- clsColour.from_str
- clsColour.fuchsia
- clsColour.gold
- clsColour.green
- clsColour.greyple
- clsColour.light_embed
- clsColour.light_gray
- clsColour.light_grey
- clsColour.lighter_gray
- clsColour.lighter_grey
- clsColour.magenta
- clsColour.og_blurple
- clsColour.orange
- clsColour.purple
- clsColour.random
- clsColour.red
- clsColour.teal
- clsColour.yellow
- defto_rgb
- class discord.Colour¶
Represents a Discord role colour. This class is similar to a (red, green, blue)
tuple.There is an alias for this called Color.
- x == y
Checks if two colours are equal.
- x != y
Checks if two colours are not equal.
- hash(x)
Return the colour’s hash.
- str(x)
Returns the hex format for the colour.
- int(x)
Returns the raw colour value.
Note
The colour values in the classmethods are mostly provided as-is and can change between versions should the Discord client’s representation of that colour also change.
- classmethod from_str(value)¶
Constructs a
Colourfrom a string.The following formats are accepted:
0x<hex>#<hex>0x#<hex>rgb(<number>, <number>, <number>)
Like CSS,
<number>can be either 0-255 or 0-100% and<hex>can be either a 6 digit hex number or a 3 digit hex shortcut (e.g. #FFF).New in version 2.0.
- Raises
ValueError – The string could not be converted into a colour.
- classmethod random(*, seed=None)¶
A factory method that returns a
Colourwith a random hue.Note
The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value.
New in version 1.6.
- classmethod brand_green()¶
A factory method that returns a
Colourwith a value of0x57F287.New in version 2.0.
- classmethod brand_red()¶
A factory method that returns a
Colourwith a value of0xED4245.New in version 2.0.
- classmethod dark_theme()¶
A factory method that returns a
Colourwith a value of0x313338.This will appear transparent on Discord’s dark theme.
New in version 1.5.
Changed in version 2.0: Updated colour from previous
0x36393Fto reflect Discord theme changes.
- classmethod fuchsia()¶
A factory method that returns a
Colourwith a value of0xEB459E.New in version 2.0.
- classmethod yellow()¶
A factory method that returns a
Colourwith a value of0xFEE75C.New in version 2.0.
Presence¶
- defis_current
- defis_headless
- defis_overall
- class discord.Session¶
Represents a connected Discord gateway session.
- x == y
Checks if two sessions are equal.
- x != y
Checks if two sessions are not equal.
- hash(x)
Returns the session’s hash.
New in version 2.0.
- os¶
The operating system the session is running on.
- Type
- client¶
The client the session is running on.
- Type
- version¶
The version of the client the session is running on (used for differentiating between e.g. PS4/PS5).
- Type
- activities¶
The activities the session is currently doing.
- Type
Tuple[Union[
BaseActivity,Spotify]]
- is_overall()¶
bool: Whether the session represents the overall presence across all platforms.Note
If this is
True, thensession_id,os, andclientwill not be real values.
- class discord.BaseActivity¶
The base activity that all user-settable activities inherit from. A user-settable activity is one that can be used in
Client.change_presence().The following types currently count as user-settable:
Note that although these types are considered user-settable by the library, Discord typically ignores certain combinations of activity depending on what is currently set. This behaviour may change in the future so there are no guarantees on whether Discord will actually let you set these types.
New in version 1.3.
- property created_at¶
When the user started doing this activity in UTC.
New in version 1.3.
- Type
Optional[
datetime.datetime]
- class discord.Activity¶
Represents an activity in Discord.
This could be an activity such as streaming, playing, listening or watching.
For memory optimisation purposes, some activities are offered in slimmed down versions:
- type¶
The type of activity currently being done.
- Type
- timestamps¶
A dictionary of timestamps. It contains the following optional keys:
start: Corresponds to when the user started doing the activity in milliseconds since Unix epoch.end: Corresponds to when the user will finish doing the activity in milliseconds since Unix epoch.
- Type
- assets¶
A dictionary representing the images and their hover text of an activity. It contains the following optional keys:
large_image: A string representing the ID for the large image asset.large_text: A string representing the text when hovering over the large image asset.small_image: A string representing the ID for the small image asset.small_text: A string representing the text when hovering over the small image asset.
- Type
- party¶
A dictionary representing the activity party. It contains the following optional keys:
id: A string representing the party ID.size: A list of up to two integer elements denoting (current_size, maximum_size).
- Type
- buttons¶
A list of strings representing the labels of custom buttons shown in a rich presence.
New in version 2.0.
- Type
List[
str]
- emoji¶
The emoji that belongs to this activity.
- Type
Optional[
PartialEmoji]
- property start¶
When the user started doing this activity in UTC, if applicable.
- Type
Optional[
datetime.datetime]
- property end¶
When the user will stop doing this activity in UTC, if applicable.
- Type
Optional[
datetime.datetime]
- property large_image_url¶
Returns a URL pointing to the large image asset of this activity, if applicable.
- Type
Optional[
str]
- property small_image_url¶
Returns a URL pointing to the small image asset of this activity, if applicable.
- Type
Optional[
str]
- class discord.Game¶
A slimmed down version of
Activitythat represents a Discord game.This is typically displayed via Playing on the official Discord client.
- x == y
Checks if two games are equal.
- x != y
Checks if two games are not equal.
- hash(x)
Returns the game’s hash.
- str(x)
Returns the game’s name.
- Parameters
name (
str) – The game’s name.
- property type¶
Returns the game’s type. This is for compatibility with
Activity.It always returns
ActivityType.playing.- Type
- property start¶
When the user started playing this game in UTC, if applicable.
- Type
Optional[
datetime.datetime]
- property end¶
When the user will stop playing this game in UTC, if applicable.
- Type
Optional[
datetime.datetime]
- class discord.Streaming¶
A slimmed down version of
Activitythat represents a Discord streaming status.This is typically displayed via Streaming on the official Discord client.
- x == y
Checks if two streams are equal.
- x != y
Checks if two streams are not equal.
- hash(x)
Returns the stream’s hash.
- str(x)
Returns the stream’s name.
- platform¶
Where the user is streaming from (ie. YouTube, Twitch).
New in version 1.3.
- Type
Optional[
str]
- assets¶
A dictionary comprising of similar keys than those in
Activity.assets.- Type
- property type¶
Returns the game’s type. This is for compatibility with
Activity.It always returns
ActivityType.streaming.- Type
- property twitch_name¶
If provided, the twitch name of the user streaming.
This corresponds to the
large_imagekey of theStreaming.assetsdictionary if it starts withtwitch:. Typically set by the Discord client.- Type
Optional[
str]
- class discord.Spotify¶
Represents a Spotify listening activity from Discord. This is a special case of
Activitythat makes it easier to work with the Spotify integration.- x == y
Checks if two activities are equal.
- x != y
Checks if two activities are not equal.
- hash(x)
Returns the activity’s hash.
- str(x)
Returns the string ‘Spotify’.
- property type¶
Returns the activity’s type. This is for compatibility with
Activity.It always returns
ActivityType.listening.- Type
- property created_at¶
When the user started listening in UTC.
New in version 1.3.
- Type
Optional[
datetime.datetime]
- property colour¶
Returns the Spotify integration colour, as a
Colour.There is an alias for this named
color- Type
- property color¶
Returns the Spotify integration colour, as a
Colour.There is an alias for this named
colour- Type
- property artist¶
The artist of the song being played.
This does not attempt to split the artist information into multiple artists. Useful if there’s only a single artist.
- Type
- property start¶
When the user started playing this song in UTC.
- Type
- property end¶
When the user will stop playing this song in UTC.
- Type
- property duration¶
The duration of the song being played.
- Type
- class discord.CustomActivity¶
Represents a custom activity from Discord.
- x == y
Checks if two activities are equal.
- x != y
Checks if two activities are not equal.
- hash(x)
Returns the activity’s hash.
- str(x)
Returns the custom status text.
New in version 1.3.
Note
Technically, the name of custom activities is hardcoded to “Custom Status”, and the state parameter has the actual custom text. This is confusing, so here, the name represents the actual custom text. However, the “correct” way of initialization still works.
- emoji¶
The emoji to pass to the activity, if any.
- Type
Optional[
PartialEmoji]
- expires_at¶
When the custom activity will expire. This is only available from
UserSettings.custom_activity- Type
Optional[
datetime.datetime]
- property type¶
Returns the activity’s type. This is for compatibility with
Activity.It always returns
ActivityType.custom.- Type
Permissions¶
- add_reactions
- administrator
- attach_files
- ban_members
- change_nickname
- connect
- create_instant_invite
- create_private_threads
- create_public_threads
- deafen_members
- embed_links
- external_emojis
- external_stickers
- kick_members
- manage_channels
- manage_emojis
- manage_emojis_and_stickers
- manage_events
- manage_guild
- manage_guild_expressions
- manage_messages
- manage_nicknames
- manage_permissions
- manage_roles
- manage_threads
- manage_webhooks
- mention_everyone
- moderate_members
- move_members
- mute_members
- priority_speaker
- read_message_history
- read_messages
- request_to_speak
- send_messages
- send_messages_in_threads
- send_tts_messages
- speak
- stream
- use_application_commands
- use_embedded_activities
- use_external_emojis
- use_external_sounds
- use_external_stickers
- use_soundboard
- use_voice_activation
- value
- view_audit_log
- view_channel
- view_guild_insights
- clsPermissions.advanced
- clsPermissions.all
- clsPermissions.all_channel
- clsPermissions.elevated
- clsPermissions.general
- clsPermissions.membership
- clsPermissions.none
- clsPermissions.stage
- clsPermissions.stage_moderator
- clsPermissions.text
- clsPermissions.voice
- defis_strict_subset
- defis_strict_superset
- defis_subset
- defis_superset
- defupdate
- class discord.Permissions¶
Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.
Changed in version 1.3: You can now use keyword arguments to initialize
Permissionssimilar toupdate().- x == y
Checks if two permissions are equal.
- x != y
Checks if two permissions are not equal.
- x <= y
Checks if a permission is a subset of another permission.
- x >= y
Checks if a permission is a superset of another permission.
- x < y
Checks if a permission is a strict subset of another permission.
- x > y
Checks if a permission is a strict superset of another permission.
- x | y, x |= y
Returns a Permissions instance with all enabled flags from both x and y.
New in version 2.0.
- x & y, x &= y
Returns a Permissions instance with only flags enabled on both x and y.
New in version 2.0.
- x ^ y, x ^= y
Returns a Permissions instance with only flags enabled on only one of x or y, not on both.
New in version 2.0.
- ~x
Returns a Permissions instance with all flags inverted from x.
New in version 2.0.
- hash(x)
Return the permission’s hash.
- iter(x)
Returns an iterator of
(perm, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available permissions. You should query permissions via the properties rather than using this raw value.
- Type
- is_subset(other)¶
Returns
Trueif self has the same or fewer permissions as other.
- is_superset(other)¶
Returns
Trueif self has the same or more permissions as other.
- is_strict_subset(other)¶
Returns
Trueif the permissions on other are a strict subset of those on self.
- is_strict_superset(other)¶
Returns
Trueif the permissions on other are a strict superset of those on self.
- classmethod none()¶
A factory method that creates a
Permissionswith all permissions set toFalse.
- classmethod all()¶
A factory method that creates a
Permissionswith all permissions set toTrue.
- classmethod all_channel()¶
A
Permissionswith all channel-specific permissions set toTrueand the guild-specific ones set toFalse. The guild-specific permissions are currently:Changed in version 1.7: Added
stream,priority_speakeranduse_application_commandspermissions.Changed in version 2.0: Added
create_public_threads,create_private_threads,manage_threads,use_external_stickers,send_messages_in_threads,request_to_speak, anduse_soundboardpermissions.
- classmethod general()¶
A factory method that creates a
Permissionswith all “General” permissions from the official Discord UI set toTrue.Changed in version 1.7: Permission
read_messagesis now included in the general permissions, but permissionsadministrator,create_instant_invite,kick_members,ban_members,change_nicknameandmanage_nicknamesare no longer part of the general permissions.
- classmethod membership()¶
A factory method that creates a
Permissionswith all “Membership” permissions from the official Discord UI set toTrue.New in version 1.7.
Changed in version 2.0: Added
moderate_memberspermission.
- classmethod text()¶
A factory method that creates a
Permissionswith all “Text” permissions from the official Discord UI set toTrue.Changed in version 1.7: Permission
read_messagesis no longer part of the text permissions. Addeduse_application_commandspermission.Changed in version 2.0: Added
create_public_threads,create_private_threads,manage_threads,send_messages_in_threadsanduse_external_stickerspermissions.
- classmethod voice()¶
A factory method that creates a
Permissionswith all “Voice” permissions from the official Discord UI set toTrue.
- classmethod stage()¶
A factory method that creates a
Permissionswith all “Stage Channel” permissions from the official Discord UI set toTrue.New in version 1.7.
- classmethod stage_moderator()¶
A factory method that creates a
Permissionswith all permissions for stage moderators set toTrue. These permissions are currently:New in version 1.7.
Changed in version 2.0: Added
manage_channelspermission and removedrequest_to_speakpermission.
- classmethod elevated()¶
A factory method that creates a
Permissionswith all permissions that require 2FA set toTrue. These permissions are currently:New in version 2.0.
- classmethod advanced()¶
A factory method that creates a
Permissionswith all “Advanced” permissions from the official Discord UI set toTrue.New in version 1.7.
- update(**kwargs)¶
Bulk updates this permission object.
Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored.
- Parameters
**kwargs – A list of key/value pairs to bulk update permissions with.
- administrator¶
Returns
Trueif a user is an administrator. This role overrides all other permissions.This also bypasses all channel-specific overrides.
- Type
- manage_channels¶
Returns
Trueif a user can edit, delete, or create channels in the guild.This also corresponds to the “Manage Channel” channel-specific override.
- Type
- read_messages¶
Returns
Trueif a user can read messages from all or specific text channels.- Type
- view_channel¶
An alias for
read_messages.New in version 1.3.
- Type
- send_messages¶
Returns
Trueif a user can send messages from all or specific text channels.- Type
- send_tts_messages¶
Returns
Trueif a user can send TTS messages from all or specific text channels.- Type
- manage_messages¶
Returns
Trueif a user can delete or pin messages in a text channel.Note
Note that there are currently no ways to edit other people’s messages.
- Type
- mention_everyone¶
Returns
Trueif a user’s @everyone or @here will mention everyone in the text channel.- Type
- use_external_emojis¶
An alias for
external_emojis.New in version 1.3.
- Type
- view_guild_insights¶
Returns
Trueif a user can view the guild’s insights.New in version 1.3.
- Type
- manage_roles¶
Returns
Trueif a user can create or edit roles less than their role’s position.This also corresponds to the “Manage Permissions” channel-specific override.
- Type
- manage_permissions¶
An alias for
manage_roles.New in version 1.3.
- Type
- manage_guild_expressions¶
Returns
Trueif a user can create, edit, or delete emojis, stickers, and soundboard sounds.New in version 2.0.
- Type
- manage_emojis¶
An alias for
manage_guild_expressions.- Type
- manage_emojis_and_stickers¶
An alias for
manage_guild_expressions.New in version 2.0.
- Type
- use_application_commands¶
Returns
Trueif a user can use slash commands.New in version 1.7.
- Type
- request_to_speak¶
Returns
Trueif a user can request to speak in a stage channel.New in version 1.7.
- Type
- create_public_threads¶
Returns
Trueif a user can create public threads.New in version 2.0.
- Type
- create_private_threads¶
Returns
Trueif a user can create private threads.New in version 2.0.
- Type
- external_stickers¶
Returns
Trueif a user can use stickers from other guilds.New in version 2.0.
- Type
- use_external_stickers¶
An alias for
external_stickers.New in version 2.0.
- Type
- send_messages_in_threads¶
Returns
Trueif a user can send messages in threads.New in version 2.0.
- Type
- use_embedded_activities¶
Returns
Trueif a user can launch an embedded application in a Voice channel.New in version 2.0.
- Type
- clsPermissionOverwrite.from_pair
- defis_empty
- defpair
- defupdate
- class discord.PermissionOverwrite¶
A type that is used to represent a channel specific permission.
Unlike a regular
Permissions, the default value of a permission is equivalent toNoneand notFalse. Setting a value toFalseis explicitly denying that permission, while setting a value toTrueis explicitly allowing that permission.The values supported by this are the same as
Permissionswith the added possibility of it being set toNone.- x == y
Checks if two overwrites are equal.
- x != y
Checks if two overwrites are not equal.
- iter(x)
Returns an iterator of
(perm, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
- Parameters
**kwargs – Set the value of permissions by their name.
- pair()¶
Tuple[
Permissions,Permissions]: Returns the (allow, deny) pair from this overwrite.
- classmethod from_pair(allow, deny)¶
Creates an overwrite from an allow/deny pair of
Permissions.
- is_empty()¶
Checks if the permission overwrite is currently empty.
An empty permission overwrite is one that has no overwrites set to
TrueorFalse.- Returns
Indicates if the overwrite is empty.
- Return type
- update(**kwargs)¶
Bulk updates this permission overwrite object.
Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored.
- Parameters
**kwargs – A list of key/value pairs to bulk update with.
ForumTag¶
- class discord.ForumTag(*, name, emoji=None, moderated=False)¶
Represents a forum tag that can be applied to a thread within a
ForumChannel.- x == y
Checks if two forum tags are equal.
- x != y
Checks if two forum tags are not equal.
- hash(x)
Returns the forum tag’s hash.
- str(x)
Returns the forum tag’s name.
New in version 2.0.
- moderated¶
Whether this tag can only be added or removed by a moderator with the
manage_threadspermission.- Type
- emoji¶
The emoji that is used to represent this tag. Note that if the emoji is a custom emoji, it will not have name information.
- Type
Optional[
PartialEmoji]
Flags¶
- active
- allow_activity_action_join_request
- allow_activity_action_spectate
- allow_assets
- application_command_badge
- embedded
- embedded_first_party
- embedded_iap
- embedded_released
- gateway_guild_members
- gateway_guild_members_limited
- gateway_message_content
- gateway_message_content_limited
- gateway_presence
- gateway_presence_limited
- group_dm_create
- managed_emoji
- rpc_has_connected
- rpc_private_beta
- value
- verification_pending_guild_limit
- class discord.ApplicationFlags¶
Wraps up the Discord Application flags.
- x == y
Checks if two ApplicationFlags are equal.
- x != y
Checks if two ApplicationFlags are not equal.
- x | y, x |= y
Returns an ApplicationFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns an ApplicationFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns an ApplicationFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns an ApplicationFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
- value¶
The raw value. You should query flags via the properties rather than using this raw value.
- Type
- managed_emoji¶
Returns
Trueif the application has the ability to create Twitch-style emotes.- Type
- embedded_iap¶
Returns
Trueif the application has the ability to use embedded in-app purchases.- Type
- rpc_private_beta¶
Returns
Trueif the application has the ability to access the client RPC server.- Type
- allow_activity_action_spectate¶
Returns
Trueif the application has the ability to enable spectating activities.- Type
- allow_activity_action_join_request¶
Returns
Trueif the application has the ability to enable activity join requests.- Type
- rpc_has_connected¶
Returns
Trueif the application has accessed the client RPC server before.- Type
- gateway_presence¶
Returns
Trueif the application is verified and is allowed to receive presence information over the gateway.- Type
- gateway_presence_limited¶
Returns
Trueif the application is allowed to receive presence information over the gateway.- Type
- gateway_guild_members¶
Returns
Trueif the application is verified and is allowed to receive full guild member lists.- Type
- gateway_guild_members_limited¶
Returns
Trueif the application is allowed to receive full guild member lists.- Type
- verification_pending_guild_limit¶
Returns
Trueif the application is currently pending verification and has hit the guild limit.- Type
- gateway_message_content¶
Returns
Trueif the application is verified and is allowed to receive message content.- Type
- gateway_message_content_limited¶
Returns
Trueif the application is allowed to read message content in guilds.- Type
- application_command_badge¶
Returns
Trueif the application has registered global application commands.- Type
- class discord.ApplicationDiscoveryFlags¶
Wraps up the Discord application discovery eligibility flags.
- x == y
Checks if two LibraryApplicationFlags are equal.
- x != y
Checks if two LibraryApplicationFlags are not equal.
- x | y, x |= y
Returns a LibraryApplicationFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a LibraryApplicationFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a LibraryApplicationFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a LibraryApplicationFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
- install_params¶
Returns
Trueif the application has a custom install URL or install parameters.- Type
- approved_commands¶
Returns
Trueif the application has the message content intent approved or utilizes application commands.- Type
- safe_directory_overview¶
Returns
Trueif the application’s directory long description is safe for work.- Type
- safe_short_description¶
Returns
Trueif the application’s directory short description is safe for work.- Type
- safe_role_connections¶
Returns
Trueif the application’s role connections metadata is safe for work.- Type
- class discord.LibraryApplicationFlags¶
Wraps up the Discord library application flags.
- x == y
Checks if two LibraryApplicationFlags are equal.
- x != y
Checks if two LibraryApplicationFlags are not equal.
- x | y, x |= y
Returns a LibraryApplicationFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a LibraryApplicationFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a LibraryApplicationFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a LibraryApplicationFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
Returns
Trueif the library application is hidden.- Type
- overlay_disabled¶
Returns
Trueif the library application has the Discord overlay disabled.- Type
Returns
Trueif the library application is free for premium users.- Type
- class discord.ChannelFlags¶
Wraps up the Discord
GuildChannelorThreadflags.- x == y
Checks if two ChannelFlags are equal.
- x | y, x |= y
Returns a ChannelFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a ChannelFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a ChannelFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a ChannelFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
- value¶
The raw value. You should query flags via the properties rather than using this raw value.
- Type
- require_tag¶
Returns
Trueif a tag is required to be specified when creating a thread in aForumChannel.- Type
- class discord.SystemChannelFlags¶
Wraps up a Discord system channel flag value.
Similar to
Permissions, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit the system flags easily.To construct an object you can pass keyword arguments denoting the flags to enable or disable.
- x == y
Checks if two SystemChannelFlags are equal.
- x != y
Checks if two SystemChannelFlags are not equal.
- x | y, x |= y
Returns a SystemChannelFlags instance with all enabled flags from both x and y.
New in version 2.0.
- x & y, x &= y
Returns a SystemChannelFlags instance with only flags enabled on both x and y.
New in version 2.0.
- x ^ y, x ^= y
Returns a SystemChannelFlags instance with only flags enabled on only one of x or y, not on both.
New in version 2.0.
- ~x
Returns a SystemChannelFlags instance with all flags inverted from x.
New in version 2.0.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
- join_notifications¶
Returns
Trueif the system channel is used for member join notifications.- Type
Returns
Trueif the system channel is used for “Nitro boosting” notifications.- Type
- guild_reminder_notifications¶
Returns
Trueif the system channel is used for server setup helpful tips notifications.New in version 2.0.
- Type
- join_notification_replies¶
Returns
Trueif sticker reply button (“Wave to say hi!”) is shown for member join notifications.New in version 2.0.
- Type
- role_subscription_purchase_notifications¶
Returns
Trueif role subscription purchase and renewal notifications are enabled.New in version 2.0.
- Type
- class discord.FriendSourceFlags¶
Wraps up the Discord friend source flags.
These are used in user settings to control who can add you as a friend.
- x == y
Checks if two FriendSourceFlags are equal.
- x != y
Checks if two FriendSourceFlags are not equal.
- x | y, x |= y
Returns a FriendSourceFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a FriendSourceFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a FriendSourceFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a FriendSourceFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
- classmethod none()¶
A factory method that creates a
FriendSourceFlagsthat allows no friend request.
- classmethod all()¶
A factory method that creates a
FriendSourceFlagsthat allows any friend requests.
- mutual_friends¶
Returns
Trueif a user can add you as a friend if you have mutual friends.- Type
- mutual_guilds¶
Returns
Trueif a user can add you as a friend if you are in the same guild.- Type
- class discord.FriendDiscoveryFlags¶
Wraps up the Discord friend discovery flags.
These are used in user settings to control how you get recommended friends.
- x == y
Checks if two FriendDiscoveryFlags are equal.
- x != y
Checks if two FriendDiscoveryFlags are not equal.
- x | y, x |= y
Returns a FriendDiscoveryFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a FriendDiscoveryFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a FriendDiscoveryFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a FriendDiscoveryFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
- classmethod none()¶
A factory method that creates a
FriendDiscoveryFlagsthat allows no friend discovery.
- classmethod all()¶
A factory method that creates a
FriendDiscoveryFlagsthat allows all friend discovery.
- find_by_phone¶
Returns
Trueif a user can add you as a friend if they have your phone number.- Type
- class discord.GiftFlags¶
Wraps up the Discord payment flags.
- x == y
Checks if two GiftFlags are equal.
- x != y
Checks if two GiftFlags are not equal.
- x | y, x |= y
Returns a GiftFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a GiftFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a GiftFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a GiftFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
- existing_subscription_disallowed¶
Returns
Trueif the gift cannot be redeemed by users with existing premium subscriptions.- Type
- class discord.HubProgressFlags¶
Wraps up the Discord hub progress flags.
These are used in user settings, specifically guild progress, to track engagement and feature usage in hubs.
- x == y
Checks if two HubProgressFlags are equal.
- x != y
Checks if two HubProgressFlags are not equal.
- x | y, x |= y
Returns a HubProgressFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a HubProgressFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a HubProgressFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a HubProgressFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
- class discord.MemberFlags¶
Wraps up the Discord Guild Member flags
New in version 2.0.
- x == y
Checks if two MemberFlags are equal.
- x != y
Checks if two MemberFlags are not equal.
- x | y, x |= y
Returns a MemberFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a MemberFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a MemberFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a MemberFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
- value¶
The raw value. You should query flags via the properties rather than using this raw value.
- Type
- bypasses_verification¶
Returns
Trueif the member can bypass the guild verification requirements.- Type
- class discord.MessageFlags¶
Wraps up a Discord Message flag value.
See
SystemChannelFlags.- x == y
Checks if two MessageFlags are equal.
- x != y
Checks if two MessageFlags are not equal.
- x | y, x |= y
Returns a MessageFlags instance with all enabled flags from both x and y.
New in version 2.0.
- x & y, x &= y
Returns a MessageFlags instance with only flags enabled on both x and y.
New in version 2.0.
- x ^ y, x ^= y
Returns a MessageFlags instance with only flags enabled on only one of x or y, not on both.
New in version 2.0.
- ~x
Returns a MessageFlags instance with all flags inverted from x.
New in version 2.0.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs.
New in version 1.3.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
- source_message_deleted¶
Returns
Trueif the source message for this crosspost has been deleted.- Type
- urgent¶
Returns
Trueif the message is an urgent message.An urgent message is one sent by Discord Trust and Safety.
- Type
- loading¶
Returns
Trueif the message is an interaction response and the bot is “thinking”.New in version 2.0.
- Type
- failed_to_mention_some_roles_in_thread¶
Returns
Trueif the message failed to mention some roles in a thread and add their members to the thread.New in version 2.0.
- Type
- link_not_discord_warning¶
Returns
Trueif this message contains a link that impersonates Discord and should show a warning.New in version 2.0.
- Type
- suppress_notifications¶
Returns
Trueif the message will not trigger push and desktop notifications.New in version 2.0.
- Type
- silent¶
Alias for
suppress_notifications.New in version 2.0.
- Type
- class discord.OnboardingProgressFlags¶
Wraps up the Discord guild onboarding progress flags.
These are used in user settings, specifically guild progress, to track engagement and feature usage in guild onboarding.
- x == y
Checks if two OnboardingProgressFlags are equal.
- x != y
Checks if two OnboardingProgressFlags are not equal.
- x | y, x |= y
Returns a OnboardingProgressFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a OnboardingProgressFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a OnboardingProgressFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a OnboardingProgressFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
- class discord.PaymentFlags¶
Wraps up the Discord payment flags.
- x == y
Checks if two PaymentFlags are equal.
- x != y
Checks if two PaymentFlags are not equal.
- x | y, x |= y
Returns a PaymentFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a PaymentFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a PaymentFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a PaymentFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
- class discord.PaymentSourceFlags¶
Wraps up the Discord payment source flags.
- x == y
Checks if two PaymentSourceFlags are equal.
- x != y
Checks if two PaymentSourceFlags are not equal.
- x | y, x |= y
Returns a PaymentSourceFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a PaymentSourceFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a PaymentSourceFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a PaymentSourceFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
- active_developer
- bot_http_interactions
- bug_hunter
- bug_hunter_level_1
- bug_hunter_level_2
- disable_premium
- discord_certified_moderator
- early_supporter
- early_verified_bot_developer
- has_unread_urgent_messages
- hypesquad
- hypesquad_balance
- hypesquad_bravery
- hypesquad_brilliance
- mfa_sms
- partner
- partner_or_verification_application
- premium_promo_dismissed
- quarantined
- spammer
- staff
- system
- team_user
- underage_deleted
- value
- verified_bot
- verified_bot_developer
- defall
- class discord.PrivateUserFlags¶
Wraps up the Discord User flags.
- x == y
Checks if two PrivateUserFlags are equal.
- x != y
Checks if two PrivateUserFlags are not equal.
- x | y, x |= y
Returns a PrivateUserFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a PrivateUserFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a PrivateUserFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a PrivateUserFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases or inherited flags are not shown.
New in version 2.0.
Note
These are only available on your own user flags.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
Returns
Trueif the user has dismissed the current premium promotion.- Type
- underage_deleted¶
Returns
Trueif the user has been flagged for deletion for being underage.- Type
- partner_or_verification_application¶
Returns
Trueif the user has a partner or a verification application.- Type
Returns
Trueif the user bought premium but has it manually disabled.- Type
- bot_http_interactions¶
Returns
Trueif the user is a bot that only uses HTTP interactions and is shown in the online member list.New in version 2.0.
- Type
- bug_hunter_level_1¶
An alias for
bug_hunter.New in version 2.0.
- Type
- discord_certified_moderator¶
Returns
Trueif the user is a Discord Certified Moderator.New in version 2.0.
- Type
- early_verified_bot_developer¶
An alias for
verified_bot_developer.New in version 1.5.
- Type
- active_developer
- bot_http_interactions
- bug_hunter
- bug_hunter_level_1
- bug_hunter_level_2
- discord_certified_moderator
- early_supporter
- early_verified_bot_developer
- hypesquad
- hypesquad_balance
- hypesquad_bravery
- hypesquad_brilliance
- partner
- spammer
- staff
- system
- team_user
- value
- verified_bot
- verified_bot_developer
- defall
- class discord.PublicUserFlags¶
Wraps up the Discord User Public flags.
- x == y
Checks if two PublicUserFlags are equal.
- x != y
Checks if two PublicUserFlags are not equal.
- x | y, x |= y
Returns a PublicUserFlags instance with all enabled flags from both x and y.
New in version 2.0.
- x & y, x &= y
Returns a PublicUserFlags instance with only flags enabled on both x and y.
New in version 2.0.
- x ^ y, x ^= y
Returns a PublicUserFlags instance with only flags enabled on only one of x or y, not on both.
New in version 2.0.
- ~x
Returns a PublicUserFlags instance with all flags inverted from x.
New in version 2.0.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 1.4.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
- bug_hunter_level_1¶
An alias for
bug_hunter.New in version 2.0.
- Type
- early_verified_bot_developer¶
An alias for
verified_bot_developer.New in version 1.5.
- Type
- discord_certified_moderator¶
Returns
Trueif the user is a Discord Certified Moderator.New in version 2.0.
- Type
- bot_http_interactions¶
Returns
Trueif the user is a bot that only uses HTTP interactions and is shown in the online member list.New in version 2.0.
- Type
- class discord.PremiumUsageFlags¶
Wraps up the Discord premium usage flags.
- x == y
Checks if two PremiumUsageFlags are equal.
- x != y
Checks if two PremiumUsageFlags are not equal.
- x | y, x |= y
Returns a PremiumUsageFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a PremiumUsageFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a PremiumUsageFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a PremiumUsageFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
Returns
Trueif the user has utilized premium discriminators.- Type
- class discord.PurchasedFlags¶
Wraps up the Discord purchased flags.
- x == y
Checks if two PurchasedFlags are equal.
- x != y
Checks if two PurchasedFlags are not equal.
- x | y, x |= y
Returns a PurchasedFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a PurchasedFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a PurchasedFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a PurchasedFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
- class discord.PromotionFlags¶
Wraps up the Discord promotion flags.
- x == y
Checks if two PromotionFlags are equal.
- x != y
Checks if two PromotionFlags are not equal.
- x | y, x |= y
Returns a PromotionFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a PromotionFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a PromotionFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a PromotionFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
- class discord.SKUFlags¶
Wraps up the Discord SKU flags.
- x == y
Checks if two SKUFlags are equal.
- x != y
Checks if two SKUFlags are not equal.
- x | y, x |= y
Returns a SKUFlags instance with all enabled flags from both x and y.
- x & y, x &= y
Returns a SKUFlags instance with only flags enabled on both x and y.
- x ^ y, x ^= y
Returns a SKUFlags instance with only flags enabled on only one of x or y, not on both.
- ~x
Returns a SKUFlags instance with all flags inverted from x.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
- value¶
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type
Returns
Trueif the SKU is a premium purchase.- Type
Returns
Trueif the SKU is free premium content.- Type
Returns
Trueif the SKU is a premium or distribution product.- Type
- guild_role_subscription¶
Returns
Trueif the SKU is a guild role subscription. These are subscriptions made to guilds for premium perks.- Type
Returns
Trueif the SKU is a Discord premium subscription or related first-party product. These are subscriptions like Nitro and Server Boosts. These are the only giftable subscriptions.- Type
- application_guild_subscription¶
Returns
Trueif the SKU is a application subscription. These are subscriptions made to applications for premium perks bound to a guild.- Type
- class discord.MemberCacheFlags¶
Controls the library’s cache policy when it comes to members.
This allows for finer grained control over what members are cached. Note that the bot’s own member is always cached. This class is passed to the
member_cache_flagsparameter inClient.To construct an object you can pass keyword arguments denoting the flags to enable or disable.
The default value is all flags enabled.
New in version 1.5.
- x == y
Checks if two flags are equal.
- x != y
Checks if two flags are not equal.
- x | y, x |= y
Returns a MemberCacheFlags instance with all enabled flags from both x and y.
New in version 2.0.
- x & y, x &= y
Returns a MemberCacheFlags instance with only flags enabled on both x and y.
New in version 2.0.
- x ^ y, x ^= y
Returns a MemberCacheFlags instance with only flags enabled on only one of x or y, not on both.
New in version 2.0.
- ~x
Returns a MemberCacheFlags instance with all flags inverted from x.
New in version 2.0.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs.
- value¶
The raw value. You should query flags via the properties rather than using this raw value.
- Type
- classmethod all()¶
A factory method that creates a
MemberCacheFlagswith everything enabled.
- classmethod none()¶
A factory method that creates a
MemberCacheFlagswith everything disabled.
- voice¶
Whether to cache members that are in voice.
Members that leave voice are no longer cached.
- Type
- other¶
Whether to cache members that are collected from other means.
This does not apply to members explicitly cached (e.g.
Guild.chunk,Guild.fetch_members).There is an alias for this called
joined.- Type
- joined¶
Whether to cache members that are collected from other means.
This does not apply to members explicitly cached (e.g.
Guild.chunk,Guild.fetch_members).This is an alias for
other.- Type
Exceptions¶
The following exceptions are thrown by the library.
- exception discord.DiscordException¶
Base exception class for discord.py
Ideally speaking, this could be caught to handle any exceptions raised from this library.
- exception discord.ClientException¶
Exception that’s raised when an operation in the
Clientfails.These are usually for exceptions that happened due to user input.
- exception discord.LoginFailure¶
Exception that’s raised when the
Client.login()function fails to log you in from improper credentials or some other misc. failure.
- exception discord.HTTPException(response, message)¶
Exception that’s raised when an HTTP request operation fails.
- response¶
The response of the failed HTTP request. This is an instance of
aiohttp.ClientResponse. In some cases this could also be arequests.Response.
- exception discord.RateLimited(retry_after)¶
Exception that’s raised for when status code 429 occurs and the timeout is greater than the configured maximum using the
max_ratelimit_timeoutparameter inClient.This is not raised during global ratelimits.
Since sometimes requests are halted pre-emptively before they’re even made, this does not subclass
HTTPException.New in version 2.0.
- exception discord.Forbidden(response, message)¶
Exception that’s raised for when status code 403 occurs.
Subclass of
HTTPException
- exception discord.NotFound(response, message)¶
Exception that’s raised for when status code 404 occurs.
Subclass of
HTTPException
- exception discord.CaptchaRequired(response, message)¶
Exception that’s raised when a captcha is required and isn’t handled.
Subclass of
HTTPException.New in version 2.0.
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception discord.DiscordServerError(response, message)¶
Exception that’s raised for when a 500 range status code occurs.
Subclass of
HTTPException.New in version 1.5.
- exception discord.InvalidData¶
Exception that’s raised when the library encounters unknown or invalid data from Discord.
- exception discord.GatewayNotFound¶
An exception that is raised when the gateway for Discord could not be found
- exception discord.ConnectionClosed(socket, *, code=None)¶
Exception that’s raised when the gateway connection is closed for reasons that could not be handled internally.
- exception discord.opus.OpusError(code)¶
An exception that is thrown for libopus related errors.
- exception discord.opus.OpusNotLoaded¶
An exception that is thrown for when libopus is not loaded.