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.
ClientUser
- defavatar_decoration_url_as
- defavatar_url_as
- defbanner_url_as
- asyncedit
- defis_avatar_animated
- defis_banner_animated
- defmentioned_in
- defpermissions_in
- class discord.ClientUser
Bases:
BaseUser
Represents your Discord user.
Changed in version 2.0: The
name
attribute was renamed tousername
due to the (upcoming) username changes.- 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
username
ifis_migrated
is true, else the user’s name with discriminator.Note
When the migration is complete, this will always return the
username
.
- global_name
The user’s global name if set. In the client UI, this is referred to as “Display Name”.
New in version 2.0.
- Type:
Optional[
str
]
- avatar
The avatar hash the user has. Could be
None
.- Type:
Optional[
str
]
- locale
The IETF language tag used to identify the language the user is using.
- Type:
Optional[
str
]
- await edit(username=MISSING, global_name=MISSING, avatar=MISSING)
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()
.The only image formats supported for uploading is JPEG and PNG.
- Parameters:
username (
str
) – The new username you wish to change to.global_name (
str
) – The new global name you wish to change to.avatar (
bytes
) – A bytes-like object representing the image to upload. Could beNone
to denote no avatar.
- Raises:
HTTPException – Editing your profile failed.
InvalidArgument – Wrong image format passed for
avatar
.
- property accent_color
A colour object that represents the user’s banner colour.
Note
This information is only available via
Client.fetch_user()
.- Type:
Optional[
Colour
]
- property accent_colour
An alias for
accent_color
.- Type:
Optional[
Colour
]
- avatar_decoration_url_as(*, format=None, size=1024)
Returns an
Asset
for the avatar decoration the user has. Could beNone
.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
, or invalidsize
.- Returns:
The resulting CDN asset if any.
- Return type:
Optional[
Asset
]
- property avatar_url
Returns an
Asset
for the avatar the user has.If the user does not have a traditional avatar, an asset for the default avatar is returned instead.
This is equivalent to calling
avatar_url_as()
with the default parameters (i.e. webp/gif detection and a size of 1024).- Type:
- avatar_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the avatar the user has.If the user does not have a traditional avatar, an asset for the default avatar is returned instead.
The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the avatar to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the avatar being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
, or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- property banner_color
A colour object that represents the user’s banner colour.
Note
This information is only available via
Client.fetch_user()
.- Type:
Optional[
Colour
]
- property banner_colour
A colour object that represents the user’s banner colour.
Note
This information is only available via
Client.fetch_user()
.- Type:
Optional[
Colour
]
- property banner_url
Returns an asset for the banner the user has, if any. This is equal to calling
banner_url_as()
with the default arguments.
- banner_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the banner the user has. Could beNone
.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated banners. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the banner to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the banner being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated banner to. Defaults to ‘webp’size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
, or invalidsize
.- Returns:
The resulting CDN asset if any.
- Return 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. For non-migrated users this is calculated by the user’s discriminator. For migrated users this is calculated by the user’s ID.
- Type:
- property display_avatar
Returns the users display avatar.
For regular users this is equal to
avatar_url
.- Type:
- property display_name
Returns the user’s display name.
For regular users this is just their
global_name
if set else theirusername
, but if they have a guild specific nickname then that is returned instead.- Type:
- property hex_banner_color
Returns a hexadecimal representation of the user’s banner colour, if available.
- Type:
Optional[
str
]
- is_avatar_animated()
bool
: Indicates if the user has an animated avatar.
- is_banner_animated()
bool
: Indicates if the user has an animated banner.
- property is_migrated
Indicates if the user has migrated to the new username system.
- Type:
- property name
This is an alias of
username
which replaces the previous name attribute.Note
It is recommended to use
username
instead as this might be removed in the future.- Type:
- permissions_in(channel)
An alias for
abc.GuildChannel.permissions_for()
.Basically equivalent to:
channel.permissions_for(self)
- Parameters:
channel (
abc.GuildChannel
) – The channel to check your permissions for.
User
- accent_color
- accent_colour
- avatar
- avatar_decoration
- avatar_url
- banner
- banner_color
- banner_colour
- banner_url
- bot
- color
- colour
- created_at
- default_avatar
- default_avatar_url
- discriminator
- display_avatar
- display_name
- dm_channel
- global_name
- hex_banner_color
- id
- is_migrated
- mention
- mutual_guilds
- name
- public_flags
- system
- username
- defavatar_decoration_url_as
- defavatar_url_as
- defbanner_url_as
- asynccreate_dm
- asyncfetch_message
- defhistory
- defis_avatar_animated
- defis_banner_animated
- defmentioned_in
- defpermissions_in
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
- class discord.User
Bases:
BaseUser
,Messageable
Represents a Discord user.
Changed in version 2.0: The
name
attribute was renamed tousername
due to the (upcoming) username changes.- 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
username
ifis_migrated
is true, else the user’s name with discriminator.Note
When the migration is complete, this will always return the
username
.
- global_name
The user’s global name if set. In the client UI, this is referred to as “Display Name”.
New in version 2.0.
- Type:
Optional[
str
]
- discriminator
The user’s discriminator.
Deprecated since version 2.0.
Important
This will be removed in the future. Read more about it here.
- Type:
- avatar
The avatar hash the user has. Could be None.
- Type:
Optional[
str
]
- banner
The banner hash the user has. Could be None.
Note
This is only available via
Client.fetch_user()
.New in version 2.0.
- Type:
Optional[
str
]
- avatar_decoration
The avatar decoration hash the user has. Could be None.
New in version 2.0.
- Type:
Optional[
str
]
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
Returns an
AsyncIterator
that enables receiving the destination’s message history.You must have
read_message_history
permissions to use 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 = await channel.history(limit=123).flatten() # 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 date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC 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 toTrue
ifafter
is 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.
- async with typing()
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
Note
This is both a regular context manager and an async context manager. This means that both
with
andasync with
work with this.Example Usage:
async with channel.typing(): # do expensive stuff here await asyncio.sleep(15) await channel.send('done!')
- 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 mutual_guilds
The guilds that the user shares with the client.
Note
This will only return mutual guilds within the client’s internal cache.
New in version 1.7.
- Type:
List[
Guild
]
- property accent_color
A colour object that represents the user’s banner colour.
Note
This information is only available via
Client.fetch_user()
.- Type:
Optional[
Colour
]
- property accent_colour
An alias for
accent_color
.- Type:
Optional[
Colour
]
- avatar_decoration_url_as(*, format=None, size=1024)
Returns an
Asset
for the avatar decoration the user has. Could beNone
.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
, or invalidsize
.- Returns:
The resulting CDN asset if any.
- Return type:
Optional[
Asset
]
- property avatar_url
Returns an
Asset
for the avatar the user has.If the user does not have a traditional avatar, an asset for the default avatar is returned instead.
This is equivalent to calling
avatar_url_as()
with the default parameters (i.e. webp/gif detection and a size of 1024).- Type:
- avatar_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the avatar the user has.If the user does not have a traditional avatar, an asset for the default avatar is returned instead.
The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the avatar to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the avatar being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
, or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- property banner_color
A colour object that represents the user’s banner colour.
Note
This information is only available via
Client.fetch_user()
.- Type:
Optional[
Colour
]
- property banner_colour
A colour object that represents the user’s banner colour.
Note
This information is only available via
Client.fetch_user()
.- Type:
Optional[
Colour
]
- property banner_url
Returns an asset for the banner the user has, if any. This is equal to calling
banner_url_as()
with the default arguments.
- banner_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the banner the user has. Could beNone
.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated banners. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the banner to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the banner being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated banner to. Defaults to ‘webp’size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
, or invalidsize
.- Returns:
The resulting CDN asset if any.
- Return 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:
- await create_dm()
This function is a coroutine.
Creates a
DMChannel
with 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. For non-migrated users this is calculated by the user’s discriminator. For migrated users this is calculated by the user’s ID.
- Type:
- property display_avatar
Returns the users display avatar.
For regular users this is equal to
avatar_url
.- Type:
- property display_name
Returns the user’s display name.
For regular users this is just their
global_name
if set else theirusername
, 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
Message
from the destination.This can only be used by bot accounts.
- 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 hex_banner_color
Returns a hexadecimal representation of the user’s banner colour, if available.
- Type:
Optional[
str
]
- is_avatar_animated()
bool
: Indicates if the user has an animated avatar.
- is_banner_animated()
bool
: Indicates if the user has an animated banner.
- property is_migrated
Indicates if the user has migrated to the new username system.
- Type:
- property name
This is an alias of
username
which replaces the previous name attribute.Note
It is recommended to use
username
instead as this might be removed in the future.- Type:
- permissions_in(channel)
An alias for
abc.GuildChannel.permissions_for()
.Basically equivalent to:
channel.permissions_for(self)
- Parameters:
channel (
abc.GuildChannel
) – The channel to check your permissions for.
- 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
Message
objects returned by this method do not contain completeMessage.reactions
data.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message
]
- await send(content=None, *, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, suppress_notifications=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 theembed
parameter must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type.- Parameters:
content (
str
) – The content of the message to send.tts (
bool
) – Indicates if the message should be sent using text-to-speech.embed (
Embed
) – The rich embed for the content.embeds (List[
Embed
]) – A list containing up to ten embedscomponents (List[Union[
ActionRow
, List[Union[Button
, Select]]]]) – A list of up to fiveActionRow`s or :class:`list
, each containing up to fiveButton
or one Select like object.file (
File
) – The file to upload.files (List[
File
]) – Alist
of files to upload. Must be a maximum of 10.stickers (List[
GuildSticker
]) – A list of up to 3discord.GuildSticker
that should be sent with the message.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.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_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
]) –A reference to the
Message
to 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_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
suppress_embeds (
bool
) – Whether to supress embeds send with the message, default toFalse
suppress_notifications (
bool
) –Whether to suppress desktop- & push-notifications for this message, default to
False
Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.
New in version 2.0.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
files
list is not of the appropriate size, you specified bothfile
andfiles
, or thereference
object is not aMessage
orMessageReference
.
- Returns:
The message that was sent.
- Return type:
- await trigger_typing()
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
Attachment
- defis_spoiler
- asyncread
- asyncsave
- defto_dict
- asyncto_file
- class discord.Attachment
Bases:
Hashable
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 cast to
str
and is hashable.Changed in version 2.0: The
ephemeral
,description
,duration
andwaveform
attributes were added.- height
The attachment’s height, in pixels. Only applicable to images and videos.
- Type:
Optional[
int
]
- width
The attachment’s width, 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
url
in 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
- Type:
Optional[
str
]
- ephemeral
Whether the attachment is ephemeral (part of an ephemeral message or was provided in a slash-command option).
- Type:
- description
The description for the file.
- Type:
Optional[
str
]
- duration
The duration of the audio file (currently only for voice messages).
- Type:
Optional[
float
]
- is_spoiler()
bool
: Whether this attachment contains a spoiler.
- property waveform
The waveform of the audio file (currently only for voice messages).
- Type:
Optional[List[:class:`int
]]`
- to_dict()
dict
: A minimal dictionary containing the filename and description of the attachment.
- 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_url
rather thanurl
when 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
bytes
object.New in version 1.1.
- Parameters:
use_cached (
bool
) – Whether to useproxy_url
rather thanurl
when 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(*, use_cached=False, spoiler=False, description=MISSING)
This function is a coroutine.
Converts the attachment into a
File
suitable for sending viaabc.Messageable.send()
.New in version 1.3.
- Parameters:
use_cached (
bool
) –Whether to use
proxy_url
rather thanurl
when 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.
description (
bool
) –The description (alt text) for the file.
This will be default to the
description
. Set the value toNone
to supress this. .. versionadded:: 2.0
- 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:
Asset
- class discord.Asset
Bases:
object
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.
- bool(x)
Checks if the Asset has a 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.
- await read()
This function is a coroutine.
Retrieves the content of this asset as a
bytes
object.Warning
PartialEmoji
won’t have a connection state if user created, and a URL won’t be present if a custom image isn’t associated with the asset, e.g. a guild with no custom icon.New in version 1.1.
- Raises:
DiscordException – There was no valid URL or 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[BinaryIO,
os.PathLike
]) – Same as inAttachment.save()
.seek_begin (
bool
) – Same as inAttachment.save()
.
- Raises:
DiscordException – There was no valid URL or internal connection state.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns:
The number of bytes written.
- Return type:
Message
- activity
- all_buttons
- all_components
- all_select_menus
- application
- attachments
- author
- 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
- thread
- tts
- type
- webhook_id
- asyncadd_reaction
- asyncclear_reaction
- asyncclear_reactions
- asynccreate_thread
- asyncdelete
- asyncedit
- defis_system
- asyncpin
- asyncpublish
- asyncremove_reaction
- asyncreply
- defto_reference
- asyncunpin
- class discord.Message
Bases:
Hashable
,Generic
[_MCH
]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
Member
that sent the message. Ifchannel
is a private channel or the user has left the guild, then it is aUser
instead.- Type:
- nonce
The value used by the discord guild and the client to verify that the message is successfully sent. This is not stored long term within Discord’s servers and is only used ephemerally.
- embeds
A list of embeds the message has.
- Type:
List[
Embed
]
- components
A list of components the message has.
- Type:
List[
ActionRow
]:
- channel
The
TextChannel
,ThreadChannel
orVoiceChannel
that the message was sent from. Could be aDMChannel
orGroupChannel
if it’s a private message.- Type:
Union[
abc.Messageable
,ThreadChannel
]
- 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
@everyone
or the@here
text is in the message itself. Rather this boolean indicates if either the@everyone
or the@here
text is in the message and it did end up mentioning.- Type:
- mentions
A list of
Member
that were mentioned. If the message is in a private message then the list will be ofUser
instead. 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.GuildChannel
that were mentioned. If the message is in a private message then the list is always empty.- Type:
List[
abc.GuildChannel
]
- role_mentions
A list of
Role
that 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
]
- 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.
It is a dictionary with the following keys:
id
: A string representing the application’s ID.name
: A string representing the application’s name.description
: A string representing the application’s description.icon
: A string representing the icon ID of the application.cover_image
: A string representing the embed’s image asset ID.
- Type:
Optional[
dict
]
- stickers
A list of stickers given to the message.
New in version 1.6.
- Type:
List[
Sticker
]
- interaction
The interaction this message is a response to, if any.
New in version 2.0.
- Type:
Optional[
MessageInteraction
]
- role_subscription
The data of the role subscription purchase or renewal that prompted this
MessageType.role_subscription_purchase
message.New in version 2.0.
- Type:
Optional[
RoleSubscriptionInfo
]
- 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
]
- guild
The guild that the message belongs to if any.
- Type:
Optional[
Guild
]
- 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_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_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 edited_at
A naive UTC datetime object containing the edited time of the message.
- Type:
Optional[
datetime.datetime
]
- is_system()
bool
: Whether the message is a system message.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.default
, this just returns the regularMessage.content
. Otherwise, this returns an English message denoting the contents of the system message.- Type:
- property all_components
Returns all
Button
’s and Select like objects that are contained in the message
- property all_buttons
Returns all
Button
’s that are contained in the message
Returns all Select like objects that are contained in the message
- property thread
The thread that belongs to this message, if there is one
- Type:
Optional[
ThreadChannel
]
- await delete(*, delay=None, reason=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 need the
manage_messages
permission.Changed in version 1.1: Added the new
delay
keyword-only parameter.- Parameters:
- 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=MISSING, embed=MISSING, embeds=MISSING, components=MISSING, attachments=MISSING, keep_existing_attachments=False, delete_after=None, allowed_mentions=MISSING, suppress_embeds=MISSING)
This function is a coroutine.
Edits the message.
The content must be able to be transformed into a string via
str(content)
.Warning
Since API v10, the
attachments
must contain all attachments that should be present after edit, including retained and new attachments.Changed in version 1.3: The
suppress
keyword-only parameter was added.Changed in version 2.0: The
suppress
keyword-only parameter was renamed tosuppress_embeds
.Changed in version 2.0: The
components`, ``attachments
andkeep_existing_attachments
keyword-only parameters were added.- Parameters:
content (Optional[
str
]) – The new content to replace the message with. Could beNone
to remove the content.embed (Optional[
Embed
]) – The new embed to replace the original with. Could beNone
to remove all embeds.embeds (Optional[List[
Embed
]]) –A list containing up to 10 embeds to send. If
None
or empty, all embeds will be removed.If passed,
embed
does also count towards the limit of 10 embeds.components (List[Union[
ActionRow
, List[Union[Button
, Select]]]]) – A list of up to fiveActionRow`s or :class:`list
, each containing up to fiveButton
or one Select like object.attachments (List[Union[
Attachment
,File
]]) –A list containing previous attachments to keep as well as new files to upload. You can use
keep_existing_attachments
to auto-add the existing attachments to the list. IfNone
or empty, all attachments will be removed.Note
New files will always appear under existing ones.
keep_existing_attachments (
bool
) –Whether to auto-add existing attachments to
attachments
, defaults toFalse
.Note
Only needed when
attachments
are passed, otherwise will be ignored.suppress_embeds (
bool
) – Whether to suppress embeds for the message. This removes all the embeds if set toTrue
. If set toFalse
this brings the embeds back if they were suppressed. Requiresmanage_messages
permissions for messages that aren’t from the bot.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_mentions
are 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.
- await publish()
This function is a coroutine.
Publishes this message to your announcement channel.
If the message is not your own then the
manage_messages
permission is needed.- Raises:
Forbidden – You do not have the proper permissions to publish this message.
HTTPException – Publishing the message failed.
- await pin(*, suppress_system_message=False, reason=None)
This function is a coroutine.
Pins the message.
You must have the
manage_messages
permission to do this in a non-private channel context.- Parameters:
- 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.
TimeoutError – Waiting for the system message timed out.
- await unpin(*, reason=None)
This function is a coroutine.
Unpins the message.
You must have the
manage_messages
permission to 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.
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild
Emoji
.You must have the
read_message_history
permission to use this. If nobody else has reacted to the message using this emoji, theadd_reactions
permission is required.- 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.
InvalidArgument – 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.
member
parameter is not you) then themanage_messages
permission is needed.The
member
parameter must represent a member and meet theabc.Snowflake
abc.- 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.
InvalidArgument – 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 need the
manage_messages
permission to use this.New in version 1.3.
- 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.
InvalidArgument – The emoji parameter is invalid.
- await clear_reactions()
This function is a coroutine.
Removes all the reactions from the message.
You need the
manage_messages
permission to use this.- Raises:
HTTPException – Removing the reactions failed.
Forbidden – You do not have the proper permissions to remove all the reactions.
- await reply(content=None, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)
This function is a coroutine.
A shortcut method to
abc.Messageable.send()
to reply to theMessage
.New in version 1.6.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
files
list is not of the appropriate size or you specified bothfile
andfiles
.
- Returns:
The message that was sent.
- Return type:
- await create_thread(name, auto_archive_duration=None, slowmode_delay=0, reason=None)
This function is a coroutine.
Creates a new thread in the channel of the message with this message as the
starter_message
.- Parameters:
name (
str
) – The name of the thread.auto_archive_duration (Optional[
AutoArchiveDuration
]) – Amount of time after that the thread will auto-hide from the channel listslowmode_delay (
int
) – Amount of seconds a user has to wait before sending another message (0-21600)reason (Optional[
str
]) – The reason for creating the thread. Shows up in the audit log.
- Raises:
TypeError – The channel of the message is not a text or news channel, or the message has already a thread, or
auto_archive_duration
is not a valid member ofAutoArchiveDuration
ValueError – The
name
is of invalid lengthForbidden – The bot is missing permissions to create threads in this channel
HTTPException – Creating the thread failed
- Returns:
The created thread on success
- Return type:
- to_reference(*, fail_if_not_exists=True)
Creates a
MessageReference
from the current message.New in version 1.6.
- Parameters:
fail_if_not_exists (
bool
) –Whether replying using the message reference should raise
HTTPException
if 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:
EphemeralMessage
- class discord.EphemeralMessage
Bases:
object
Like a normal
Message
but with a modifiededit()
method and withoutdelete()
method.- guild
The guild that the message belongs to, if applicable.
- Type:
Optional[
Guild
]
- property all_components
Union[
Button
, Select]: Yields all buttons and selects that are contained in the message
- property all_buttons
Returns all
Button
’s that are contained in the message
Returns all Select’s that are contained in the message
- await edit(*, content=MISSING, embed=MISSING, embeds=MISSING, components=MISSING, attachments=MISSING, keep_existing_attachments=False, allowed_mentions=MISSING, suppress_embeds=False, delete_after=None)
This function is a coroutine.
Edits the message.
- Parameters:
content (Optional[
str
]) – The new content to replace the message with. Could beNone
to remove the content.embed (Optional[
Embed
]) – The new embed to replace the original with. Could beNone
to remove all embeds.embeds (Optional[List[
Embed
]]) –A list containing up to 10 embeds to send. If
None
or empty, all embeds will be removed.If passed,
embed
does also count towards the limit of 10 embeds.components (List[Union[
ActionRow
, List[Union[Button
, Select]]]]) – A list of up to fiveActionRow`s or :class:`list
, each containing up to fiveButton
or one Select like object.attachments (List[Union[
Attachment
,File
]]) –A list containing previous attachments to keep as well as new files to upload. You can use
keep_existing_attachments
to auto-add the existing attachments to the list. If an empty list ([]
) is passed, all attachment will be removed.Note
New files will always appear under existing ones.
keep_existing_attachments (
bool
) –Whether to auto-add existing attachments to
attachments
, defaultFalse
.Note
Only needed when
attachments
are passed, otherwise will be ignored.suppress_embeds (
bool
) – Whether to suppress embeds for the message. IfTrue
this will remove all embeds from the message. If ´False` it adds them back.delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the response 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 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_mentions
are used instead.
- await delete(*, delay=None)
This function is a coroutine.
Deletes the message.
Note
This can only be used while the interaction token is valid. So within 15 minutes after the interaction.
- 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:
NotFound – The message was deleted already or the interaction token expired
HTTPException – Deleting the message failed.
MessageInteraction
- class discord.MessageInteraction
Bases:
object
Represents the
interaction
object of a message that is a response to an interaction without an existing message.Note
This means responses to
ComponentInteraction
does not include this, instead including areference
as components always exist on preexisting messages.New in version 2.0.
- name
The name of the
ApplicationCommand
, including subcommands and subcommand groups.- Type:
RoleSubscriptionInfo
- class discord.RoleSubscriptionInfo
Bases:
object
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.
- total_months_subscribed
The cumulative number of months that the user has been subscribed for.
- Type:
DeletedReferencedMessage
- class discord.DeletedReferencedMessage
Bases:
object
A special sentinel type that denotes whether the resolved message referenced message had since been deleted.
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.
- property guild_id
The guild ID of the deleted referenced message.
- Type:
Optional[
int
]
Reaction
- class discord.Reaction
Bases:
object
Represents a reaction to a message.
Depending on the way this object was created, some 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. Might be a custom emoji, or a unicode emoji.
- Type:
Union[
Emoji
,PartialEmoji
,str
]
- async for ... in users(limit=None, after=None)
Returns an
AsyncIterator
representing the users that have reacted to the message.The
after
parameter must represent a member and meet theabc.Snowflake
abc.Examples
Usage
# I do not actually recommend doing this. async for user in reaction.users(): await channel.send('{0} has reacted with {1.emoji}!'.format(user, reaction))
Flattening into a list:
users = await reaction.users().flatten() # users is now a list of User... winner = random.choice(users) await channel.send('{} has won the raffle.'.format(winner))
- Parameters:
limit (
int
) – The maximum number of results to return. If not provided, returns all the users who reacted to the message.after (
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 aMember
is in a guild message context. Sometimes it can be aUser
if the member has left the guild.
- is_burst()
bool
: Whether this is a burst reaction or not.
- await remove(user)
This function is a coroutine.
Remove the reaction by the provided
User
from the message.If the reaction is not your own (i.e.
user
parameter is not you) then themanage_messages
permission is needed.The
user
parameter must represent a user or member and meet theabc.Snowflake
abc.- 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 need the
manage_messages
permission to use this.New in version 1.3.
- 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.
InvalidArgument – The emoji parameter is invalid.
Guild
- afk_channel
- afk_timeout
- application_commands
- banner
- banner_url
- bitrate_limit
- cached_automod_rules
- categories
- channels
- chunked
- created_at
- default_notifications
- default_role
- description
- discovery_splash
- discovery_splash_url
- dms_disabled_until
- emoji_limit
- emojis
- events
- explicit_content_filter
- features
- filesize_limit
- forum_channels
- forum_posts
- guide_channels
- icon
- icon_url
- id
- invites_disabled_until
- large
- max_members
- max_presences
- max_video_channel_users
- me
- member_count
- members
- mfa_level
- name
- owner
- owner_id
- preferred_locale
- premium_progress_bar_enabled
- premium_subscriber_role
- premium_subscribers
- premium_subscription_count
- premium_tier
- public_updates_channel
- resource_channels
- roles
- rules_channel
- safety_alerts_channel
- scheduled_events
- self_role
- server_guide_channels
- shard_id
- splash
- splash_url
- stage_channels
- sticker_limit
- system_channel
- system_channel_flags
- text_channels
- thread_channels
- unavailable
- verification_level
- voice_channels
- voice_client
- defaudit_logs
- asyncautomod_rules
- asyncban
- defbanner_url_as
- defbans
- defby_category
- asyncchange_voice_state
- asyncchunk
- asynccreate_automod_rule
- asynccreate_category
- asynccreate_category_channel
- asynccreate_custom_emoji
- asynccreate_forum_channel
- asynccreate_integration
- asynccreate_role
- asynccreate_scheduled_event
- asynccreate_stage_channel
- asynccreate_sticker
- asynccreate_template
- asynccreate_text_channel
- asynccreate_voice_channel
- asyncdelete
- defdiscovery_splash_url_as
- asyncedit
- asyncedit_incidents_actions
- asyncedit_onboarding
- asyncedit_role_positions
- asyncestimate_pruned_members
- asyncfetch_active_threads
- asyncfetch_ban
- asyncfetch_channels
- asyncfetch_emoji
- asyncfetch_emojis
- asyncfetch_event
- asyncfetch_events
- asyncfetch_member
- deffetch_members
- asyncfetch_roles
- defget_application_command
- defget_channel
- defget_event
- defget_member
- defget_member_named
- defget_role
- defget_scheduled_event
- deficon_url_as
- asyncintegrations
- asyncinvites
- defis_icon_animated
- asynckick
- asyncleave
- asynconboarding
- asyncprune_members
- asyncquery_members
- defsplash_url_as
- defstage_instances
- asynctemplates
- asyncunban
- asyncvanity_invite
- asyncwebhooks
- asyncwelcome_screen
- asyncwidget
- class discord.Guild
Bases:
Hashable
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.
- emojis
All emojis that the guild owns.
- Type:
Tuple[
Emoji
, …]
- afk_channel
The channel that denotes the AFK channel.
None
if it doesn’t exist.- Type:
Optional[
VoiceChannel
]
- icon
The guild’s icon.
- Type:
Optional[
str
]
- owner_id
The guild owner’s ID. Use
Guild.owner
instead.- Type:
Indicates if the guild is unavailable. If this is
True
then the reliability of other attributes outside ofGuild.id
is 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_presences
The maximum amount of presences for the guild.
- Type:
Optional[
int
]
- max_members
The maximum amount of members for the guild.
Note
This attribute is only available via
Client.fetch_guild()
.- Type:
Optional[
int
]
- max_video_channel_users
The maximum amount of users in a video channel.
New in version 1.4.
- Type:
Optional[
int
]
- banner
The guild’s banner.
- Type:
Optional[
str
]
- description
The guild’s description.
- Type:
Optional[
str
]
- mfa_level
Indicates the guild’s two-factor authorisation level. If this value is 0 then the guild does not require 2FA for their administrative members. If the value is 1 then they do.
- Type:
- features
A list of features that the guild has. They are currently as follows:
VIP_REGIONS
: Guild has VIP voice regionsVANITY_URL
: Guild can have a vanity invite URL (e.g. discord.gg/discord-api)INVITE_SPLASH
: Guild’s invite page can have a special splash.VERIFIED
: Guild is a verified server.PARTNERED
: Guild is a partnered server.MORE_EMOJI
: Guild is allowed to have more than 50 custom emoji.MORE_STICKER
: Guild is allowed to have more than 60 custom sticker.DISCOVERABLE
: Guild shows up in Server Discovery.FEATURABLE
: Guild is able to be featured in Server Discovery.COMMUNITY
: Guild is a community server.PUBLIC
: Guild is a public guild.NEWS
: Guild can create news channels.BANNER
: Guild can upload and use a banner (i.e.banner_url()
).ANIMATED_ICON
: Guild can upload an animated icon.PUBLIC_DISABLED
: Guild cannot be public.WELCOME_SCREEN_ENABLED
: Guild has enabled the welcome screenMEMBER_VERIFICATION_GATE_ENABLED
: Guild has Membership Screening enabled.PREVIEW_ENABLED
: Guild can be viewed before being accepted via Membership Screening.
- Type:
List[
str
]
- splash
The guild’s invite splash.
- Type:
Optional[
str
]
The premium tier for this guild. Corresponds to “Nitro Server” in the official UI. The number goes from 0 to 3 inclusive.
- Type:
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.
- Type:
Optional[
Locale
]
Whether the guild has the boost progress bar enabled.
- Type:
- invites_disabled_until
When this is set to a time in the future, then invites to the guild are disabled until that time. .. versionadded:: 2.0
- Type:
Optional[
datetime
]
- dms_disabled_until
When this is set to a time in the future, then direct messages to members of the guild are disabled (unless users are friends to each other) until that time. .. versionadded:: 2.0
- Type:
Optional[
datetime
]
- async for ... in fetch_members(*, limit=1000, after=None)
Retrieves an
AsyncIterator
that enables receiving the guild’s members. In order to use this,Intents.members()
must be enabled.Note
This method is an API call. For general usage, consider
members
instead.New in version 1.3.
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of members to retrieve. Defaults to 1000. PassNone
to fetch all members. Note that this is potentially slow.after (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Retrieve members after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.
- Raises:
ClientException – The members intent is not enabled.
HTTPException – Getting the members failed.
- Yields:
Member
– The member with the member data parsed.
Examples
Usage
async for member in guild.fetch_members(limit=150): print(member.name)
Flattening into a list
members = await guild.fetch_members(limit=150).flatten() # members is now a list of Member...
- async for ... in audit_logs(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)
Returns an
AsyncIterator
that enables receiving the guild’s audit logs.You must have the
view_audit_log
permission to use this.Examples
Getting the first 100 entries:
async for entry in guild.audit_logs(limit=100): print('{0.user} did {0.action} to {0.target}'.format(entry))
Getting entries for a specific action:
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban): print('{0.user} banned {0.target}'.format(entry))
Getting entries made by a specific user:
entries = await guild.audit_logs(limit=None, user=guild.me).flatten() await channel.send('I made {} moderation actions.'.format(len(entries)))
- Parameters:
limit (Optional[
int
]) – The number of entries to retrieve. IfNone
retrieve all entries.before (Union[
abc.Snowflake
,datetime.datetime
]) – Retrieve entries before this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Union[
abc.Snowflake
,datetime.datetime
]) – Retrieve entries after this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time.oldest_first (
bool
) – If set toTrue
, return entries in oldest->newest order. Defaults toTrue
ifafter
is 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.
- property application_commands
A list of application-commands from this application that are registered only in this guild.
- Type:
List[
ApplicationCommand
]
- get_application_command(id)
Optional[
ApplicationCommand
]: Returns an application-command from this application that are registered only in this guild with the given id
- property channels
A list of channels that belongs to this guild.
- Type:
List[
abc.GuildChannel
,ThreadChannel
,ForumPost
]
- property server_guide_channels
A list of channels that are part of the servers guide.
- Type:
List[
abc.GuildChannel
]
- property events
A list of scheduled events that belong to this guild.
- Type:
List[
GuildScheduledEvent
]
- property scheduled_events
A list of scheduled events that belong to this guild.
- Type:
List[
GuildScheduledEvent
]
- property cached_automod_rules
A list of auto moderation rules that are cached.
Reliable Fetching
This property is only reliable if
automod_rules()
was used before. To ensure that the rules are up-to-date, useautomod_rules()
instead.- Type:
List[
AutoModRules
]
- get_event(id)
Returns a scheduled event with the given ID.
- Parameters:
id (
int
) – The ID of the event to get.- Returns:
The scheduled event or
None
if not found.- Return type:
Optional[
GuildScheduledEvent
]
- get_scheduled_event(id)
Returns a scheduled event with the given ID.
- Parameters:
id (
int
) – The ID of the event to get.- Returns:
The scheduled event or
None
if not found.- Return type:
Optional[
GuildScheduledEvent
]
- property large
Indicates if the guild is a ‘large’ guild.
A large guild is defined as having more than
large_threshold
count 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 voice 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.user
except an instance ofMember
. This is essentially used to get the member version of yourself.- Type:
- property voice_client
Returns the
VoiceProtocol
associated with this guild, if any.- Type:
Optional[
VoiceProtocol
]
- 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 thread_channels
A list of cached thread channels the guild has.
This is sorted by the position of the threads
parent
and are in UI order from top to bottom.- Type:
List[
ThreadChannel
]
- property forum_channels
A list of forum channels the guild has.
This is sorted by the position of the forums
parent
and are in UI order from top to bottom.- Type:
List[
ForumChannel
]
- property forum_posts
A list of cached forum posts the guild has.
This is sorted by the position of the forums
parent
and are in UI order from top to bottom.- Type:
List[
ForumPost
]
- property guide_channels
A list of channels that are part of the server guide.
There is an alias for this called
resource_channels
.- Type:
List[
GuildChannel
]
- property resource_channels
A list of channels that are part of the server guide.
There is an alias for this called
resource_channels
.- Type:
List[
GuildChannel
]
- 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
]
- by_category()
Returns every
CategoryChannel
and 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(channel_id)
Returns a channel with the given ID.
- Parameters:
channel_id (
int
) – The ID to search for.- Returns:
The channel or
None
if not found.- Return type:
Optional[Union[
abc.GuildChannel
,ThreadChannel
,ForumPost
]]
- 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 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 2.0.
- Type:
Optional[
TextChannel
]
- property safety_alerts_channel
Return’s the guild’s channel where Discord sends safety alerts in. The guild must be a Community guild.
If no channel is set, then this returns
None
.New in version 2.0.
- Type:
Optional[
TextChannel
]
- property filesize_limit
The maximum number of bytes files can have when uploaded to this guild.
- Type:
- property members
A list of members that belong to this guild.
- Type:
List[
Member
]
A list of members who have “boosted” this guild.
- Type:
List[
Member
]
- property roles
Returns a
list
of the guild’s roles in hierarchy order.The first element of this list will be the lowest role in the hierarchy.
- Type:
List[
Role
]
Gets the premium subscriber role, AKA “boost” role, in this guild.
New in version 1.6.
- Type:
Optional[
Role
]
- property self_role
Gets the role associated with this client’s user, if any.
New in version 1.6.
- Type:
Optional[
Role
]
- property owner
The member that owns the guild.
- Type:
Optional[
Member
]
- is_icon_animated()
bool
: Returns True if the guild has an animated icon.
- icon_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the guild’s icon.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the icon to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the icon being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated icons to.size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- banner_url_as(*, format='webp', size=2048)
Returns an
Asset
for the guild’s banner.The format must be one of ‘webp’, ‘jpeg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- splash_url_as(*, format='webp', size=2048)
Returns an
Asset
for the guild’s invite splash.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- discovery_splash_url_as(*, format='webp', size=2048)
Returns an
Asset
for the guild’s discovery splash.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
New in version 1.3.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- property member_count
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires
Intents.members
to be specified.- Type:
- property chunked
Returns a boolean indicating if the guild is “chunked”.
A chunked guild means that
member_count
is equal to the number of members stored in the internalmembers
cache.If this value returns
False
, then you should request for offline members.- Type:
- property shard_id
Returns the shard ID for this guild if applicable.
- Type:
Optional[
int
]
- 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,
None
is returned.
- await create_text_channel(name, *, overwrites=None, category=None, reason=None, **options)
This function is a coroutine.
Creates a
TextChannel
for the guild.Note that you need the
manage_channels
permission to create the channel.The
overwrites
parameter can be used to create a ‘secret’ channel upon creation. This parameter expects adict
of overwrites with the target (either aMember
or aRole
) as the key and aPermissionOverwrite
as 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.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 – A
dict
of target (either a role or a member) toPermissionOverwrite
to 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 (Optional[
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 is 21600.default_thread_slowmode_delay (
int
) – The initialslowmode_delay
to set on newly created threads in the channel. This field is copied to the thread at creation time and does not live update.nsfw (
bool
) – To mark the channel as NSFW or not.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.
InvalidArgument – The permission overwrite information is not in proper form.
- Returns:
The channel that was just created.
- Return type:
- await create_voice_channel(name, *, overwrites=None, category=None, reason=None, **options)
This function is a coroutine.
This is similar to
create_text_channel()
except makes aVoiceChannel
instead, in addition to having the following new parameters.- Parameters:
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[
VoiceRegion
]) –The region for the voice channel’s voice communication. A value of
None
indicates automatic voice region detection.New in version 1.7.
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Returns:
The channel that was just created.
- Return type:
- await create_stage_channel(name, *, topic=None, category=None, overwrites=None, reason=None, position=None)
This function is a coroutine.
This is similar to
create_text_channel()
except makes aStageChannel
instead, in addition to having the following new parameters.- Parameters:
topic (Optional[
str
]) – The topic of the Stage instance (1-120 characters)note:: (..) – The
slowmode_delay
andnsfw
parameters are not supported in this function.versionadded: (..) – 1.7:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Returns:
The channel that was just created.
- Return type:
- await create_forum_channel(name, *, topic=None, slowmode_delay=None, default_post_slowmode_delay=None, default_auto_archive_duration=None, overwrites=None, nsfw=None, category=None, position=None, reason=None)
This function is a coroutine.
Same as
create_text_channel()
excepts that it creates a forum channel instead- Parameters:
name (
str
) – The name of the channeloverwrites – A
dict
of target (either a role or a member) toPermissionOverwrite
to 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 (Optional[
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 is 21600.default_post_slowmode_delay (
int
) – The initialslowmode_delay
to set on newly created threads in the channel. This field is copied to the thread at creation time and does not live update.default_auto_archive_duration (
AutoArchiveDuration
) – The default duration that the clients use (not the API) for newly created threads in the channel, in minutes, to automatically archive the thread after recent activitynsfw (
bool
) – To mark the channel as NSFW or not.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.
InvalidArgument – The permission overwrite information is not in proper form, or the
default_auto_archive_duration
is not a valid member ofAutoArchiveDuration
- Returns:
The channel that was just created
- Return type:
- await create_category(name, *, overwrites=None, reason=None, position=None)
This function is a coroutine.
Same as
create_text_channel()
except makes aCategoryChannel
instead.Note
The
category
parameter is not supported in this function since categories cannot have categories.- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Returns:
The channel that was just created.
- Return type:
- await create_category_channel(name, *, overwrites=None, reason=None, position=None)
This function is a coroutine.
Same as
create_text_channel()
except makes aCategoryChannel
instead.Note
The
category
parameter is not supported in this function since categories cannot have categories.- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – 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 the 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(name=MISSING, description=MISSING, features=MISSING, icon=MISSING, banner=MISSING, splash=MISSING, discovery_splash=MISSING, region=MISSING, afk_channel=MISSING, afk_timeout=MISSING, system_channel=MISSING, system_channel_flags=MISSING, rules_channel=MISSING, public_updates_channel=MISSING, preferred_locale=MISSING, verification_level=MISSING, default_notifications=MISSING, explicit_content_filter=MISSING, vanity_code=MISSING, owner=MISSING, *, reason=None)
This function is a coroutine.
Edits the guild.
You must have the
manage_guild
permission to edit the guild.Changed in version 1.4: The rules_channel and public_updates_channel keyword-only parameters were added.
- Parameters:
name (
str
) – The new name of the guild.description (
str
) – The new description of the guild. This is only available to guilds that containPUBLIC
inGuild.features
.features (
GuildFeatures
) – Features to enable/disable will be merged in to the current features. See the discord api documentation for a list of currently mutable features and the required permissions.icon (
bytes
) – A bytes-like object representing the icon. Only PNG/JPEG is supported. GIF is only available to guilds that containANIMATED_ICON
inGuild.features
. Could beNone
to denote removal of the icon.banner (
bytes
) – A bytes-like object representing the banner. Could beNone
to denote removal of the banner.splash (
bytes
) – A bytes-like object representing the invite splash. Only PNG/JPEG supported. Could beNone
to denote removing the splash. This is only available to guilds that containINVITE_SPLASH
inGuild.features
.discovery_splash (
bytes
) – A bytes-like object representing the discovery splash. Only PNG/JPEG supported. Could beNone
to denote removing the splash. This is only available to guilds that containDISCOVERABLE
inGuild.features
.region (
VoiceRegion
) – Deprecated: The new region for the guild’s voice communication.afk_channel (Optional[
VoiceChannel
]) – The new channel that is the AFK channel. Could beNone
for 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 beNone
for no system channel.system_channel_flags (
SystemChannelFlags
) – The new system channel settings to use with the new system channel.preferred_locale (
str
) – The new preferred locale for the guild. Used as the primary language in the guild. If set, this must be an ISO 639 code, e.g.en-US
orja
orzh-CN
.rules_channel (Optional[
TextChannel
]) – The new channel that is used for rules. This is only available to guilds that containPUBLIC
inGuild.features
. Could beNone
for no rules channel.public_updates_channel (Optional[
TextChannel
]) – The new channel that is used for public updates from Discord. This is only available to guilds that containPUBLIC
inGuild.features
. Could beNone
for no public updates channel.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.
InvalidArgument – The image format passed in to
icon
is 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.
- await fetch_channels()
This function is a coroutine.
Retrieves all
abc.GuildChannel
that the guild has.Note
This method is an API call. For general usage, consider
channels
instead.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:
List[
abc.GuildChannel
]
- await fetch_active_threads()
This function is a coroutine.
Returns all active threads and forum posts in the guild. This includes all public and private threads as long as the current user has permissions to access them. Threads are ordered by their id, in descending order.
Note
This method is an API call.
New in version 2.0.
- Returns:
The active threads and forum posts in the guild.
- Return type:
List[Union[
ThreadChannel
,ForumPost
]]
- await fetch_member(member_id)
This function is a coroutine.
Retrieves a
Member
from a guild ID, and a member ID.Note
This method is an API call. If you have
Intents.members
and member cache enabled, considerget_member()
instead.- 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.
- Returns:
The member from the member ID.
- Return type:
- await fetch_ban(user)
This function is a coroutine.
Retrieves the
BanEntry
for a user.You must have the
ban_members
permission to 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
BanEntry
object for the specified user.- Return type:
- bans(limit=None, before=None, after=None)
Retrieves an
AsyncIterator
that enables receiving the guild’s bans.You must have the
ban_members
permission to get this information.Note
This method is an API call. Use it careful.
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of bans to retrieve. Defaults to all. Note that this is potentially slow.before (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Retrieve members before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Retrieve members after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.
- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – Getting the bans failed.
- Yields:
BanEntry
– The ban entry containing the user and an optional reason.
Examples
Usage
async for ban_entry in guild.bans(limit=150): print(ban_entry.user)
Flattening into a list
ban_entries = await guild.bans(limit=150).flatten() # ban_entries is now a list of BanEntry...
- await prune_members(*, days, compute_prune_count=True, roles=None, 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
days
number of days, and they have no roles.You must have the
kick_members
permission to use 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
roles
parameter.Changed in version 1.4: The
roles
keyword-only parameter was added.- 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 toTrue
which 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 (Optional[List[
abc.Snowflake
]]) – A list ofabc.Snowflake
that 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.
InvalidArgument – An integer was not passed for
days
.
- Returns:
The number of members pruned. If
compute_prune_count
isFalse
then this returnsNone
.- Return type:
Optional[
int
]
- await templates()
This function is a coroutine.
Gets the list of templates from this guild.
Requires
manage_guild
permissions.New in version 1.7.
- await webhooks()
This function is a coroutine.
Gets the list of webhooks from this guild.
Requires
manage_webhooks
permissions.
- await estimate_pruned_members(*, days, roles=None)
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.- Parameters:
days (
int
) – The number of days before counting as inactive.roles (Optional[List[
abc.Snowflake
]]) –A list of
abc.Snowflake
that 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.
InvalidArgument – An integer was not passed for
days
.
- Returns:
The number of members estimated to be pruned.
- Return type:
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from the guild.
You must have the
manage_guild
permission to 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=None)
This function is a coroutine.
Creates a template for the guild.
You must have the
manage_guild
permission to do this.New in version 1.7.
- await create_integration(*, type, id)
This function is a coroutine.
Attaches an integration to the guild.
You must have the
manage_guild
permission to 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()
This function is a coroutine.
Returns a list of all integrations attached to the guild. You must have the
manage_guild
permission to do this. .. versionadded:: 1.4 :raises Forbidden: You do not have permission to create the integration. :raises HTTPException: Fetching the integrations failed.- Returns:
The list of integrations that are attached to the guild.
- Return type:
List[
Integration
]
- await fetch_emojis()
This function is a coroutine.
Retrieves all custom
Emoji
s from the guild.Note
This method is an API call. For general usage, consider
emojis
instead.- 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
Emoji
from the guild.Note
This method is an API call. For general usage, consider iterating over
emojis
instead.- 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=None, reason=None)
This function is a coroutine.
Creates a custom
Emoji
for the guild.There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the
MORE_EMOJI
feature which extends the limit to 200.You must have the
manage_emojis
permission to 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 (Optional[List[
Role
]]) – Alist
ofRole
s 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 fetch_roles()
This function is a coroutine.
Retrieves all
Role
that the guild has.Note
This method is an API call. For general usage, consider
roles
instead.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=MISSING, permissions=MISSING, color=MISSING, colour=MISSING, hoist=False, mentionable=False, icon=None, unicode_emoji=None, reason=None)
This function is a coroutine.
Creates a
Role
for the guild.All fields are optional.
You must have the
manage_roles
permission to do this.Changed in version 1.6: Can now pass
int
tocolour
keyword-only parameter.New in version 2.0: Added the
icon
andunicode_emoji
keyword-only parameters.Note
The
icon
andunicode_emoji
can’t be used together. Both of them can only be used whenROLE_ICONS
is in the guildfeatures()
.- Parameters:
name (
str
) – The role name. Defaults to ‘new role’.permissions (
Permissions
) – The permissions to have. Defaults to no permissions.color (Union[
Colour
,int
]) – The colour for the role. Defaults toColour.default()
.colour (Union[
Colour
,int
]) – The colour for the role. Defaults toColour.default()
. This is aliased tocolor
as well.hoist (
bool
) – Indicates if the role should be shown separately in the member list. Defaults toFalse
.mentionable (
bool
) – Indicates if the role should be mentionable by others. Defaults toFalse
.icon (Optional[
bytes
]) – The bytes-like object representing the image data to use as the roleicon
.unicode_emoji (Optional[
str
]) – The unicode emoji to use as the roleunicode_emoji
.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.
InvalidArgument – Both
icon
andunicode_emoji
were passed.
- Returns:
The newly created role.
- Return type:
- await edit_role_positions(positions, *, reason=None)
This function is a coroutine.
Bulk edits a list of
Role
in the guild.You must have the
manage_roles
permission to do this.New in version 1.4.
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.
InvalidArgument – 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.Snowflake
abc.You must have the
kick_members
permission to 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, *, delete_message_days=None, delete_message_seconds=0, reason=None)
This function is a coroutine.
Bans a user from the guild.
The user must meet the
abc.Snowflake
abc.You must have the
ban_members
permission to 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.
Deprecated since version 2.0.
delete_message_seconds (
int
) –The number of days worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (7 days).
New in version 2.0.
reason (Optional[
str
]) – The reason the user got banned.
- Raises:
Forbidden – You do not have the proper permissions to ban.
HTTPException – Banning failed.
- await unban(user, *, reason=None)
This function is a coroutine.
Unbans a user from the guild.
The user must meet the
abc.Snowflake
abc.You must have the
ban_members
permission to 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:
Forbidden – You do not have the proper permissions to unban.
HTTPException – Unbanning failed.
- await vanity_invite()
This function is a coroutine.
Returns the guild’s special vanity invite.
The guild must have
VANITY_URL
infeatures
.You must have the
manage_guild
permission to use 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.
- Return type:
- 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 chunk(*, cache=True)
This function is a coroutine.
Requests all members that belong to this guild. In order to use this,
Intents.members()
must be enabled.This is a websocket operation and can be slow.
New in version 1.5.
- Parameters:
cache (
bool
) – Whether to cache the members as well.- Raises:
ClientException – The members intent is not enabled.
- await query_members(query=None, *, limit=5, user_ids=None, presences=False, cache=True)
This function is a coroutine.
Request members that belong to this guild whose username starts with the query given.
This is a websocket operation and can be slow.
New in version 1.3.
- Parameters:
query (Optional[
str
]) – The string that the username’s 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
False
.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.
- Raises:
asyncio.TimeoutError – The query timed out waiting for the members.
ValueError – Invalid parameters were passed to the function
ClientException – The presences intent is not enabled.
- 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)
This function is a coroutine.
Changes client’s voice state in the guild.
New in version 1.4.
- Parameters:
channel (Optional[
VoiceChannel
]) – Channel the client wants to join. UseNone
to disconnect.self_mute (
bool
) – Indicates if the client should be self-muted.self_deaf (
bool
) – Indicates if the client should be self-deafened.
- await create_sticker(name, file, tags, description=None, *, reason=None)
This function is a coroutine.
Create a new sticker for the guild.
Requires the
MANAGE_EMOJIS_AND_STICKERS
permission.- Parameters:
name (
str
) – The name of the sticker (2-30 characters).tags (Union[
str
, List[str
]]) – Autocomplete/suggestion tags for the sticker separated by,
or in a list. (max 200 characters).description (Optional[
str
]) – The description of the sticker (None or 2-100 characters).file (Union[
UploadFile
,str
]) – The sticker file to upload or the path to it, must be a PNG, APNG, GIF or Lottie JSON file, max 500 KBreason (Optional[
str
]) – The reason for creating the sticker., shows up in the audit-log.
- Raises:
discord.Forbidden: – You don’t have the permissions to upload stickers in this guild.
discord.HTTPException: – Creating the sticker failed.
ValueError – Any of name, description or tags is too short/long.
- Returns:
The new GuildSticker created on success.
- Return type:
- await fetch_events(with_user_count=True)
This function is a coroutine.
Retrieves a
list
of scheduled events the guild has.Note
This method is an API call. For general usage, consider iterating over
events
instead.- Parameters:
with_user_count (
bool
) – Whether to include the number of interested users the event has, defaultTrue
.- Returns:
A list of scheduled events the guild has.
- Return type:
Optional[List[
GuildScheduledEvent
]]
- await fetch_event(id, with_user_count=True)
This function is a coroutine.
Fetches the
GuildScheduledEvent
with the given id.- Parameters:
- Returns:
The event on success.
- Return type:
Optional[
GuildScheduledEvent
]
- await create_scheduled_event(name, entity_type, start_time, end_time=None, channel=None, description=None, location=None, cover_image=None, *, reason=None)
This function is a coroutine.
Schedules a new Event in this guild. Requires
MANAGE_EVENTS
at least in thechannel
or in the entire guild iftype
isexternal
.- Parameters:
name (
str
) – The name of the scheduled event. 1-100 characters long.entity_type (
EventEntityType
) –The entity_type of the scheduled event.
Important
end_time
andlocation
must be provided if entity_type isexternal
, otherwisechannel
start_time (
datetime.datetime
) – The time when the event will start. Must be a valid date in the future.end_time (Optional[
datetime.datetime
]) –The time when the event will end. Must be a valid date in the future.
Important
If
entity_type
isexternal
this must be provided.channel (Optional[Union[
StageChannel
,VoiceChannel
]]) – The channel in which the event takes place. Must be provided ifentity_type
isstage
orvoice
.description (Optional[
str
]) – The description of the scheduled event. 1-1000 characters long.location (Optional[
str
]) –The location where the event will take place. 1-100 characters long.
Important
This must be provided if
entity_type
isexternal
cover_image (Optional[
bytes
]) – The cover image of the scheduled event.reason (Optional[
str
]) – The reason for scheduling the event, shows up in the audit-log.
- Returns:
The scheduled event on success.
- Return type:
- Raises:
TypeError: – Any parameter is of wrong type.
errors.InvalidArgument: – entity_type is
stage
orvoice
butchannel
is not provided orexternal
but nolocation
and/orend_time
provided.ValueError: – The value of any parameter is invalid. (e.g. to long/short)
errors.Forbidden: – You don’t have permissions to schedule the event.
discord.HTTPException: – Scheduling the event failed.
- await welcome_screen()
This function is a coroutine.
Fetches the welcome screen from the guild if any.
New in version 2.0.
- Returns:
The welcome screen of the guild if any.
- Return type:
Optional[
WelcomeScreen
]
- await onboarding()
This function is a coroutine.
Fetches the onboarding configuration for the guild.
New in version 2.0.
- Returns:
The onboarding configuration fetched.
- Return type:
Onboarding
- await edit_onboarding(*, prompts=MISSING, default_channels=MISSING, enabled=MISSING, mode=MISSING, reason=None)
This function is a coroutine.
Edits the onboarding configuration for the guild.
New in version 2.0.
- Parameters:
prompts (List[
PartialOnboardingPrompt
]) – The prompts that will be shown to new members (ifis_onboarding
isTrue
, otherwise only in customise community).default_channels (List[
Snowflake
]) – The channels that will be added to new members’ channel list by default.enabled (
bool
) – Whether the onboarding configuration is enabled.mode (
OnboardingMode
) – The mode that will be used for the onboarding configuration.reason (Optional[
str
]) – The reason for editing the onboarding configuration. Shows up in the audit log.
- Raises:
Forbidden – You do not have permissions to edit the onboarding configuration.
HTTPException – Editing the onboarding configuration failed.
- Returns:
The new onboarding configuration.
- Return type:
Onboarding
- await automod_rules()
This function is a coroutine.
Fetches the Auto Moderation rules for this guild
Warning
This is an API-call, use it carefully.
- Returns:
A list of AutoMod rules the guild has
- Return type:
List[
AutoModRule
]
- await create_automod_rule(name, event_type, trigger_type, trigger_metadata, actions, enabled=True, exempt_roles=[], exempt_channels=[], *, reason=None)
This function is a coroutine.
Creates a new AutoMod rule for this guild
- Parameters:
name (
str
) – The name, the rule should have. Only valid if it’s not a preset rule.event_type (
AutoModEventType
) – Indicates in what event context a rule should be checked.trigger_type (
AutoModTriggerType
) – Characterizes the type of content which can trigger the rule.trigger_metadata (
AutoModTriggerMetadata
) – Additional data used to determine whether a rule should be triggered. Different fields are relevant based on the value oftrigger_type
.actions (List[
AutoModAction
]) – The actions which will execute when the rule is triggered.exempt_roles (List[
Snowflake
]) – Up to 20Role
’s, that should not be affected by the rule.exempt_channels (List[
Snowflake
]) – Up to 50TextChannel
/VoiceChannel
’s, that should not be affected by the rule.reason (Optional[
str
]) – The reason for creating the rule. Shows up in the audit log.
- Raises:
discord.Forbidden – The bot is missing permissions to create AutoMod rules
HTTPException – Creating the rule failed
- Returns:
The AutoMod rule created
- Return type:
- await edit_incidents_actions(*, invites_disabled_until, dms_disabled_until, reason=None)
This function is a coroutine.
Edits the incident actions of the guild. This requires the
manage_guild
permission.- Parameters:
invites_disabled_until (Optional[
datetime.datetime
]) – When invites should be possible again (up to 24h in the future). Set toNone
to enable invites again.dms_disabled_until (Optional[
datetime.datetime
]) – When direct messages should be enabled again (up to 24h in the future). Set toNone
to enable direct messages again.reason (Optional[
str
]) – The reason for editing the incident actions. Shows up in the audit log.
- Raises:
Forbidden – You don’t have permissions to edit the incident actions.
HTTPException – Editing the incident actions failed.
- class discord.GuildFeatures
-
Represents a guild’s features.
This class mainly exists to make it easier to edit a guild’s features.
New in version 2.0.
- 'FEATURE_NAME' in features
Checks if the guild has the feature.
- features.FEATURE_NAME
Checks if the guild has the feature. Returns
False
if it doesn’t.
- features.FEATURE_NAME = True
Enables the feature in the features object, but does not enable it in the guild itself except if you pass it to
Guild.edit()
.
- features.FEATURE_NAME = False
Disables the feature in the features object, but does not disable it in the guild itself except if you pass it to
Guild.edit()
.
- del features.FEATURE_NAME
The same as
features.FEATURE_NAME = False
- features.parsed()
Returns a list of all features that are/should be enabled.
- features.merge(other)
Returns a new object with the features of both objects merged. If a feature is missing in the other object, it will be ignored.
- features == other
Checks if two feature objects are equal.
- features != other
Checks if two feature objects are not equal.
- iter(features)
Returns an iterator over the enabled features.
- Parameters:
GuildScheduledEvent
- asyncdelete
- asyncedit
- deficon_url_as
- asyncusers
- class discord.GuildScheduledEvent
Bases:
Hashable
Represents a scheduled event in a guild
Warning
Do not initialize this class manually. Use
fetch_event()
/fetch_events()
or to create onecreate_scheduled_event()
instead.- end_time
Optional, when the event will end
- Type:
Optional[
datetime.datetime
]
- image
Optional, the image hash of the event
- Type:
Optional[
str
]
- broadcast_to_directory_channels
Whether the event will be broadcasted to directory channels
Note
This is only possible when the guild the event belongs to is part of a student hub.
- Type:
- async for ... in await users(limit=100, before=None, after=None, with_member=False)
Returns an
AsyncIterator
that enables receiving the interest users of the event.All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of users to retrieve. IfNone
, retrieves every user of the event. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve users before this user. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve users after this user. If a date is provided it must be a timezone-naive datetime representing UTC time.with_member (Optional[
bool
]) – If set toTrue
, return theMember
instead of theUser
if it is part of the guild the event is in.
Examples
# Usage counter = 0 async for user in event.users(limit=200): if user.id > 264905529753600000: # all accounts created before 2018 counter += 1 # Flattening into a list users = await event.users(limit=123).flatten() # users is now a list of Member/User...
- Raises:
Forbidden – You do not have permissions to get the event users.
HTTPException – The request to get event users failed.
- Yields:
- property location
The location of the event if
entity_type
isexternal
.- Type:
Optional[
str
]
- property channel
Optional[Union[
StageChannel
,VoiceChannel
]]: The channel the event is scheduled in ifentity_type
isstage
orvoice
.
- icon_url_as(*, format='webp', size=1024)
Returns an
Asset
for the event image.The format must be one of ‘webp’, ‘jpeg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- await edit(*, name=MISSING, description=MISSING, start_time=MISSING, end_time=MISSING, status=MISSING, entity_type=MISSING, location=MISSING, channel=MISSING, cover_image=MISSING, reason=None)
This function is a coroutine.
Modify the event. Requires
manage_events
permissions. All parameters are optional.- Parameters:
name (
str
) – The new name of the eventdescription (
str
) – The new description of the eventstart_time (
datetime.datetime
) – The new start time of the eventend_time (Optional[
datetime.datetime
]) – The new end time of the eventstatus (
EventStatus
) – The new status of the event.entity_type (
EventEntityType
) – The new type of the scheduled eventlocation (
str
) – The new location of the event. Ifentity_type
isexternal
channel (Optional[Union[
StageChannel, :class:`VoiceChannel
]]) – The new channel the event is scheduled in ifentity_type
isEventEntityType.stage
orEventEntityType.voice
.cover_image (Optional[
bytes
]) – The new cover image of the event. Must be abytes
object representing a jpeg or png image.reason (Optional[
str
]) – The reason for editing the event, shows up in the audit-log.
- Returns:
The updatet event.
- Return type:
- await delete(*, reason=None)
Deletes the event. Requires
MANAGE_EVENTS
permissions.- Parameters:
reason (Optional[
str
]) – The reason for deleting the event, shows up in the audit-log.- Return type:
None
AutoModRule
- class discord.AutoModRule
Bases:
object
Represents a rule for auto moderation
Warning
Do not initialize this class directly. Use
create_automod_rule()
instead.- trigger_metadata
Additional data used to determine whether a rule should be triggered. Different fields are relevant based on the value of
trigger_type
.- Type:
- actions
The actions which will execute when the rule is triggered
- Type:
List[
AutoModAction
]
- property exempt_roles
Yields the roles that should not be affected by the rule (Maximum of 20)
Note
This is equal to
for role_id in self._exempt_roles: role = self.guild.get_role(int(role_id)) yield role or Object(int(role_id))
- property exempt_channels
Yields the channels that should not be affected by the rule (Maximum of 20)
Note
This is equal to
for channel_id in self._exempt_channels: channel = self.guild.get_role(int(channel_id)) yield channel or Object(channel_id, type=GuildChannel, state=self._state)
- property creator
Returns the creator of the rule
Note
The
Intents.members
must be enabled, otherwise this may return `` None``
- await delete(*, reason)
This function is a coroutine.
Deletes the automod rule, this requires the
manage_server
permission.- Parameters:
reason (Optional[
str
]) – The reason for deleting this rule. Shows up in the audit log.- Raises:
discord.Forbidden – The bot is missing permissions to delete the rule
HTTPException – Deleting the rule failed
- await edit(*, name=MISSING, event_type=MISSING, trigger_type=MISSING, trigger_metadata=MISSING, actions=MISSING, enabled=MISSING, exempt_roles=MISSING, exempt_channels=MISSING, reason=None)
This function is a coroutine.
Edits the automod rule, this requires the
manage_server
permission.You only need to provide the parameters you want to edit the.
- Parameters:
name (
str
) – The name, the rule should have. Only valid if it’s not a preset rule.event_type (
AutoModEventType
) – Indicates in what event context a rule should be checked.trigger_type (
AutoModTriggerType
) – Characterizes the type of content which can trigger the ruletrigger_metadata (
AutoModTriggerMetadata
) – Additional data used to determine whether a rule should be triggered. Different fields are relevant based on the value oftrigger_type
.actions (List[
AutoModAction
]) – The actions which will execute when the rule is triggered.enabled (
bool
) – Whether the rule is enabled.exempt_roles (List[
Snowflake
]) – Up to 20Role
’s, that should not be affected by the rule.exempt_channels (List[
Snowflake
]) – Up to 50TextChannel
/VoiceChannel
/StageChannel
’s, that should not be affected by the rule.reason (Optional[
str
]) – The reason for editing the rule. Shows up in the audit log.
- Raises:
discord.Forbidden – The bot is missing permissions to edit the rule
HTTPException – Editing the rule failed
- Returns:
The updated rule on success.
- Return type:
AutoModActionPayload
- class discord.AutoModActionPayload
Bases:
object
Represents the payload for an
on_automod_action()
event- channel_id
The id of the channel in which user content was posted
- Type:
Optional[
int
]
- message_id
The id of any user message which content belongs to
Note
This wil not exists if message was blocked by automod or content was not part of any message
- Type:
Optional[
int
]
- alert_system_message_id
The id of any system auto moderation messages posted as the result of this action
- Type:
Optional[
int
]
- content
The user generated text content
Important
The
Intents.message_content
intent is required to get a non-empty value for this field- Type:
- matched_content
The substring in
content
that triggered the ruleImportant
The
message_content
intent is required to get a non-empty value for this field- Type:
- property channel
The channel in wich user content was posted, if any.
- Returns:
The
TextChannel
,VoiceChannel
orThreadChannel
the user content was posted in.- Return type:
Optional[
abc.GuildChannel
]
WelcomeScreen
- class discord.WelcomeScreen
Bases:
object
Represents a welcome screen for a guild returned by
welcome_screen()
.Warning
Do not initialize this class directly. Use
welcome_screen()
instead.- welcome_channels
- Type:
List[
WelcomeScreenChannel
]
Integration
- class discord.Integration
Bases:
object
Represents a guild integration.
New in version 1.4.
- await delete()
This function is a coroutine. Deletes the integration. You must have the
manage_guild
permission to do this.- Raises:
Forbidden – You do not have permission to delete the integration.
HTTPException – Deleting the integration failed.
Member
- accent_color
- accent_colour
- activities
- activity
- avatar
- avatar_decoration
- avatar_url
- banner
- banner_color
- banner_colour
- banner_url
- bot
- color
- colour
- communication_disabled_until
- created_at
- default_avatar
- default_avatar_url
- desktop_status
- discriminator
- display_avatar
- display_avatar_url
- display_banner_url
- display_name
- dm_channel
- flags
- global_name
- guild
- guild_avatar_url
- guild_banner_url
- guild_permissions
- hex_banner_color
- id
- is_migrated
- joined_at
- mention
- mobile_status
- mutual_guilds
- name
- nick
- pending
- premium_since
- public_flags
- raw_status
- role_ids
- roles
- status
- system
- timed_out
- top_role
- username
- voice
- web_status
- asyncadd_roles
- defavatar_decoration_url_as
- defavatar_url_as
- asyncban
- defbanner_url_as
- asynccreate_dm
- defdisplay_avatar_url_as
- defdisplay_banner_url_as
- asyncedit
- asyncfetch_message
- defguild_avatar_url_as
- defguild_banner_url_as
- defhistory
- defis_avatar_animated
- defis_banner_animated
- defis_guild_avatar_animated
- defis_guild_banner_animated
- defis_on_mobile
- asynckick
- defmentioned_in
- asyncmove_to
- defpermissions_in
- asyncpins
- asyncremove_roles
- asyncremove_timeout
- asyncrequest_to_speak
- asyncsend
- asynctimeout
- asynctrigger_typing
- deftyping
- asyncunban
- class discord.Member
Bases:
Messageable
,_BaseUser
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
User
instances too.
- x != y
Checks if two members are not equal. Note that this works with
User
instances too.
- hash(x)
Returns the member’s hash.
- str(x)
Returns the members
username
ifis_migrated
is true, else the member’s name with discriminator.Note
When the migration is complete, this will always return the
username
.
- joined_at
A 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
]
- activities
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
]]
- nick
The guild specific nickname of the user.
- Type:
Optional[
str
]
A 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
]
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
Returns an
AsyncIterator
that enables receiving the destination’s message history.You must have
read_message_history
permissions to use 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 = await channel.history(limit=123).flatten() # 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 date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC 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 toTrue
ifafter
is 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.
- async with typing()
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
Note
This is both a regular context manager and an async context manager. This means that both
with
andasync with
work with this.Example Usage:
async with channel.typing(): # do expensive stuff here await asyncio.sleep(15) await channel.send('done!')
- property name
Equivalent to
User.name
- property username
Equivalent to
User.username
- property global_name
Equivalent to
User.global_name
- property id
Equivalent to
User.id
- property discriminator
Equivalent to
User.discriminator
- property bot
Equivalent to
User.bot
- 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 dm_channel
Equivalent to
User.dm_channel
- await create_dm()
This function is a coroutine.
Creates a
DMChannel
with this user.This should be rarely called, as this is done transparently for most people.
- Returns:
The channel that was created.
- Return type:
- property mutual_guilds
Equivalent to
User.mutual_guilds
- 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 status
The member’s overall status. If the value is unknown, then it will be a
str
instead.- Type:
- is_on_mobile()
bool
: A helper function that determines if a member is active on a mobile device.
- 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 role_ids
An iterable of
int
contain the ID’s of the roles the member has. You can use this to check on an efficient way whether a member has a role or not- Type:
utils.SnowflakeList
- property roles
A
list
ofRole
that 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_name
Returns the user’s display name.
This is either the guild
nick
, theglobal_name
or theusername
of the user.- Type:
- property guild_avatar_url
Returns the guild-specific banner asset for the member if any.
- Type:
Optional[
Asset
]
- guild_avatar_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the guild-specific avatar of the member if any, elseNone
.The format must be one of ‘webp’, ‘jpeg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset if any.
- Return type:
Optional[
Asset
]
- is_guild_avatar_animated()
bool
: Indicates if the member has an animated guild-avatar.
- property display_avatar_url
Asset
: Returns the displayed avatar of the member.This is in the following order: - Guild-specific avatar if available - User avatar if available - Default avatar
- property display_avatar
An alias for
display_avatar_url
.- Type:
- display_avatar_url_as(format=None, static_format='webp', size=1024)
Asset
: Same behaviour asUser.avatar_url_as()
andguild_avatar_url_as()
but it prefers the guild-specific avatar
- property guild_banner_url
Returns the guild-specific banner asset for the member if any.
- Type:
Optional[
Asset
]
- guild_banner_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the guild-specific banner of the member if any, elseNone
.The format must be one of ‘webp’, ‘jpeg’, ‘gif’ or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset if any.
- Return type:
Optional[
Asset
}
- is_guild_banner_animated()
bool
: Indicates if the member has an animated guild-banner.
- property display_banner_url
Returns the guild-specific banner asset for the member if he has one, else the default banner asset if any.
- Type:
Optional[
Asset
]
- display_banner_url_as(format=None, static_format='webp', size=1024)
Optional[
Asset
]: Same behaviour asUser.banner_url_as()
andguild_banner_url_as()
but it prefers the guild-specific banner
- property activity
Returns the primary activity the user is currently doing. Could be
None
if no activity is being done.Note
Due to a Discord API limitation, this may be
None
if 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:
Union[
BaseActivity
,Spotify
]
- permissions_in(channel)
An alias for
abc.GuildChannel.permissions_for()
.Basically equivalent to:
channel.permissions_for(self)
- Parameters:
channel (
abc.GuildChannel
) – The channel to check your permissions for.- Returns:
The resolved permissions for the member.
- Return type:
- 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 either
permissions_in()
orabc.GuildChannel.permissions_for()
.This does take into consideration guild ownership and the administrator implication.
- Type:
- property voice
Returns the member’s current voice state.
- Type:
Optional[
VoiceState
]
- property communication_disabled_until
The time until the member is timeouted, if any
- Type:
Optional[
datetime.datetime
]
- property timed_out
Returns True when the member is timed out.
New in version 2.0.
- Type:
class.`bool`
- await timeout(until, *, reason=None)
This function is a coroutine.
A shortcut method to timeout a member. This just calls
edit()
with the communication_disabled_until field set.The
moderate_members
permission is needed to do this.- Parameters:
until (Union[
datetime
,timedelta
]) –Until when the member should be timeouted. This can be a timezone aware datetime object or a timedelta that will be added to the current time.
Note
This can be max 28 days from current time!
reason (Optional[
str
]) – The reason for sending the member to timeout - Shows up in the audit-log
- Raises:
TypeError – The passed
datetime
object is not timezone awareForbidden – The bot missing access to time out this member
HTTPException – Sending the member to timeout failed
- await remove_timeout(*, reason=None)
This function is a coroutine.
A shortcut method to remove a member from timeout.
The
moderate_members
permission is needed to do this.- Parameters:
reason (Optional[
str
]) – The reason for removing the member from timeout - Shows up in the audit-log- Raises:
Forbidden – The bot missing access to remove this member from timeout
HTTPException – Removing the member from timeout failed
- await ban(delete_message_days=None, delete_message_seconds=0, 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=MISSING, mute=MISSING, deafen=MISSING, suppress=MISSING, roles=MISSING, voice_channel=MISSING, flags=MISSING, communication_disabled_until=MISSING, 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
flags
communication_disabled_until
All parameters are optional.
Changed in version 1.1: Can now pass
None
tovoice_channel
to kick a member from voice.- Parameters:
nick (Optional[
str
]) – The member’s new nickname. UseNone
to 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 (Optional[List[
Role
]]) – The member’s new list of roles. This replaces the roles.voice_channel (Optional[
VoiceChannel
]) – The voice channel to move the member to. PassNone
to kick them from voice.flags (Optional[
GuildMemberFlags
]) – The new flags for this member. Note that you are currently only able to update theGuildMemberFlags.bypasses_verification
flag.communication_disabled_until (Optional[
datetime.datetime
]) –Temporarily puts the member in timeout until this time. If
None
, then the member is removed from timeout.Note
The
datetime
object must be timezone aware.reason (Optional[
str
]) – The reason for editing this member. Shows up on the audit log.
- Raises:
TypeError – The
datetime
object passed tocommunication_disabled_until
is not timezone awareForbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation 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
edit
providingsuppress
asFalse
.New in version 1.7.
- Raises:
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
- property avatar_decoration
Equivalent to
User.avatar_decoration
- avatar_decoration_url_as(*, format=None, size=1024)
Returns an
Asset
for the avatar decoration the user has. Could beNone
.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
, or invalidsize
.- Returns:
The resulting CDN asset if any.
- Return type:
Optional[
Asset
]
- property avatar_url
Equivalent to
User.avatar_url
- avatar_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the avatar the user has.If the user does not have a traditional avatar, an asset for the default avatar is returned instead.
The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the avatar to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the avatar being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
, or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- property banner_color
Equivalent to
User.banner_color
- property banner_colour
Equivalent to
User.banner_colour
- property banner_url
Equivalent to
User.banner_url
- banner_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the banner the user has. Could beNone
.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated banners. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the banner to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the banner being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated banner to. Defaults to ‘webp’size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
, or invalidsize
.- Returns:
The resulting CDN asset if any.
- Return type:
Optional[
Asset
]
- property default_avatar_url
Equivalent to
User.default_avatar_url
- await fetch_message(id, /)
This function is a coroutine.
Retrieves a single
Message
from the destination.This can only be used by bot accounts.
- 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 hex_banner_color
Equivalent to
User.hex_banner_color
- is_avatar_animated()
bool
: Indicates if the user has an animated avatar.
- is_banner_animated()
bool
: Indicates if the user has an animated banner.
- property is_migrated
Equivalent to
User.is_migrated
- 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 the
move_members
permission to use this.This raises the same exceptions as
edit()
.Changed in version 1.1: Can now pass
None
to kick a member from voice.- Parameters:
channel (Optional[Union[
VoiceChannel
,StageChannel
]) – The new voice channel to move the member to. PassNone
to kick them from voice.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.
- 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
Message
objects returned by this method do not contain completeMessage.reactions
data.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message
]
- await send(content=None, *, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, suppress_notifications=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 theembed
parameter must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type.- Parameters:
content (
str
) – The content of the message to send.tts (
bool
) – Indicates if the message should be sent using text-to-speech.embed (
Embed
) – The rich embed for the content.embeds (List[
Embed
]) – A list containing up to ten embedscomponents (List[Union[
ActionRow
, List[Union[Button
, Select]]]]) – A list of up to fiveActionRow`s or :class:`list
, each containing up to fiveButton
or one Select like object.file (
File
) – The file to upload.files (List[
File
]) – Alist
of files to upload. Must be a maximum of 10.stickers (List[
GuildSticker
]) – A list of up to 3discord.GuildSticker
that should be sent with the message.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.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_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
]) –A reference to the
Message
to 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_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
suppress_embeds (
bool
) – Whether to supress embeds send with the message, default toFalse
suppress_notifications (
bool
) –Whether to suppress desktop- & push-notifications for this message, default to
False
Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.
New in version 2.0.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
files
list is not of the appropriate size, you specified bothfile
andfiles
, or thereference
object is not aMessage
orMessageReference
.
- Returns:
The message that was sent.
- Return type:
- await trigger_typing()
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- await add_roles(*roles, reason=None, atomic=True)
This function is a coroutine.
Gives the member a number of
Role
s.You must have the
manage_roles
permission to use this, and the addedRole
s must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake
) – An argument list ofabc.Snowflake
representing aRole
to 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
Role
s from this member.You must have the
manage_roles
permission to use this, and the removedRole
s must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake
) – An argument list ofabc.Snowflake
representing aRole
to 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.
GuildMemberFlags
- class discord.GuildMemberFlags
Bases:
BaseFlags
Wraps up the Discord Guild Member flags.
- x == y
Checks if two GuildMemberFlags are equal.
- x != y
Checks if two GuildMemberFlags are not equal.
- 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. 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:
- bypasses_verification
Returns
True
if the member bypasses guild verification requirementsNote
This flag is editable and let you manually “verify” the member. This requires
moderate_members
permissions.- Type:
Spotify
- class discord.Spotify
Bases:
object
Represents a Spotify listening activity from Discord. This is a special case of
Activity
that 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
.This is an alias for
colour
.- Type:
- property artists
The artists of the song being played.
- Type:
List[
str
]
- 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:
VoiceState
- class discord.VoiceState
Bases:
object
Represents a Discord user’s voice state.
- await voice(...)
- Acts as a shortcut to :meth:`VoiceProtocol.connect`.
- Raises :exc:`NotInVoiceChannel` if :attr:`channel` is ``None``.
- 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 applies to stage channels.
New in version 1.7.
- Type:
- requested_to_speak_at
A datetime object that specifies the date and time in UTC that the member requested to speak. It will be
None
if 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.
None
if the user is not currently in a voice channel.- Type:
Optional[Union[
VoiceChannel
,StageChannel
]]
Emoji
- class discord.Emoji
Bases:
_EmojiTag
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.
- user
The user that created the emoji. This can only be retrieved using
Guild.fetch_emoji()
and having themanage_emojis
permission.- Type:
Optional[
User
]
- property url
Returns the asset of the emoji.
This is equivalent to calling
url_as()
with the default parameters (i.e. png/gif detection).- Type:
- property roles
A
list
of roles that is allowed to use this emoji.If roles is empty, the emoji is unrestricted.
- Type:
List[
Role
]
- url_as(*, format=None, static_format='png')
Returns an
Asset
for the emoji’s url.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’. ‘gif’ is only valid for animated emojis.
New in version 1.6.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the emojis to. If the format isNone
, then it is automatically detected as either ‘gif’ or static_format, depending on whether the emoji is animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated emoji’s to. Defaults to ‘png’
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
.- Returns:
The resulting CDN asset.
- Return type:
- is_usable()
bool
: Whether the bot can use this emoji.New in version 1.3.
- await delete(*, reason=None)
This function is a coroutine.
Deletes the custom emoji.
You must have
manage_emojis
permission to 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=None, roles=None, reason=None)
This function is a coroutine.
Edits the custom emoji.
You must have
manage_emojis
permission to do this.- Parameters:
- Raises:
Forbidden – You are not allowed to edit emojis.
HTTPException – An error occurred editing the emoji.
PartialEmoji
- class discord.PartialEmoji
Bases:
_EmojiTag
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
None
if the emoji got deleted (e.g. removing a reaction with a deleted emoji).- Type:
Optional[
str
]
- id
The ID of the custom emoji, if applicable.
- Type:
Optional[
int
]
- classmethod from_string(string)
Converts a (custom) emoji as they are in a message into a partial emoji object.
Note
To get them, type a custom emoji into the chat, put an
\
in front of it and send it. You can then use what comes out when you add a reaction or similar.Warning
This does not support the :emoji: format for (standard) emojis
- Returns:
The emoji object if the string was valid.
- Return type:
- is_custom_emoji()
bool
: Checks if this is a custom non-Unicode emoji.
- is_unicode_emoji()
bool
: Checks if this is a Unicode emoji.
- 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 asset of the emoji, if it is custom.
This is equivalent to calling
url_as()
with the default parameters (i.e. png/gif detection).- Type:
- url_as(*, format=None, static_format='png')
Returns an
Asset
for the emoji’s url, if it is custom.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’. ‘gif’ is only valid for animated emojis.
New in version 1.7.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the emojis to. If the format isNone
, then it is automatically detected as either ‘gif’ or static_format, depending on whether the emoji is animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated emoji’s to. Defaults to ‘png’
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
.- Returns:
The resulting CDN asset.
- Return type:
Role
- asyncdelete
- asyncedit
- deficon_url_as
- defis_bot_managed
- defis_default
- defis_integration
- defis_premium_subscriber
- class discord.Role
Bases:
Hashable
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.
- icon
The role-icon hash
- Type:
Optional[
str
]
- unicode_emoji
The unicode emoji of the role (shows as role-icon)
- Type:
Optional[
str
]
- position
The position of the role. This number is usually positive. The bottom role has a position of 0.
- Type:
- managed
Indicates if the role is managed by the guild through some form of integrations such as Twitch.
- Type:
- tags
The role tags associated with this role.
- Type:
Optional[
RoleTags
]
- is_default()
bool
: Checks if the role is the default role.
- is_bot_managed()
bool
: Whether the role is associated with a bot.New in version 1.6.
bool
: Whether the role is the premium subscriber, AKA “boost”, role for the guild.New in version 1.6.
- is_integration()
bool
: Whether the role is managed by an integration.New in version 1.6.
- property members
Returns all the members with this role.
- Type:
List[
Member
]
- icon_url_as(*, format='webp', size=1024)
Returns an
Asset
for the role icon.The format must be one of ‘webp’, ‘jpeg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- await edit(*, reason=None, **fields)
This function is a coroutine.
Edits the role.
You must have the
manage_roles
permission to use this.All fields are optional.
Changed in version 1.4: Can now pass
int
tocolour
keyword-only parameter.- 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.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.unicode_emoji (
str
) – The new role-icon as a unicode-emoji This is only available for guilds that containROLE_ICON
inGuild.features
.icon (
bytes
) – A bytes-like object representing the new role-icon. Only PNG/JPEG is supported. This is only available for guilds that containROLE_ICON
inGuild.features
. Could beNone
to denote removal of the icon.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.
InvalidArgument – An invalid position was given or the default role was asked to be moved.
- await delete(*, reason=None)
This function is a coroutine.
Deletes the role.
You must have the
manage_roles
permission to use 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.
TextChannel
- asyncarchived_threads
- asyncclone
- asynccreate_invite
- asynccreate_thread
- asynccreate_webhook
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_message
- asyncfollow
- defget_partial_message
- defget_thread
- defhistory
- asyncinvites
- defis_news
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncpins
- asyncpurge
- asyncsend
- asyncset_permissions
- asynctrigger_typing
- deftyping
- asyncwebhooks
- class discord.TextChannel
Bases:
Messageable
,GuildChannel
,Hashable
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.
- category_id
The category channel ID this channel belongs to, if applicable.
- Type:
Optional[
int
]
- topic
The channel’s topic.
None
if it doesn’t exist.- Type:
Optional[
str
]
- icon_emoji
The channel’s icon-emoji, if set.
- Type:
Optional[
PartialEmoji
]