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”.
Added 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”.
Added 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()
.Added in version 2.0.
- Type:
Optional[
str
]
- avatar_decoration
The avatar decoration hash the user has. Could be None.
Added 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.
Added 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.Added 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
.Added in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.Added 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.
Added 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.Added 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()
.Added 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.Added in version 1.4.
spoiler (
bool
) –Whether the file is a spoiler.
Added 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.Added 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.Added 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.
Added in version 1.6.
- Type:
List[
Sticker
]
- interaction
The interaction this message is a response to, if any.
Added 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.Added 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.
Added 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.Added 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.Added 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.
Added 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.Added 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
.Added 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.Added 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.Added 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.Added 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
.Added 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.
Added 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.Added 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_automod_rule
- 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.
Added 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.Added 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.
Added 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
.Added 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
.Added 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
.Added 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.
Added in version 1.6.
- Type:
Optional[
Role
]
- property self_role
Gets the role associated with this client’s user, if any.
Added 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:
- property discovery_splash_url
Returns the guild’s discovery splash asset.
Added in version 1.3.
- 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.
Added 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.Added 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.Added 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.
Added 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.Added 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.Added 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.Added 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.Added 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.Added 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.Added 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.Added 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).
Added 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.
Added 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.
Added 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
.Added 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.
Added 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.
Added 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.
Added 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.
Added 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.
Added 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 fetch_automod_rule(rule_id)
This function is a coroutine.
Fetches a Auto Moderation rule for this guild by their ID
- Raises:
Forbidden – You do not have permissions to fetch the rule.
HTTPException – Fetching the rule failed.
- Returns:
The AutoMod rule
- Return type:
- 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.
Added 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.
Added 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.
Added 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.
Added 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
.Added 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.Added 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
.Added in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.Added 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.
Added 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.
Added 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.
Added in version 1.3.
- Type:
- suppress
Indicates if the user is suppressed from speaking.
Only applies to stage channels.
Added 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.
Added 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.
Added 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.Added 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.
Added 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.
Added 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.Added in version 1.6.
bool
: Whether the role is the premium subscriber, AKA “boost”, role for the guild.Added in version 1.6.
- is_integration()
bool
: Whether the role is managed by an integration.Added 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
]
- position
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type:
- last_message_id
The last message ID of the message sent to this channel. It may not point to an existing or valid message.
- Type:
Optional[
int
]
- slowmode_delay
The number of seconds a member must wait between sending messages in this channel. A value of 0 denotes that it is disabled. Bots and users with
manage_channels
ormanage_messages
bypass slowmode.- Type:
- async for ... in await archived_threads(*, private=False, joined_private=True, before=None, limit=100)
This function is a coroutine.
Returns an
abc.AsyncIterator
to retrieve archived threads from this channel.- Parameters:
private (
bool
) – Whether to fetch all private threads instead of public ones. Defaults toFalse
.joined_private (
bool
) –Whether to only fetch private threads the bot has joined. Defaults to
True
.Note
The
manage_threads()
permission is required in order to fetch not-joined private threads.before (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Only fetch threads created before this date or ID.limit (
int
) – The maximum number of threads to fetch. Defaults to100
.
- Raises:
Forbidden – The bot lacks permissions to fetch not-joined private threads.
HTTPException – Fetching the threads failed.
- Returns:
An iterator to retrieve the archived threads.
- Return type:
ArchivedThreadIterator
- 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!')
- get_thread(id)
Optional[
ThreadChannel
]: Returns the cached thread in this channel with the given ID if any, elseNone
- property threads
Returns a list of cached threads for this channel
- Type:
List[
ThreadChannel
]
- permissions_for(member, /)
Handles permission resolution for the current
Member
.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
- Parameters:
member (
Member
) – The member to resolve permissions for.- Returns:
The resolved permissions for the member.
- Return type:
- property members
Returns all members that can see this channel.
- Type:
List[
Member
]
- is_nsfw()
bool
: Checks if the channel is NSFW.
- is_news()
bool
: Checks if the channel is a news channel.
- property last_message
Fetches the last message from this channel in cache.
The message might not be valid or point to an existing message.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either
history()
orfetch_message()
with thelast_message_id
attribute.- Returns:
The last message in this channel or
None
if not found.- Return type:
Optional[
Message
]
- await edit(*, reason=None, **options)
This function is a coroutine.
Edits the channel.
You must have the
manage_channels
permission to use this.Changed in version 1.3: The
overwrites
keyword-only parameter was added.Changed in version 1.4: The
type
keyword-only parameter was added.- Parameters:
name (
str
) – The new channel name.topic (
str
) – The new channel’s topic.position (
int
) – The new channel’s position.nsfw (
bool
) – To mark the channel as NSFW or not.sync_permissions (
bool
) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse
.category (Optional[
CategoryChannel
]) – The new category for this channel. Can beNone
to remove the category.slowmode_delay (
int
) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600.type (
ChannelType
) – Change the type of this text channel. Currently, only conversion betweenChannelType.text
andChannelType.news
is supported. This is only available to guilds that containNEWS
inGuild.features
.reason (Optional[
str
]) – The reason for editing this channel. Shows up on the audit log.overwrites (
dict
) – Adict
of target (either a role or a member) toPermissionOverwrite
to apply to the channel.
- Raises:
InvalidArgument – If position is less than 0 or greater than the number of channels, or if the permission overwrite information is not in proper form.
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
- await clone(*, name=None, reason=None)
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channels
permission to do this.Added in version 1.1.
- Parameters:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- await delete_messages(messages, reason=None)
This function is a coroutine.
Deletes a list of messages. This is similar to
Message.delete()
except it bulk deletes multiple messages.As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have the
manage_messages
permission to use this.Usable only by bot accounts.
- Parameters:
messages (Iterable[
abc.Snowflake
]) – An iterable of messages denoting which ones to bulk delete.reason (Optional[
str
]) – The reason for deleting these messages. Shows up on the audit log.
- Raises:
ClientException – The number of messages to delete was more than 100.
Forbidden – You do not have proper permissions to delete the messages or you’re not using a bot account.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- await purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check
. If acheck
is not provided then all messages are deleted without discrimination.You must have the
manage_messages
permission to delete messages even if they are your own (unless you are a user account). Theread_message_history
permission is also needed to retrieve message history.Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.
Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await channel.purge(limit=100, check=is_me) await channel.send('Deleted {} message(s)'.format(len(deleted)))
- Parameters:
limit (Optional[
int
]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message
],bool
]) – The function used to check if a message should be deleted. It must take aMessage
as its sole parameter.before (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asbefore
inhistory()
.after (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asafter
inhistory()
.around (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asaround
inhistory()
.oldest_first (Optional[
bool
]) – Same asoldest_first
inhistory()
.bulk (
bool
) – IfTrue
, use bulk delete. Setting this toFalse
is useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages
. WhenTrue
, will fall back to single delete if current account is a user bot (now deprecated), or if messages are older than two weeks.reason (Optional[
str
]) – The reason for deleting the messages. Shows up on the audit log.
- Raises:
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
- Returns:
The list of messages that were deleted.
- Return type:
List[
Message
]
- await webhooks()
This function is a coroutine.
Gets the list of webhooks from this channel.
Requires
manage_webhooks
permissions.
- await create_webhook(*, name, avatar=None, reason=None)
This function is a coroutine.
Creates a webhook for this channel.
Requires
manage_webhooks
permissions.Changed in version 1.1: Added the
reason
keyword-only parameter.- Parameters:
name (
str
) – The webhook’s name.avatar (Optional[
bytes
]) – A bytes-like object representing the webhook’s default avatar. This operates similarly toedit()
.reason (Optional[
str
]) – The reason for creating this webhook. Shows up in the audit logs.
- Raises:
HTTPException – Creating the webhook failed.
Forbidden – You do not have permissions to create a webhook.
- Returns:
The created webhook.
- Return type:
- await follow(*, destination, reason=None)
Follows a channel using a webhook.
Only news channels can be followed.
Note
The webhook returned will not provide a token to do webhook actions, as Discord does not provide it.
Added in version 1.3.
- Parameters:
destination (
TextChannel
) – The channel you would like to follow from.reason (Optional[
str
]) –The reason for following the channel. Shows up on the destination guild’s audit log.
Added in version 1.4.
- Raises:
HTTPException – Following the channel failed.
Forbidden – You do not have the permissions to create a webhook.
- Returns:
The created webhook.
- Return type:
- get_partial_message(message_id)
Creates a
PartialMessage
from the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
Added in version 1.6.
- Parameters:
message_id (
int
) – The message ID to create a partial message for.- Returns:
The partial message.
- Return type:
- await create_thread(name, auto_archive_duration=None, slowmode_delay=0, private=False, invitable=True, *, reason=None)
This function is a coroutine.
Creates a new thread in this channel.
You must have the
create_public_threads
, or for privatecreate_private_threads
permission to use this.- 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)private (
bool
) – Whether to create a private threadinvitable (
bool
) – For private-threads Whether non-moderators can add new members to the thread, default :obj`True`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 of
AutoArchiveDuration
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:
- property category
The category this channel belongs to.
If there is no category then this is
None
.- Type:
Optional[
CategoryChannel
]
- property changed_roles
Returns a list of roles that have been overridden from their default values in the
roles
attribute.- Type:
List[
Role
]
- await create_invite(*, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, reason=None)
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invite
permission to do this.- Parameters:
max_age (Optional[
int
]) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0
.max_uses (Optional[
int
]) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0
.temporary (Optional[
bool
]) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse
.unique (Optional[
bool
]) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalse
then it will return a previously created invite.target_type (Optional[
InviteTargetType
]) –The type of target for this voice channel invite, if any.
Added in version 2.0.
target_user (Optional[
int
]) –The user whose stream to display for this invite, required if target_type is
TargetType.stream
. The user must be streaming in the channel.Added in version 2.0.
target_application_id (Optional[
int
]) –The id of the embedded application to open for this invite, required if target_type is
InviteTargetType.embeded_application
, the application must have the EMBEDDED flag.Added in version 2.0.
target_event (Optional[
GuildScheduledEvent
]) –The scheduled event object to link to the event. Shortcut to
Invite.set_scheduled_event()
See
Invite.set_scheduled_event()
for more info on event invite linking.Added in version 2.0.
reason (Optional[
str
]) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The invite that was created.
- Return type:
- await delete(*, reason=None)
This function is a coroutine.
Deletes the channel.
You must have
manage_channels
permission to use this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await fetch_message(id, /)
This function is a coroutine.
Retrieves a single
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:
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channels
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
]
- property jump_url
Returns a URL that allows the client to jump to the referenced channel.
Added in version 2.0.
- Type:
- await move(*, beginning=False, end=False, before=MISSING, after=MISSING, offset=0, category=MISSING, sync_permissions=False, reason=None)
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
edit()
should be used instead.You must have the
manage_channels
permission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
Added in version 1.7.
- Parameters:
beginning (
bool
) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend
,before
, andafter
.end (
bool
) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning
,before
, andafter
.before (
Snowflake
) – The channel that should be before our current channel. This is mutually exclusive withbeginning
,end
, andafter
.after (
Snowflake
) – The channel that should be after our current channel. This is mutually exclusive withbeginning
,end
, andbefore
.offset (
int
) – The number of channels to offset the move by. For example, an offset of2
withbeginning=True
would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning
,end
,before
, andafter
parameters.category (Optional[
Snowflake
]) – The category to move this channel under. IfNone
is given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool
) – Whether to sync the permissions with the category (if given).reason (
str
) – The reason for the move.
- Raises:
InvalidArgument – An invalid position was given or a bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- property overwrites
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Role
or aMember
and the value is the overwrite as aPermissionOverwrite
.- Returns:
The channel’s permission overwrites.
- Return type:
Mapping[Union[
Role
,Member
],PermissionOverwrite
]
- overwrites_for(obj)
Returns the channel-specific overwrites for a member or a role.
- property permissions_synced
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False
.Added in version 1.3.
- Type:
- await pins()
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
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.Added 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
.Added in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.Added 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.
Added 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 set_permissions(target, *, overwrite=MISSING, reason=None, **permissions)
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
target
parameter should either be aMember
or aRole
that belongs to guild.The
overwrite
parameter, if given, must either beNone
orPermissionOverwrite
. For convenience, you can pass in keyword arguments denotingPermissions
attributes. If this is done, then you cannot mix the keyword arguments with theoverwrite
parameter.If the
overwrite
parameter isNone
, then the permission overwrites are deleted.You must have the
manage_roles
permission to use this.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwrite
overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (Union[
Member
,Role
]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite
]) – The permissions to allow and deny to the target, orNone
to delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite
.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
InvalidArgument – The overwrite parameter invalid or the target type was not
Role
orMember
.
- 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.
ThreadChannel
- asyncadd_member
- asynccreate_invite
- asyncdelete
- asyncdelete_messages
- asyncedit
- deffetch_members
- asyncfetch_message
- defget_member
- defhistory
- asyncinvites
- defis_nsfw
- asyncjoin
- asyncleave
- defpermissions_for
- asyncpins
- asyncpurge
- asyncremove_member
- asyncsend
- asynctrigger_typing
- deftyping
- class discord.ThreadChannel
Bases:
Messageable
,Hashable
Represents a thread in a guild
- 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!')
- async for ... in fetch_members(limit=100, after=None)
Returns a
ThreadMemberIterator
that allows to retrieve the currently joined members of this thread.Note
This requires the
members()
intent to be enabled and will also add the members retrieved tomembers
Examples
Usage
print(f"The thread {channel.name} has the following members:\n") async for member in thread.fetch_members(limit=200): print(member)
Flattening into a list
messages = await thread.fetch_members(limit=123).flatten() # messages is now a list of ThreadMember...
All parameters are optional.
- Parameters:
limit (
int
) – The limit of thread members to retrieve - defaults to 100after (Union[
int
,datetime.datetime
]) – Get thread members after this user ID
- Raises:
ClientException – The
members
intent is not enabled.- Yields:
ThreadMember
– A member of this thread
- property starter_message
The starter message of this thread if it was started from a message and the message is cached
- Type:
Optional[
Message
]
- property owner
Returns the owner(creator) of the thread. Depending on whether the associated guild member is cached, this returns the
Member
instead of theThreadMember
Note
If the thread members are not fetched (can be done manually using
fetch_members()
) and the guild member is not cached, this returnsNone
.- Returns:
The thread owners’ Member if cached, else the respective ThreadMember.
- Return type:
Optional[Union[
Member
,ThreadMember
]]
- property members
Returns a list with cached members of this thread
- Type:
List[
Member
]
- property locked
Whether the threads conversation is locked by a moderator. If so, the thread can only be unarchived by a moderator
- Type:
- property auto_archive_duration
The duration after which the thread will auto hide from the channel list
- Type:
AutoArchiveDuration
- property invitable
Private threads only: When
True
only the owner of the thread and members withmanage_threads
permissions can add new members- Return type:
- property archive_time
When the thread’s archive status was last changed, used for calculating recent activity
- Type:
Optional[
datetime
]
- property me
The thread member of the bot, or
None
if he is not a member of the thread.- Type:
Optional[
ThreadMember
]
- property parent_channel
The parent channel of this thread
- Type:
Union[
TextChannel
,ForumChannel
]
- property category_id
The ID of the threads parent channel category, if any
- Type:
Optional[
int
]
- property created_at
An aware timestamp of when the thread was created in UTC.
Note
This timestamp only exists for threads created after 9 January 2022, otherwise returns
None
.- Type:
Optional[
datetime.datetime
]
- get_member(id)
ThreadMember
: Returns the thread member with the given ID, orNone
if he is not a member of the thread.
- permissions_for(member)
Handles permission resolution for the current
Member
.Note
threads inherit their permissions from their parent channel.
This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
- Parameters:
member (
Member
) – The member to resolve permissions for.- Returns:
The resolved permissions for the member.
- Return type:
- is_nsfw()
bool
: Whether the parent channel of this thread has NSFW enabled.
- await join()
This function is a coroutine.
Adds the current user to the thread.
Note
Also requires the thread is not archived.
This will fire a
discord.thread_members_update()
event.
- await leave()
This function is a coroutine.
Removes the current user from the thread.
Note
Also requires the thread is not archived.
This will fire a
discord.thread_members_update()
event.
- await add_member(member)
This function is a coroutine.
Adds another member to the thread.
Note
Requires the ability to send messages in the thread.
Also requires the thread is not archived.
This will fire a
thread_members_update
event.- Parameters:
member (Union[
discord.Member
,int
]) – The member that should be added to the thread; could be adiscord.Member
or hisid
(e.g. anint
)
- await remove_member(member)
This function is a coroutine.
Removes a member from the thread.
Note
This requires the
MANAGE_THREADS
permission, or to be the creator of the thread if it is aPRIVATE_THREAD
.Also requires the thread is not archived.
This will fire a
thread_members_update
event.- Parameters:
member (Union[
discord.Member
,int
]) – The member that should be removed from the thread; could be adiscord.Member
or hisid
(e.g. anint
)
- await delete(*, reason=None)
This function is a coroutine.
Deletes the thread channel.
The bot must have
manage_channels
permission to use this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this thread. Shows up on the audit log.- Raises:
Forbidden – The bot is missing permissions to delete the thread.
NotFound – The thread was not found or was already deleted.
HTTPException – Deleting the thread failed.
- await create_invite(*, reason=None, **fields)
This function is a coroutine.
Creates an instant invite from this thread.
You must have the
create_instant_invite
permission to do this.- Parameters:
max_age (
int
) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0
.max_uses (
int
) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0
.temporary (
bool
) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse
.unique (
bool
) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalse
then it will return a previously created invite.reason (Optional[
str
]) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
- Returns:
The invite that was created.
- Return type:
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from this thread.
You must have
manage_channels
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 edit(*, name=MISSING, archived=MISSING, auto_archive_duration=MISSING, locked=MISSING, invitable=MISSING, slowmode_delay=MISSING, reason=None)
This function is a coroutine.
Edits the thread. In order to unarchive it, you must already be a member of it.
- Parameters:
name (Optional[
str
]) – The channel name. Must be 1-100 characters longauto_archive_duration (Optional[
AutoArchiveDuration
]) – Duration in minutes to automatically archive the thread after recent activityarchived (Optional[
bool
]) – Whether the thread is archivedlocked (Optional[
bool
]) – Whether the thread is locked; when a thread is locked, only users withPermissions.manage_threads
can unlock itinvitable (Optional[
bool
]) – Whether non-moderators can add other non-moderators to a thread; only available on private threadsslowmode_delay (:Optional[
int
]) – Amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permissionPermissions.manage_messages
,Permissions.manage_thread
, orPermissions.manage_channel
, are unaffectedreason (Optional[
str
]) – The reason for editing the channel. Shows up on the audit log.
- Raises:
InvalidArgument: – The
auto_archive_duration
is not a valid member ofAutoArchiveDuration
Forbidden: – The bot missing permissions to edit the thread or the specific field
HTTPException: – Editing the thread failed
- Returns:
The updated thread on success
- Return type:
- await delete_messages(messages, *, reason=None)
This function is a coroutine.
Deletes a list of messages. This is similar to
Message.delete()
except it bulk deletes multiple messages.As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have the
manage_messages
permission to use this.Usable only by bot accounts.
- Parameters:
messages (Iterable[
abc.Snowflake
]) – An iterable of messages denoting which ones to bulk delete.reason (Optional[
str
]) – The reason for deleting these messages. Shows up on the audit log.
- Raises:
ClientException – The number of messages to delete was more than 100.
Forbidden – You do not have proper permissions to delete the messages or you’re not using a bot account.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- await purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check
. If acheck
is not provided then all messages are deleted without discrimination.You must have the
manage_messages
permission to delete messages even if they are your own (unless you are a user account). Theread_message_history
permission is also needed to retrieve message history.Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.
Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await channel.purge(limit=100, check=is_me) await channel.send('Deleted {} message(s)'.format(len(deleted)))
- Parameters:
limit (Optional[
int
]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message
],bool
]) – The function used to check if a message should be deleted. It must take aMessage
as its sole parameter.before (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asbefore
inhistory()
.after (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asafter
inhistory()
.around (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asaround
inhistory()
.oldest_first (Optional[
bool
]) – Same asoldest_first
inhistory()
.bulk (
bool
) – IfTrue
, use bulk delete. Setting this toFalse
is useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages
. WhenTrue
, will fall back to single delete if current account is a user bot (now deprecated), or if messages are older than two weeks.reason (Optional[
str
]) – The reason for deleting the messages. Shows up on the audit log.
- Raises:
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
- Returns:
The list of messages that were deleted.
- Return type:
List[
Message
]
- await 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:
- 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.Added 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
.Added in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.Added 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.
Added 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.
ThreadMember
- defpermissions_in
- asyncsend
- class discord.ThreadMember
Bases:
object
Represents a minimal
Member
that has joined aThreadChannel
orForumPost
- property as_guild_member
Returns the full guild member for the thread member if cached else
None
- Type:
Optional[
Member
]
- await send(*args, **kwargs)
A shortcut to
Member.send()
- permissions_in(channel)
A shorthand method to
Member.permissions_in()
- Raises:
TypeError – The associated guild member is not cached
VoiceChannel
- asyncclone
- asyncconnect
- asynccreate_invite
- asynccreate_webhook
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_message
- defhistory
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncpins
- asyncpurge
- asyncsend
- asyncset_permissions
- asynctrigger_typing
- deftyping
- asyncwebhooks
- class discord.VoiceChannel
Bases:
VocalGuildChannel
,Messageable
Represents a Discord guild voice channel.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns the channel’s name.
- category_id
The category channel ID this channel belongs to, if applicable.
- Type:
Optional[
int
]
- position
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type:
- icon_emoji
The channel’s icon-emoji, if set.
- Type:
Optional[
PartialEmoji
]
- rtc_region
The region for the voice channel’s voice communication. A value of
None
indicates automatic voice region detection.Added in version 1.7.
- Type:
Optional[
VoiceRegion
]
- slowmode_delay
The channel’s slowmode delay in seconds. A value of
0
indicates that slowmode is disabled.Added in version 2.0.
- Type:
- 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 status
The current channel “status” (0-500 characters) if any.
- Type:
Optional[
str
]
- await clone(*, name=None, reason=None)
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channels
permission to do this.Added in version 1.1.
- Parameters:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- await edit(*, reason=None, **options)
This function is a coroutine.
Edits the channel.
You must have the
manage_channels
permission to use this.Changed in version 1.3: The
overwrites
keyword-only parameter was added.- Parameters:
name (
str
) – The new channel’s name.bitrate (
int
) – The new channel’s bitrate.user_limit (
int
) – The new channel’s user limit.position (
int
) – The new channel’s position.sync_permissions (
bool
) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse
.category (Optional[
CategoryChannel
]) – The new category for this channel. Can beNone
to remove the category.reason (Optional[
str
]) – The reason for editing this channel. Shows up on the audit log.overwrites (
dict
) – Adict
of target (either a role or a member) toPermissionOverwrite
to apply to the channel.rtc_region (Optional[
VoiceRegion
]) –The new region for the voice channel’s voice communication. A value of
None
indicates automatic voice region detection.Added in version 1.7.
slowmode_delay (
int
) –The new slowmode delay for this channel in seconds. A value of
0
disables slowmode.Added in version 2.0.
nsfw (
bool
) – Whether the channel is NSFW. This can only be set by guild administrators.icon_emoji (Optional[
PartialEmoji
]) – The channels new icon-emoji. Note that custom emojis are only allowed when the guild has boost level 2 or higher.
- Raises:
InvalidArgument – If the permission overwrite information is not in proper form.
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
- property category
The category this channel belongs to.
If there is no category then this is
None
.- Type:
Optional[
CategoryChannel
]
- property changed_roles
Returns a list of roles that have been overridden from their default values in the
roles
attribute.- Type:
List[
Role
]
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)
This function is a coroutine.
Connects to voice and creates a
VoiceClient
to establish your connection to the voice server.- Parameters:
timeout (
float
) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool
) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (Type[
VoiceProtocol
]) – A type that subclassesVoiceProtocol
to connect with. Defaults toVoiceClient
.
- Raises:
asyncio.TimeoutError – Could not connect to the voice channel in time.
ClientException – You are already connected to a voice channel.
OpusNotLoaded – The opus library has not been loaded.
- Returns:
A voice client that is fully connected to the voice server.
- Return type:
- await create_invite(*, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, reason=None)
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invite
permission to do this.- Parameters:
max_age (Optional[
int
]) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0
.max_uses (Optional[
int
]) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0
.temporary (Optional[
bool
]) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse
.unique (Optional[
bool
]) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalse
then it will return a previously created invite.target_type (Optional[
InviteTargetType
]) –The type of target for this voice channel invite, if any.
Added in version 2.0.
target_user (Optional[
int
]) –The user whose stream to display for this invite, required if target_type is
TargetType.stream
. The user must be streaming in the channel.Added in version 2.0.
target_application_id (Optional[
int
]) –The id of the embedded application to open for this invite, required if target_type is
InviteTargetType.embeded_application
, the application must have the EMBEDDED flag.Added in version 2.0.
target_event (Optional[
GuildScheduledEvent
]) –The scheduled event object to link to the event. Shortcut to
Invite.set_scheduled_event()
See
Invite.set_scheduled_event()
for more info on event invite linking.Added in version 2.0.
reason (Optional[
str
]) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The invite that was created.
- Return type:
- await create_webhook(*, name, avatar=None, reason=None)
This function is a coroutine.
Creates a webhook for this channel.
Requires
manage_webhooks
permissions.Changed in version 1.1: Added the
reason
keyword-only parameter.- Parameters:
name (
str
) – The webhook’s name.avatar (Optional[
bytes
]) – A bytes-like object representing the webhook’s default avatar. This operates similarly toedit()
.reason (Optional[
str
]) – The reason for creating this webhook. Shows up in the audit logs.
- Raises:
HTTPException – Creating the webhook failed.
Forbidden – You do not have permissions to create a webhook.
- Returns:
The created webhook.
- Return type:
- await delete(*, reason=None)
This function is a coroutine.
Deletes the channel.
You must have
manage_channels
permission to use this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await delete_messages(messages, *, reason=None)
This function is a coroutine.
Deletes a list of messages. This is similar to
Message.delete()
except it bulk deletes multiple messages.As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have the
manage_messages
permission to use this.Usable only by bot accounts.
- Parameters:
messages (Iterable[
abc.Snowflake
]) – An iterable of messages denoting which ones to bulk delete.reason (Optional[
str
]) – The reason for deleting these messages. Shows up on the audit log.
- Raises:
ClientException – The number of messages to delete was more than 100.
Forbidden – You do not have proper permissions to delete the messages or you’re not using a bot account.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- 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:
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channels
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
]
- is_nsfw()
bool
: Checks if the channel is NSFW.
- property jump_url
Returns a URL that allows the client to jump to the referenced channel.
Added in version 2.0.
- Type:
- property members
Returns all members that are currently inside this voice channel.
- Type:
List[
Member
]
- await move(*, beginning=False, end=False, before=MISSING, after=MISSING, offset=0, category=MISSING, sync_permissions=False, reason=None)
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
edit()
should be used instead.You must have the
manage_channels
permission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
Added in version 1.7.
- Parameters:
beginning (
bool
) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend
,before
, andafter
.end (
bool
) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning
,before
, andafter
.before (
Snowflake
) – The channel that should be before our current channel. This is mutually exclusive withbeginning
,end
, andafter
.after (
Snowflake
) – The channel that should be after our current channel. This is mutually exclusive withbeginning
,end
, andbefore
.offset (
int
) – The number of channels to offset the move by. For example, an offset of2
withbeginning=True
would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning
,end
,before
, andafter
parameters.category (Optional[
Snowflake
]) – The category to move this channel under. IfNone
is given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool
) – Whether to sync the permissions with the category (if given).reason (
str
) – The reason for the move.
- Raises:
InvalidArgument – An invalid position was given or a bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- property overwrites
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Role
or aMember
and the value is the overwrite as aPermissionOverwrite
.- Returns:
The channel’s permission overwrites.
- Return type:
Mapping[Union[
Role
,Member
],PermissionOverwrite
]
- overwrites_for(obj)
Returns the channel-specific overwrites for a member or a role.
- permissions_for(member, /)
Handles permission resolution for the current
Member
.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
- Parameters:
member (
Member
) – The member to resolve permissions for.- Returns:
The resolved permissions for the member.
- Return type:
- property permissions_synced
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False
.Added in version 1.3.
- Type:
- await pins()
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
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 purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check
. If acheck
is not provided then all messages are deleted without discrimination.You must have the
manage_messages
permission to delete messages even if they are your own (unless you are a user account). Theread_message_history
permission is also needed to retrieve message history.Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.
Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await channel.purge(limit=100, check=is_me) await channel.send('Deleted {} message(s)'.format(len(deleted)))
- Parameters:
limit (Optional[
int
]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message
],bool
]) – The function used to check if a message should be deleted. It must take aMessage
as its sole parameter.before (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asbefore
inhistory()
.after (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asafter
inhistory()
.around (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asaround
inhistory()
.oldest_first (Optional[
bool
]) – Same asoldest_first
inhistory()
.bulk (
bool
) – IfTrue
, use bulk delete. Setting this toFalse
is useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages
. WhenTrue
, will fall back to single delete if current account is a user bot (now deprecated), or if messages are older than two weeks.reason (Optional[
str
]) – The reason for deleting the messages. Shows up on the audit log.
- Raises:
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
- Returns:
The list of messages that were deleted.
- Return type:
List[
Message
]
- await 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.Added 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
.Added in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.Added 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.
Added 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 set_permissions(target, *, overwrite=MISSING, reason=None, **permissions)
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
target
parameter should either be aMember
or aRole
that belongs to guild.The
overwrite
parameter, if given, must either beNone
orPermissionOverwrite
. For convenience, you can pass in keyword arguments denotingPermissions
attributes. If this is done, then you cannot mix the keyword arguments with theoverwrite
parameter.If the
overwrite
parameter isNone
, then the permission overwrites are deleted.You must have the
manage_roles
permission to use this.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwrite
overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (Union[
Member
,Role
]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite
]) – The permissions to allow and deny to the target, orNone
to delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite
.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
InvalidArgument – The overwrite parameter invalid or the target type was not
Role
orMember
.
- 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.
- property voice_states
Returns a mapping of member IDs who have voice states in this channel.
Added in version 1.3.
Note
This function is intentionally low level to replace
members
when the member cache is unavailable.- Returns:
The mapping of member ID to a voice state.
- Return type:
Mapping[
int
,VoiceState
]
- await webhooks()
This function is a coroutine.
Gets the list of webhooks from this channel.
Requires
manage_webhooks
permissions.
StageChannel
- asyncclone
- asyncconnect
- asynccreate_invite
- asynccreate_webhook
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_message
- defget_instance
- defhistory
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncpins
- asyncpurge
- asyncsend
- asyncset_permissions
- asyncstart_instance
- asynctrigger_typing
- deftyping
- asyncwebhooks
- class discord.StageChannel
Bases:
VocalGuildChannel
,Messageable
Represents a Discord guild stage channel.
Added in version 1.7.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns the channel’s name.
- topic
The channel’s topic.
None
if it isn’t set.- Type:
Optional[
str
]
- icon_emoji
The channel’s icon-emoji, if set.
- Type:
Optional[
PartialEmoji
]
- category_id
The category channel ID this channel belongs to, if applicable.
- Type:
Optional[
int
]
- position
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type:
- rtc_region
The region for the stage channel’s voice communication. A value of
None
indicates automatic voice region detection.- Type:
Optional[
VoiceRegion
]
- slowmode_delay
The channel’s slowmode delay in seconds. A value of
0
indicates that slowmode is disabled.Added in version 2.0.
- Type:
- property requesting_to_speak
A list of members who are requesting to speak in the stage channel.
- Type:
List[
Member
]
- await clone(*, name=None, reason=None)
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channels
permission to do this.Added in version 1.1.
- Parameters:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- await edit(*, reason=None, **options)
This function is a coroutine.
Edits the channel.
You must have the
manage_channels
permission to use this.- Parameters:
name (
str
) – The new channel’s name.topic (
str
) – The new channel’s topic.icon_emoji (Optional[
PartialEmoji
]) – The new channel’s icon-emoji. Note that custom emojis are only allowed when the guild has boost level 2 or higher.position (
int
) – The new channel’s position.sync_permissions (
bool
) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse
.category (Optional[
CategoryChannel
]) – The new category for this channel. Can beNone
to remove the category.reason (Optional[
str
]) – The reason for editing this channel. Shows up on the audit log.overwrites (
dict
) – Adict
of target (either a role or a member) toPermissionOverwrite
to apply to the channel.rtc_region (Optional[
VoiceRegion
]) – The new region for the stage channel’s voice communication. A value ofNone
indicates automatic voice region detection.
- Raises:
InvalidArgument – If the permission overwrite information is not in proper form.
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
- await start_instance(topic, send_start_notification=False, *, reason=None)
This function is a coroutine. Starts a new stage instance for this stage channel (e.g. make it go live).
You must have the
manage_channels
permission to use this.- Parameters:
topic (
str
) – The topic of the stage instance.send_start_notification (
bool
) –Whether to send a notification to everyone in the guild that the stage is live.
This requires the
mention_everyone
permission.reason (Optional[
str
]) – The reason for starting the stage instance. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to start the stage instance.
HTTPException – Starting the stage instance failed.
- Returns:
The created stage instance.
- Return type:
StageInstance
- property category
The category this channel belongs to.
If there is no category then this is
None
.- Type:
Optional[
CategoryChannel
]
- property changed_roles
Returns a list of roles that have been overridden from their default values in the
roles
attribute.- Type:
List[
Role
]
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)
This function is a coroutine.
Connects to voice and creates a
VoiceClient
to establish your connection to the voice server.- Parameters:
timeout (
float
) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool
) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (Type[
VoiceProtocol
]) – A type that subclassesVoiceProtocol
to connect with. Defaults toVoiceClient
.
- Raises:
asyncio.TimeoutError – Could not connect to the voice channel in time.
ClientException – You are already connected to a voice channel.
OpusNotLoaded – The opus library has not been loaded.
- Returns:
A voice client that is fully connected to the voice server.
- Return type:
- await create_invite(*, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, reason=None)
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invite
permission to do this.- Parameters:
max_age (Optional[
int
]) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0
.max_uses (Optional[
int
]) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0
.temporary (Optional[
bool
]) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse
.unique (Optional[
bool
]) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalse
then it will return a previously created invite.target_type (Optional[
InviteTargetType
]) –The type of target for this voice channel invite, if any.
Added in version 2.0.
target_user (Optional[
int
]) –The user whose stream to display for this invite, required if target_type is
TargetType.stream
. The user must be streaming in the channel.Added in version 2.0.
target_application_id (Optional[
int
]) –The id of the embedded application to open for this invite, required if target_type is
InviteTargetType.embeded_application
, the application must have the EMBEDDED flag.Added in version 2.0.
target_event (Optional[
GuildScheduledEvent
]) –The scheduled event object to link to the event. Shortcut to
Invite.set_scheduled_event()
See
Invite.set_scheduled_event()
for more info on event invite linking.Added in version 2.0.
reason (Optional[
str
]) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The invite that was created.
- Return type:
- await create_webhook(*, name, avatar=None, reason=None)
This function is a coroutine.
Creates a webhook for this channel.
Requires
manage_webhooks
permissions.Changed in version 1.1: Added the
reason
keyword-only parameter.- Parameters:
name (
str
) – The webhook’s name.avatar (Optional[
bytes
]) – A bytes-like object representing the webhook’s default avatar. This operates similarly toedit()
.reason (Optional[
str
]) – The reason for creating this webhook. Shows up in the audit logs.
- Raises:
HTTPException – Creating the webhook failed.
Forbidden – You do not have permissions to create a webhook.
- Returns:
The created webhook.
- Return type:
- await delete(*, reason=None)
This function is a coroutine.
Deletes the channel.
You must have
manage_channels
permission to use this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await delete_messages(messages, *, reason=None)
This function is a coroutine.
Deletes a list of messages. This is similar to
Message.delete()
except it bulk deletes multiple messages.As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have the
manage_messages
permission to use this.Usable only by bot accounts.
- Parameters:
messages (Iterable[
abc.Snowflake
]) – An iterable of messages denoting which ones to bulk delete.reason (Optional[
str
]) – The reason for deleting these messages. Shows up on the audit log.
- Raises:
ClientException – The number of messages to delete was more than 100.
Forbidden – You do not have proper permissions to delete the messages or you’re not using a bot account.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- 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:
- 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.
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channels
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
]
- is_nsfw()
bool
: Checks if the channel is NSFW.
- property jump_url
Returns a URL that allows the client to jump to the referenced channel.
Added in version 2.0.
- Type:
- property members
Returns all members that are currently inside this voice channel.
- Type:
List[
Member
]
- await move(*, beginning=False, end=False, before=MISSING, after=MISSING, offset=0, category=MISSING, sync_permissions=False, reason=None)
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
edit()
should be used instead.You must have the
manage_channels
permission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
Added in version 1.7.
- Parameters:
beginning (
bool
) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend
,before
, andafter
.end (
bool
) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning
,before
, andafter
.before (
Snowflake
) – The channel that should be before our current channel. This is mutually exclusive withbeginning
,end
, andafter
.after (
Snowflake
) – The channel that should be after our current channel. This is mutually exclusive withbeginning
,end
, andbefore
.offset (
int
) – The number of channels to offset the move by. For example, an offset of2
withbeginning=True
would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning
,end
,before
, andafter
parameters.category (Optional[
Snowflake
]) – The category to move this channel under. IfNone
is given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool
) – Whether to sync the permissions with the category (if given).reason (
str
) – The reason for the move.
- Raises:
InvalidArgument – An invalid position was given or a bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- property overwrites
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Role
or aMember
and the value is the overwrite as aPermissionOverwrite
.- Returns:
The channel’s permission overwrites.
- Return type:
Mapping[Union[
Role
,Member
],PermissionOverwrite
]
- overwrites_for(obj)
Returns the channel-specific overwrites for a member or a role.
- permissions_for(member, /)
Handles permission resolution for the current
Member
.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
- Parameters:
member (
Member
) – The member to resolve permissions for.- Returns:
The resolved permissions for the member.
- Return type:
- property permissions_synced
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False
.Added in version 1.3.
- Type:
- await pins()
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
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 purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check
. If acheck
is not provided then all messages are deleted without discrimination.You must have the
manage_messages
permission to delete messages even if they are your own (unless you are a user account). Theread_message_history
permission is also needed to retrieve message history.Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.
Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await channel.purge(limit=100, check=is_me) await channel.send('Deleted {} message(s)'.format(len(deleted)))
- Parameters:
limit (Optional[
int
]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message
],bool
]) – The function used to check if a message should be deleted. It must take aMessage
as its sole parameter.before (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asbefore
inhistory()
.after (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asafter
inhistory()
.around (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asaround
inhistory()
.oldest_first (Optional[
bool
]) – Same asoldest_first
inhistory()
.bulk (
bool
) – IfTrue
, use bulk delete. Setting this toFalse
is useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages
. WhenTrue
, will fall back to single delete if current account is a user bot (now deprecated), or if messages are older than two weeks.reason (Optional[
str
]) – The reason for deleting the messages. Shows up on the audit log.
- Raises:
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
- Returns:
The list of messages that were deleted.
- Return type:
List[
Message
]
- await 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.Added 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
.Added in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.Added 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.
Added 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 set_permissions(target, *, overwrite=MISSING, reason=None, **permissions)
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
target
parameter should either be aMember
or aRole
that belongs to guild.The
overwrite
parameter, if given, must either beNone
orPermissionOverwrite
. For convenience, you can pass in keyword arguments denotingPermissions
attributes. If this is done, then you cannot mix the keyword arguments with theoverwrite
parameter.If the
overwrite
parameter isNone
, then the permission overwrites are deleted.You must have the
manage_roles
permission to use this.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwrite
overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (Union[
Member
,Role
]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite
]) – The permissions to allow and deny to the target, orNone
to delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite
.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
InvalidArgument – The overwrite parameter invalid or the target type was not
Role
orMember
.
- 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.
- 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 voice_states
Returns a mapping of member IDs who have voice states in this channel.
Added in version 1.3.
Note
This function is intentionally low level to replace
members
when the member cache is unavailable.- Returns:
The mapping of member ID to a voice state.
- Return type:
Mapping[
int
,VoiceState
]
- await webhooks()
This function is a coroutine.
Gets the list of webhooks from this channel.
Requires
manage_webhooks
permissions.
ForumChannel
- available_tags
- category
- category_id
- changed_roles
- created_at
- default_auto_archive_duration
- default_forum_layout
- default_reaction_emoji
- default_sort_order
- flags
- guild
- icon_emoji
- id
- jump_url
- last_post
- last_post_id
- members
- mention
- name
- nsfw
- overwrites
- permissions_synced
- position
- post_slowmode_delay
- posts
- slowmode_delay
- template
- topic
- type
- asyncarchived_posts
- asyncclone
- asynccreate_invite
- asynccreate_post
- asynccreate_webhook
- asyncdelete
- asyncedit
- defget_post
- defget_tag
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncset_permissions
- asyncwebhooks
- class discord.ForumChannel
Bases:
GuildChannel
,Hashable
Represents a forum 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
]
- template
The channel’s template.
None
if it doesn’t exist.Currently, this field is only available on some selected guilds.
- Type:
Optional[
str
]
- icon_emoji
The channel’s icon-emoji, if set.
- Type:
Optional[
PartialEmoji
]
- default_reaction_emoji
The default emoji for reacting to a post in this forum
- Type:
Optional[
PartialEmoji
]
- position
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type:
- last_post_id
The ID of the last post that was created in this forum, this may not point to an existing or valid post.
- Type:
Optional[
int
]
- slowmode_delay
The number of seconds a member must wait between sending messages in posts inside this channel. A value of 0 denotes that it is disabled. Bots and users with
manage_channels
ormanage_messages
bypass slowmode.- Type:
- default_auto_archive_duration
The default duration for which threads in this channel are automatically archived.
- Type:
AutoArchiveDuration
- async for ... in await archived_posts(*, before=None, limit=100)
This function is a coroutine.
Returns an
abc.AsyncIterator
to retrieve archived posts from this channel.- Parameters:
before (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Only fetch posts created before this date or ID.limit (
int
) – The maximum number of posts to fetch. Defaults to100
.
- Raises:
Forbidden – The bot lacks permissions to fetch not-joined private posts.
HTTPException – Fetching the posts failed.
- Returns:
An iterator to retrieve the archived threads.
- Return type:
ArchivedThreadIterator
- get_post(id)
Optional[
ForumPost
]: Returns a post in the forum with the given ID. or None when not found.
- property posts
A list of all cached posts in the forum.
- Type:
List[
ForumPost
]
- get_tag(tag_id)
Optional[
ForumTag
]: Returns a tag with the given ID in the forum, orNone
when not found.
- property available_tags
A list of all tags available in the forum.
- Type:
List[
ForumTag
]
- permissions_for(member, /)
Handles permission resolution for the current
Member
.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
- Parameters:
member (
Member
) – The member to resolve permissions for.- Returns:
The resolved permissions for the member.
- Return type:
- property members
Returns all members that can see this channel.
- Type:
List[
Member
]
- is_nsfw()
bool
: Checks if the channel is NSFW.
- property last_post
Fetches the last post from this channel in cache.
The post might not be valid or point to an existing post.
- await edit(*, name=MISSING, topic=MISSING, available_tags=MISSING, tags_required=MISSING, default_post_sort_order=MISSING, default_forum_layout=MISSING, default_reaction_emoji=MISSING, position=MISSING, nsfw=MISSING, sync_permissions=False, category=MISSING, slowmode_delay=MISSING, post_slowmode_delay=MISSING, overwrites=MISSING, icon_emoji=MISSING, reason=None)
This function is a coroutine.
Edits the channel.
You must have the
manage_channels
permission to use this.- Parameters:
name (
str
) – The new channel name.topic (
str
) – The new channel’s topic.available_tags (Sequence[
ForumTag
]) – An iterable of tags to keep as well of new tags. You can use this to reorder the tags.tags_required (
bool
) – Whether new created post require at least one tag provided on creationdefault_post_sort_order (Optional[
PostSortOrder
]) – How the posts in the forum will be sorted for users by default.default_forum_layout (Optional[
ForumLayout
]) – The default forum layout view used to display posts to users.default_reaction_emoji (Optional[
PartialEmoji
]) – The default emoji used to react to posts in the forum.position (
int
) – The new channel’s position.nsfw (
bool
) – To mark the channel as NSFW or not.sync_permissions (
bool
) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse
.category (Optional[
CategoryChannel
]) – The new category for this channel. Can beNone
to remove the category.slowmode_delay (
int
) – The number of seconds (max.21600
) a member must wait between sending messages in posts inside this channel. A value of 0 denotes that it is disabled. Bots and users withmanage_channels
ormanage_messages
bypass slowmode.post_slowmode_delay (
int
) – The number of seconds (max.21600
) a member must wait between creating new posts.overwrites (
dict
) – Adict
of target (either a role or a member) toPermissionOverwrite
to apply to the channel.icon_emoji (Optional[
PartialEmoji
]) – The new icon-emoji for the channel. Note that setting custom emojis require the guild to have boost level 2 or higher.reason (Optional[
str
]) – The reason for editing this channel. Shows up on the audit log.
- Raises:
InvalidArgument – If position is less than 0 or greater than the number of channels, or if the permission overwrite information is not in proper form.
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
- await clone(*, name=None, reason=None)
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channels
permission to do this.Added in version 1.1.
- Parameters:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- await webhooks()
This function is a coroutine.
Gets the list of webhooks from this channel.
Requires
manage_webhooks
permissions.
- await create_webhook(*, name, avatar=None, reason=None)
This function is a coroutine.
Creates a webhook for this channel.
Requires
manage_webhooks
permissions.- Parameters:
name (
str
) – The webhook’s name.avatar (Optional[
bytes
]) – A bytes-like object representing the webhook’s default avatar. This operates similarly toedit()
.reason (Optional[
str
]) – The reason for creating this webhook. Shows up in the audit logs.
- Raises:
HTTPException – Creating the webhook failed.
Forbidden – You do not have permissions to create a webhook.
- Returns:
The created webhook.
- Return type:
- await create_post(*, name, tags=None, content=None, embed=None, embeds=None, components=None, file=None, files=None, allowed_mentions=None, suppress_embeds=False, supress_notifications=False, auto_archive_duration=None, slowmode_delay=0, reason=None)
This function is a coroutine.
Creates a new post in this forum. Requires the
create_posts
permission.- Parameters:
name (
str
) – The name of the post.tags (Optional[List[
ForumTag
]]) – The list of up to 5 tags that should be added to the post. These tags must be from the parent channel (forum).content (
str
) – The content of the post starter-message.embed (Optional[
Embed
]) – A embed of the post starter-message.embeds (List[
Embed
]) – A list of up to 10 embeds to include in the post starter-message.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.file (Optional[class:File]) – A file to include in the post starter-message.
files (List[
File
]) – A list of files to include in the post starter-message.allowed_mentions (Optional[
AllowedMentions
]) – The allowed mentions for the post.suppress_embeds (Optional[
bool
]) – Whether to suppress embeds in the post starter-message.supress_notifications (Optional[
bool
]) –Whether to suppress desktop- & push-notifications for the post starter-message.
Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.
auto_archive_duration (Optional[
AutoArchiveDuration
]) – The duration after the post will be archived automatically when inactive.slowmode_delay (Optional[
int
]) – The amount of seconds a user has to wait before sending another message (0-21600)reason (Optional[
str
]) – The reason for creating this post. Shows up in the audit logs.
- Raises:
InvalidArgument – The forum requires
tags
on post creation but no tags where provided, orname
is of invalid length, orauto_archive_duration
is not of valid type.Forbidden – The bot does not have permissions to create posts in this channel
HTTPException – Creating the post failed
- property category
The category this channel belongs to.
If there is no category then this is
None
.- Type:
Optional[
CategoryChannel
]
- property changed_roles
Returns a list of roles that have been overridden from their default values in the
roles
attribute.- Type:
List[
Role
]
- await create_invite(*, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, reason=None)
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invite
permission to do this.- Parameters:
max_age (Optional[
int
]) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0
.max_uses (Optional[
int
]) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0
.temporary (Optional[
bool
]) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse
.unique (Optional[
bool
]) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalse
then it will return a previously created invite.target_type (Optional[
InviteTargetType
]) –The type of target for this voice channel invite, if any.
Added in version 2.0.
target_user (Optional[
int
]) –The user whose stream to display for this invite, required if target_type is
TargetType.stream
. The user must be streaming in the channel.Added in version 2.0.
target_application_id (Optional[
int
]) –The id of the embedded application to open for this invite, required if target_type is
InviteTargetType.embeded_application
, the application must have the EMBEDDED flag.Added in version 2.0.
target_event (Optional[
GuildScheduledEvent
]) –The scheduled event object to link to the event. Shortcut to
Invite.set_scheduled_event()
See
Invite.set_scheduled_event()
for more info on event invite linking.Added in version 2.0.
reason (Optional[
str
]) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The invite that was created.
- Return type:
- await delete(*, reason=None)
This function is a coroutine.
Deletes the channel.
You must have
manage_channels
permission to use this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channels
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
]
- property jump_url
Returns a URL that allows the client to jump to the referenced channel.
Added in version 2.0.
- Type:
- await move(*, beginning=False, end=False, before=MISSING, after=MISSING, offset=0, category=MISSING, sync_permissions=False, reason=None)
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
edit()
should be used instead.You must have the
manage_channels
permission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
Added in version 1.7.
- Parameters:
beginning (
bool
) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend
,before
, andafter
.end (
bool
) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning
,before
, andafter
.before (
Snowflake
) – The channel that should be before our current channel. This is mutually exclusive withbeginning
,end
, andafter
.after (
Snowflake
) – The channel that should be after our current channel. This is mutually exclusive withbeginning
,end
, andbefore
.offset (
int
) – The number of channels to offset the move by. For example, an offset of2
withbeginning=True
would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning
,end
,before
, andafter
parameters.category (Optional[
Snowflake
]) – The category to move this channel under. IfNone
is given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool
) – Whether to sync the permissions with the category (if given).reason (
str
) – The reason for the move.
- Raises:
InvalidArgument – An invalid position was given or a bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- property overwrites
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Role
or aMember
and the value is the overwrite as aPermissionOverwrite
.- Returns:
The channel’s permission overwrites.
- Return type:
Mapping[Union[
Role
,Member
],PermissionOverwrite
]
- overwrites_for(obj)
Returns the channel-specific overwrites for a member or a role.
- property permissions_synced
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False
.Added in version 1.3.
- Type:
- await set_permissions(target, *, overwrite=MISSING, reason=None, **permissions)
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
target
parameter should either be aMember
or aRole
that belongs to guild.The
overwrite
parameter, if given, must either beNone
orPermissionOverwrite
. For convenience, you can pass in keyword arguments denotingPermissions
attributes. If this is done, then you cannot mix the keyword arguments with theoverwrite
parameter.If the
overwrite
parameter isNone
, then the permission overwrites are deleted.You must have the
manage_roles
permission to use this.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwrite
overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (Union[
Member
,Role
]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite
]) – The permissions to allow and deny to the target, orNone
to delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite
.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
InvalidArgument – The overwrite parameter invalid or the target type was not
Role
orMember
.
ForumPost
- asyncadd_member
- asynccreate_invite
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncedit_tags
- deffetch_members
- asyncfetch_message
- defget_member
- defhistory
- asyncinvites
- defis_nsfw
- asyncjoin
- asyncleave
- defpermissions_for
- asyncpins
- asyncpurge
- asyncremove_member
- asyncsend
- asynctrigger_typing
- deftyping
- class discord.ForumPost
Bases:
ThreadChannel
Represents a post in a
ForumChannel
, this is very similar to aThreadChannel
Added in version 2.0.
- 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!')
- async for ... in fetch_members(limit=100, after=None)
Returns a
ThreadMemberIterator
that allows to retrieve the currently joined members of this thread.Note
This requires the
members()
intent to be enabled and will also add the members retrieved tomembers
Examples
Usage
print(f"The thread {channel.name} has the following members:\n") async for member in thread.fetch_members(limit=200): print(member)
Flattening into a list
messages = await thread.fetch_members(limit=123).flatten() # messages is now a list of ThreadMember...
All parameters are optional.
- Parameters:
limit (
int
) – The limit of thread members to retrieve - defaults to 100after (Union[
int
,datetime.datetime
]) – Get thread members after this user ID
- Raises:
ClientException – The
members
intent is not enabled.- Yields:
ThreadMember
– A member of this thread
- property applied_tags
Returns a list of tags applied to this post.
- Type:
List[
ForumTag
]
- await edit_tags(*tags)
This function is a coroutine.
Edits the tags of the post
- await edit(*, name=MISSING, tags=MISSING, pinned=MISSING, auto_archive_duration=MISSING, archived=MISSING, locked=MISSING, slowmode_delay=MISSING, reason=None)
This function is a coroutine.
Edits the post, all parameters are optional
- Parameters:
name (
str
) – The new name of the posttags (Sequence[
ForumPost
]) – Tags to keep as well as new tags to addpinned (
bool
) –Whether the post is pinned to the top of the parent forum.
Note
Per forum, only one post can be pinned.
auto_archive_duration (
AutoArchiveDuration
) – The new amount of minutes after that the post will stop showing in the channel list afterauto_archive_duration
minutes of inactivity.locked (
bool
) – Whether the post is locked; when a post is locked, only users with :func:~Permissions.manage_threads` permissions can unlock itarchived (
bool
) – Whether the post is archived.slowmode_delay (Optional[
str
]) – Amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffectedreason (Optional[
str
]) – The reason for editing the post, shows up in the audit log.
- await add_member(member)
This function is a coroutine.
Adds another member to the thread.
Note
Requires the ability to send messages in the thread.
Also requires the thread is not archived.
This will fire a
thread_members_update
event.- Parameters:
member (Union[
discord.Member
,int
]) – The member that should be added to the thread; could be adiscord.Member
or hisid
(e.g. anint
)
- property archive_time
When the thread’s archive status was last changed, used for calculating recent activity
- Type:
Optional[
datetime
]
- property auto_archive_duration
The duration after which the thread will auto hide from the channel list
- Type:
AutoArchiveDuration
- property category_id
The ID of the threads parent channel category, if any
- Type:
Optional[
int
]
- await create_invite(*, reason=None, **fields)
This function is a coroutine.
Creates an instant invite from this thread.
You must have the
create_instant_invite
permission to do this.- Parameters:
max_age (
int
) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0
.max_uses (
int
) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0
.temporary (
bool
) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse
.unique (
bool
) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalse
then it will return a previously created invite.reason (Optional[
str
]) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
- Returns:
The invite that was created.
- Return type:
- property created_at
An aware timestamp of when the thread was created in UTC.
Note
This timestamp only exists for threads created after 9 January 2022, otherwise returns
None
.- Type:
Optional[
datetime.datetime
]
- await delete(*, reason=None)
This function is a coroutine.
Deletes the thread channel.
The bot must have
manage_channels
permission to use this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this thread. Shows up on the audit log.- Raises:
Forbidden – The bot is missing permissions to delete the thread.
NotFound – The thread was not found or was already deleted.
HTTPException – Deleting the thread failed.
- await delete_messages(messages, *, reason=None)
This function is a coroutine.
Deletes a list of messages. This is similar to
Message.delete()
except it bulk deletes multiple messages.As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have the
manage_messages
permission to use this.Usable only by bot accounts.
- Parameters:
messages (Iterable[
abc.Snowflake
]) – An iterable of messages denoting which ones to bulk delete.reason (Optional[
str
]) – The reason for deleting these messages. Shows up on the audit log.
- Raises:
ClientException – The number of messages to delete was more than 100.
Forbidden – You do not have proper permissions to delete the messages or you’re not using a bot account.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- 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:
- get_member(id)
ThreadMember
: Returns the thread member with the given ID, orNone
if he is not a member of the thread.
- property invitable
Private threads only: When
True
only the owner of the thread and members withmanage_threads
permissions can add new members- Return type:
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from this thread.
You must have
manage_channels
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
]
- is_nsfw()
bool
: Whether the parent channel of this thread has NSFW enabled.
- await join()
This function is a coroutine.
Adds the current user to the thread.
Note
Also requires the thread is not archived.
This will fire a
discord.thread_members_update()
event.
- await leave()
This function is a coroutine.
Removes the current user from the thread.
Note
Also requires the thread is not archived.
This will fire a
discord.thread_members_update()
event.
- property locked
Whether the threads conversation is locked by a moderator. If so, the thread can only be unarchived by a moderator
- Type:
- property me
The thread member of the bot, or
None
if he is not a member of the thread.- Type:
Optional[
ThreadMember
]
- property members
Returns a list with cached members of this thread
- Type:
List[
Member
]
- property owner
Returns the owner(creator) of the thread. Depending on whether the associated guild member is cached, this returns the
Member
instead of theThreadMember
Note
If the thread members are not fetched (can be done manually using
fetch_members()
) and the guild member is not cached, this returnsNone
.- Returns:
The thread owners’ Member if cached, else the respective ThreadMember.
- Return type:
Optional[Union[
Member
,ThreadMember
]]
- property parent_channel
The parent channel of this thread
- Type:
Union[
TextChannel
,ForumChannel
]
- permissions_for(member)
Handles permission resolution for the current
Member
.Note
threads inherit their permissions from their parent channel.
This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
- Parameters:
member (
Member
) – The member to resolve permissions for.- Returns:
The resolved permissions for the member.
- Return type:
- await pins()
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
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 purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check
. If acheck
is not provided then all messages are deleted without discrimination.You must have the
manage_messages
permission to delete messages even if they are your own (unless you are a user account). Theread_message_history
permission is also needed to retrieve message history.Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.
Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await channel.purge(limit=100, check=is_me) await channel.send('Deleted {} message(s)'.format(len(deleted)))
- Parameters:
limit (Optional[
int
]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message
],bool
]) – The function used to check if a message should be deleted. It must take aMessage
as its sole parameter.before (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asbefore
inhistory()
.after (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asafter
inhistory()
.around (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asaround
inhistory()
.oldest_first (Optional[
bool
]) – Same asoldest_first
inhistory()
.bulk (
bool
) – IfTrue
, use bulk delete. Setting this toFalse
is useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages
. WhenTrue
, will fall back to single delete if current account is a user bot (now deprecated), or if messages are older than two weeks.reason (Optional[
str
]) – The reason for deleting the messages. Shows up on the audit log.
- Raises:
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
- Returns:
The list of messages that were deleted.
- Return type:
List[
Message
]
- await remove_member(member)
This function is a coroutine.
Removes a member from the thread.
Note
This requires the
MANAGE_THREADS
permission, or to be the creator of the thread if it is aPRIVATE_THREAD
.Also requires the thread is not archived.
This will fire a
thread_members_update
event.- Parameters:
member (Union[
discord.Member
,int
]) – The member that should be removed from the thread; could be adiscord.Member
or hisid
(e.g. anint
)
- 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.Added 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
.Added in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.Added 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.
Added 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:
- property starter_message
The starter message of this thread if it was started from a message and the message is cached
- Type:
Optional[
Message
]
- 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.
CategoryChannel
- asyncclone
- asynccreate_forum_channel
- asynccreate_invite
- asynccreate_stage_channel
- asynccreate_text_channel
- asynccreate_voice_channel
- asyncdelete
- asyncedit
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncset_permissions
- class discord.CategoryChannel
Bases:
GuildChannel
,Hashable
Represents a Discord channel category.
These are useful to group channels to logical compartments.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the category’s hash.
- str(x)
Returns the category’s name.
- position
The position in the category list. This is a number that starts at 0. e.g. the top category is position 0.
- Type:
- is_nsfw()
bool
: Checks if the category is NSFW.
- await clone(*, name=None, reason=None)
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channels
permission to do this.Added in version 1.1.
- Parameters:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- await edit(*, reason=None, **options)
This function is a coroutine.
Edits the channel.
You must have the
manage_channels
permission to use this.Changed in version 1.3: The
overwrites
keyword-only parameter was added.- Parameters:
name (
str
) – The new category’s name.position (
int
) – The new category’s position.nsfw (
bool
) – To mark the category as NSFW or not.reason (Optional[
str
]) – The reason for editing this category. Shows up on the audit log.overwrites (
dict
) – Adict
of target (either a role or a member) toPermissionOverwrite
to apply to the channel.
- Raises:
InvalidArgument – If position is less than 0 or greater than the number of categories.
Forbidden – You do not have permissions to edit the category.
HTTPException – Editing the category failed.
- await move(*, beginning=False, end=False, before=MISSING, after=MISSING, offset=0, category=MISSING, sync_permissions=False, reason=None)
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
edit()
should be used instead.You must have the
manage_channels
permission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
Added in version 1.7.
- Parameters:
beginning (
bool
) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend
,before
, andafter
.end (
bool
) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning
,before
, andafter
.before (
Snowflake
) – The channel that should be before our current channel. This is mutually exclusive withbeginning
,end
, andafter
.after (
Snowflake
) – The channel that should be after our current channel. This is mutually exclusive withbeginning
,end
, andbefore
.offset (
int
) – The number of channels to offset the move by. For example, an offset of2
withbeginning=True
would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning
,end
,before
, andafter
parameters.category (Optional[
Snowflake
]) – The category to move this channel under. IfNone
is given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool
) – Whether to sync the permissions with the category (if given).reason (
str
) – The reason for the move.
- Raises:
InvalidArgument – An invalid position was given or a bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- property channels
Returns the channels that are under this category.
These are sorted by the official Discord UI, which places voice channels below the text channels.
- Type:
List[
abc.GuildChannel
]
- property text_channels
Returns the text channels that are under this category.
- Type:
List[
TextChannel
]
- property thread_channels
Returns the thread channels that are under this category. Only includes public threads and threads that the authorized bot has joined.
Note
This also includes forum-posts as they are threads too.
- Type:
List[
ThreadChannel
]
- property voice_channels
Returns the voice channels that are under this category.
- Type:
List[
VoiceChannel
]
- property stage_channels
Returns the voice channels that are under this category.
Added in version 1.7.
- Type:
List[
StageChannel
]
- property forum_channels
Returns the forum channels that are under this category.
- Type:
List[
ForumChannel
]
- await create_text_channel(name, *, overwrites=None, reason=None, **options)
This function is a coroutine.
A shortcut method to
Guild.create_text_channel()
to create aTextChannel
in the category.- Returns:
The channel that was just created.
- Return type:
- await create_voice_channel(name, *, overwrites=None, reason=None, **options)
This function is a coroutine.
A shortcut method to
Guild.create_voice_channel()
to create aVoiceChannel
in the category.- Returns:
The channel that was just created.
- Return type:
- await create_stage_channel(name, *, overwrites=None, reason=None, **options)
This function is a coroutine.
A shortcut method to
Guild.create_stage_channel()
to create aStageChannel
in the category.Added in version 1.7.
- 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, position=None, reason=None)
This function is a coroutine.
A shortcut method to
Guild.create_forum_channel()
to create aForumChannel
in the category.- Returns:
The channel that was just created
- Return type:
- property category
The category this channel belongs to.
If there is no category then this is
None
.- Type:
Optional[
CategoryChannel
]
- property changed_roles
Returns a list of roles that have been overridden from their default values in the
roles
attribute.- Type:
List[
Role
]
- await create_invite(*, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, reason=None)
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invite
permission to do this.- Parameters:
max_age (Optional[
int
]) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0
.max_uses (Optional[
int
]) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0
.temporary (Optional[
bool
]) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse
.unique (Optional[
bool
]) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalse
then it will return a previously created invite.target_type (Optional[
InviteTargetType
]) –The type of target for this voice channel invite, if any.
Added in version 2.0.
target_user (Optional[
int
]) –The user whose stream to display for this invite, required if target_type is
TargetType.stream
. The user must be streaming in the channel.Added in version 2.0.
target_application_id (Optional[
int
]) –The id of the embedded application to open for this invite, required if target_type is
InviteTargetType.embeded_application
, the application must have the EMBEDDED flag.Added in version 2.0.
target_event (Optional[
GuildScheduledEvent
]) –The scheduled event object to link to the event. Shortcut to
Invite.set_scheduled_event()
See
Invite.set_scheduled_event()
for more info on event invite linking.Added in version 2.0.
reason (Optional[
str
]) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The invite that was created.
- Return type:
- await delete(*, reason=None)
This function is a coroutine.
Deletes the channel.
You must have
manage_channels
permission to use this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channels
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
]
- property overwrites
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Role
or aMember
and the value is the overwrite as aPermissionOverwrite
.- Returns:
The channel’s permission overwrites.
- Return type:
Mapping[Union[
Role
,Member
],PermissionOverwrite
]
- overwrites_for(obj)
Returns the channel-specific overwrites for a member or a role.
- permissions_for(member, /)
Handles permission resolution for the current
Member
.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
- Parameters:
member (
Member
) – The member to resolve permissions for.- Returns:
The resolved permissions for the member.
- Return type:
- property permissions_synced
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False
.Added in version 1.3.
- Type:
- await set_permissions(target, *, overwrite=MISSING, reason=None, **permissions)
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
target
parameter should either be aMember
or aRole
that belongs to guild.The
overwrite
parameter, if given, must either beNone
orPermissionOverwrite
. For convenience, you can pass in keyword arguments denotingPermissions
attributes. If this is done, then you cannot mix the keyword arguments with theoverwrite
parameter.If the
overwrite
parameter isNone
, then the permission overwrites are deleted.You must have the
manage_roles
permission to use this.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwrite
overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (Union[
Member
,Role
]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite
]) – The permissions to allow and deny to the target, orNone
to delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite
.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
InvalidArgument – The overwrite parameter invalid or the target type was not
Role
orMember
.
DMChannel
- asyncfetch_message
- defget_partial_message
- defhistory
- defpermissions_for
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
- class discord.DMChannel
Bases:
Messageable
,Hashable
Represents a Discord direct message channel.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns a string representation of the channel
- 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!')
- permissions_for(user=None)
Handles permission resolution for a
User
.This function is there for compatibility with other channel types.
Actual direct messages do not really have the concept of permissions.
This returns all the Text related permissions set to
True
except:send_tts_messages
: You cannot send TTS messages in a DM.manage_messages
: You cannot delete others messages in a DM.
- Parameters:
user (
User
) – The user to check permissions for. This parameter is ignored but kept for compatibility.- Returns:
The resolved permissions.
- Return type:
- get_partial_message(message_id)
Creates a
PartialMessage
from the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
Added in version 1.6.
- Parameters:
message_id (
int
) – The message ID to create a partial message for.- Returns:
The partial message.
- Return 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:
- 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.Added 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
.Added in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.Added 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.
Added 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.
GroupChannel
- asyncadd_recipients
- asyncedit
- asyncfetch_message
- defhistory
- deficon_url_as
- asyncleave
- defpermissions_for
- asyncpins
- asyncremove_recipients
- asyncsend
- asynctrigger_typing
- deftyping
- class discord.GroupChannel
Bases:
Messageable
,Hashable
Represents a Discord group channel.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns a string representation of the channel
- recipients
The users you are participating with in the group channel.
- Type:
List[
User
]
- icon
The group channel’s icon hash if provided.
- Type:
Optional[
str
]
- name
The group channel’s name if provided.
- 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 icon_url
Returns the channel’s icon asset if available.
This is equivalent to calling
icon_url_as()
with the default parameters (‘webp’ format and a size of 1024).- Type:
- icon_url_as(*, format='webp', size=1024)
Returns an
Asset
for the icon the channel has.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’ or ‘png’. The size must be a power of 2 between 16 and 4096.
Added in version 2.0.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- permissions_for(user)
Handles permission resolution for a
User
.This function is there for compatibility with other channel types.
Actual direct messages do not really have the concept of permissions.
This returns all the Text related permissions set to
True
except:send_tts_messages
: You cannot send TTS messages in a DM.manage_messages
: You cannot delete others messages in a DM.
This also checks the kick_members permission if the user is the owner.
- Parameters:
user (
User
) – The user to check permissions for.- Returns:
The resolved permissions for the user.
- Return type:
- await add_recipients(*recipients)
This function is a coroutine.
Adds recipients to this group.
A group can only have a maximum of 10 members. Attempting to add more ends up in an exception. To add a recipient to the group, you must have a relationship with the user of type
RelationshipType.friend
.Deprecated since version 1.7.
- Parameters:
*recipients (
User
) – An argument list of users to add to this group.- Raises:
HTTPException – Adding a recipient to this group failed.
- await remove_recipients(*recipients)
This function is a coroutine.
Removes recipients from this group.
Deprecated since version 1.7.
- Parameters:
*recipients (
User
) – An argument list of users to remove from this group.- Raises:
HTTPException – Removing a recipient from this group failed.
- await edit(**fields)
This function is a coroutine.
Edits the group.
Deprecated since version 1.7.
- Parameters:
name (Optional[
str
]) – The new name to change the group to. Could beNone
to remove the name.icon (Optional[
bytes
]) – A bytes-like object representing the new icon. Could beNone
to remove the icon.
- Raises:
HTTPException – Editing the group failed.
- await leave()
This function is a coroutine.
Leave the group.
If you are the only one in the group, this deletes it as well.
- Raises:
HTTPException – Leaving the group failed.
- 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:
- 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.Added 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
.Added in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.Added 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.
Added 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.
PartialInviteGuild
- defbanner_url_as
- deficon_url_as
- defis_icon_animated
- defsplash_url_as
- class discord.PartialInviteGuild
Bases:
object
Represents a “partial” invite guild.
This model will be given when the user is not part of the guild the
Invite
resolves to.- x == y
Checks if two partial guilds are the same.
- x != y
Checks if two partial guilds are not the same.
- hash(x)
Return the partial guild’s hash.
- str(x)
Returns the partial guild’s name.
- features
A list of features the guild has. See
Guild.features
for more information.- Type:
List[
str
]
- icon
The partial guild’s icon.
- Type:
Optional[
str
]
- banner
The partial guild’s banner.
- Type:
Optional[
str
]
- splash
The partial guild’s invite splash.
- Type:
Optional[
str
]
- description
The partial guild’s description.
- Type:
Optional[
str
]
The partial guild’s “boost” count.
- Type:
- is_icon_animated()
bool
: ReturnsTrue
if the guild has an animated icon.Added in version 1.4.
- icon_url_as(*, format=None, static_format='webp', size=1024)
The same operation as
Guild.icon_url_as()
.- Returns:
The resulting CDN asset.
- Return type:
- banner_url_as(*, format='webp', size=2048)
The same operation as
Guild.banner_url_as()
.- Returns:
The resulting CDN asset.
- Return type:
- splash_url_as(*, format='webp', size=2048)
The same operation as
Guild.splash_url_as()
.- Returns:
The resulting CDN asset.
- Return type:
PartialInviteChannel
- class discord.PartialInviteChannel
Bases:
object
Represents a “partial” invite channel.
This model will be given when the user is not part of the guild the
Invite
resolves to.- x == y
Checks if two partial channels are the same.
- x != y
Checks if two partial channels are not the same.
- hash(x)
Return the partial channel’s hash.
- str(x)
Returns the partial channel’s name.
Invite
- asyncdelete
- defset_scheduled_event
- class discord.Invite
Bases:
Hashable
Represents a Discord
Guild
orabc.GuildChannel
invite.Depending on the way this object was created, some of the attributes can have a value of
None
.- x == y
Checks if two invites are equal.
- x != y
Checks if two invites are not equal.
- hash(x)
Returns the invite hash.
- str(x)
Returns the invite URL.
The following table illustrates what methods will obtain the attributes:
Attribute
Method
If it’s not in the table above then it is available by all methods.
- max_age
How long the before the invite expires in seconds. A value of
0
indicates that it doesn’t expire.- Type:
- guild
The guild the invite is for. Can be
None
if it’s from a group direct message.- Type:
Optional[Union[
Guild
,Object
,PartialInviteGuild
]]
- temporary
Indicates that the invite grants temporary membership. If
True
, members who joined via this invite will be kicked upon disconnect.- Type:
- max_uses
How many times the invite can be used. A value of
0
indicates that it has unlimited uses.- Type:
- approximate_member_count
The approximate number of members in the guild.
- Type:
Optional[
int
]
- approximate_presence_count
The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded.
- Type:
Optional[
int
]
- scheduled_event
The scheduled event attached to this invite link, if any.
- Type:
Optional[
GuildScheduledEvent
]
- channel
The channel the invite is for.
- Type:
Union[
abc.GuildChannel
,Object
,PartialInviteChannel
]
- await delete(*, reason=None)
This function is a coroutine.
Revokes the instant invite.
You must have the
manage_channels
permission to do this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this invite. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to revoke invites.
NotFound – The invite is invalid or expired.
HTTPException – Revoking the invite failed.
- set_scheduled_event(event)
Links the given scheduled event to this invite.
Note
Scheduled events aren’t actually associated with invites on the API. Any guild channel invite can have an event attached to it. Using
abc.GuildChannel.create_invite()
,Client.fetch_invite()
, or this method, you can link scheduled events.Added in version 2.0.
- Parameters:
event (
ScheduledEvent
) – The scheduled event object to link.
Template
- asynccreate_guild
- asyncdelete
- asyncedit
- asyncsync
- class discord.Template
Bases:
object
Represents a Discord template.
Added in version 1.4.
- await create_guild(name, region=None, icon=None)
This function is a coroutine.
Creates a
Guild
using the template.Bot accounts in more than 10 guilds are not allowed to create guilds.
- Parameters:
name (
str
) – The name of the guild.region (
VoiceRegion
) – The region for the voice communication server. Defaults toVoiceRegion.us_west
.icon (
bytes
) – The bytes-like object representing the icon. SeeClientUser.edit()
for more details on what is expected.
- Raises:
HTTPException – Guild creation failed.
InvalidArgument – Invalid icon image format given. Must be PNG or JPG.
- Returns:
The guild created. This is not the same guild that is added to cache.
- Return type:
- await sync()
This function is a coroutine.
Sync the template to the guild’s current state.
You must have the
manage_guild
permission in the source guild to do this.Added in version 1.7.
- Raises:
HTTPException – Editing the template failed.
Forbidden – You don’t have permissions to edit the template.
NotFound – This template does not exist.
- await edit(**kwargs)
This function is a coroutine.
Edit the template metadata.
You must have the
manage_guild
permission in the source guild to do this.Added in version 1.7.
- Parameters:
- Raises:
HTTPException – Editing the template failed.
Forbidden – You don’t have permissions to edit the template.
NotFound – This template does not exist.
- await delete()
This function is a coroutine.
Delete the template.
You must have the
manage_guild
permission in the source guild to do this.Added in version 1.7.
- Raises:
HTTPException – Editing the template failed.
Forbidden – You don’t have permissions to edit the template.
NotFound – This template does not exist.
WidgetChannel
- class discord.WidgetChannel
Bases:
object
Represents a “partial” widget channel.
- x == y
Checks if two partial channels are the same.
- x != y
Checks if two partial channels are not the same.
- hash(x)
Return the partial channel’s hash.
- str(x)
Returns the partial channel’s name.
WidgetMember
- accent_color
- accent_colour
- activity
- avatar
- avatar_url
- banner_color
- banner_colour
- banner_url
- bot
- color
- colour
- connected_channel
- created_at
- deafened
- default_avatar
- default_avatar_url
- discriminator
- display_avatar
- display_name
- global_name
- hex_banner_color
- id
- is_migrated
- mention
- muted
- nick
- public_flags
- status
- suppress
- username
- class discord.WidgetMember
Bases:
BaseUser
Represents a “partial” member of the widget’s guild.
Changed in version 2.0: The
name
attribute was renamed tousername
due to the (upcoming) username changes.- x == y
Checks if two widget members are the same.
- x != y
Checks if two widget members are not the same.
- hash(x)
Return the widget member’s hash.
- str(x)
Returns the
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 member’s global name if set. In the client UI this is referred to as “Display Name”.
Added in version 2.0.
- Type:
Optional[
str
]
- discriminator
The member’s discriminator.
Important
This will be removed in a future API version. Read more about it here.
- Type:
- nick
The member’s nickname.
- Type:
Optional[
str
]
- avatar
The member’s avatar hash.
- Type:
Optional[
str
]
- activity
The member’s activity.
- Type:
Optional[Union[
BaseActivity
,Spotify
]]
- deafened
Whether the member is currently deafened.
- Type:
Optional[
bool
]
- muted
Whether the member is currently muted.
- Type:
Optional[
bool
]
- suppress
Whether the member is currently being suppressed.
- Type:
Optional[
bool
]
- connected_channel
Which channel the member is connected to.
- Type:
Optional[
VoiceChannel
]
- 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 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:
- 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.
Widget
- asyncfetch_invite
- class discord.Widget
Bases:
object
Represents a
Guild
widget.- x == y
Checks if two widgets are the same.
- x != y
Checks if two widgets are not the same.
- str(x)
Returns the widget’s JSON URL.
- channels
The accessible voice channels in the guild.
- Type:
Optional[List[
WidgetChannel
]]
- members
The online members in the server. Offline members do not appear in the widget.
Note
Due to a Discord limitation, if this data is available the users will be “anonymized” with linear IDs and discriminator information being incorrect. Likewise, the number of members retrieved is capped.
- Type:
Optional[List[
Member
]]
- property invite_url
The invite URL for the guild, if available.
- Type:
Optional[
str
]
- await fetch_invite(*, with_counts=True)
This function is a coroutine.
Retrieves an
Invite
from a invite URL or ID. This is the same asClient.fetch_invite()
; the invite code is abstracted away.- Parameters:
with_counts (
bool
) – Whether to include count information in the invite. This fills theInvite.approximate_member_count
andInvite.approximate_presence_count
fields.- Returns:
The invite from the URL/ID.
- Return type:
StickerPack
- defbanner_url_as
- defget_sticker
- class discord.StickerPack
Bases:
Hashable
Represents a pack of build-in stickers
- cover_sticker_id
The id of a sticker in the pack which is shown in the client as the pack’s icon.
- Type:
Optional[
int
]
- property stickers
The stickers of the pack
- Type:
Tuple[
Sticker
]
- property banner_url
Returns an
Asset
for the sticker pack’s banner.- Returns:
The resulting CDN asset.
- Return type:
- banner_url_as(format='png', size=1024)
Returns an
Asset
for the sticker pack’s banner.The size must be a power of 2 between 16 and 4096.
- Returns:
The resulting CDN asset.
- Return type:
Sticker
- defimage_url_as
- class discord.Sticker
Bases:
Hashable
Represents a sticker.
Added in version 1.6.
- str(x)
Returns the name of the sticker.
- x == y
Checks if the sticker is equal to another sticker.
- x != y
Checks if the sticker is not equal to another sticker.
- tags
A list of tags for the sticker.
- Type:
List[
str
]
- pack
The pack the sticker belongs to. Could be
None
even ifSticker.pack_id
is present.- Type:
Optional[
StickerPack
]
- sort_value
The sticker’s sort order within its
Sticker.pack
.- Type:
- asyncdelete
- asyncedit
- defimage_url_as
- class discord.GuildSticker
Bases:
Sticker
Represents a “custom” sticker in a guild
- tags
A list of tags for the sticker.
- Type:
List[
str
]
- available
Whether this guild sticker can be used, may be
False
due to loss of Server Boosts- Type:
- await edit(*, reason=None, **fields)
This function is a coroutine.
Modify the sticker.
Requires the
MANAGE_EMOJIS_AND_STICKERS
permission.- Parameters:
name (
str
) – The name of the sticker; 2-30 characters long.description (Optional[
str
]) – The description of the sticker;None
or 2-100 characters long.tags (Union[
str
, List[str
]]) – The autocomplete/suggestion tags for the sticker. A string in which the individual tags are separated by,
or a list of tags; (max 200 characters).reason (Optional[
str
]) – The reason for modifying the sticker, shows up in the audit-log.
- Raises:
discord.Forbidden: – You don’t have the required permission to edit the sticker.
discord.HTTPException: – Editing the sticker failed.
ValueError: – Any of name, description or tags is invalid.
- Returns:
The updated sticker on success.
- Return type:
- await delete(*, reason)
This function is a coroutine.
Delete the sticker.
Requires the
MANAGE_EMOJIS_AND_STICKERS
permission.- Parameters:
reason (Optional[
str
]) – The reason for deleting the sticker, shows up in the audit-log.- Raises:
discord.Forbidden: – You don’t have the required permissions to delete the sticker.
discord.HTTPException: – Deleting the sticker failed.
- Returns:
The sticker that was deleted.
- Return type:
VoiceRegionInfo
- class discord.VoiceRegionInfo
Bases:
object
A class containing info about a specific voice region.
These can be retrieved via
fetch_voice_regions()
.Added in version 2.0.
- .. container:: operations
- x == y
- Whether two voice regions are equal.
- x != y
- Whether two voice regions are not equal.
- x > y
- Whether a voice region is optimal over another.
- x < y
- Whether a voice region is not optimal over another.
- str(x)
- Returns the id of the region.
- repr(x)
- Returns a representation of the region.
RawMessageDeleteEvent
- class discord.RawMessageDeleteEvent
Bases:
_RawReprMixin
Represents the event payload for a
on_raw_message_delete()
event.- guild_id
The guild ID where the deletion took place, if applicable.
- Type:
Optional[
int
]
- cached_message
The cached message, if found in the internal message cache.
- Type:
Optional[
Message
]
RawBulkMessageDeleteEvent
- class discord.RawBulkMessageDeleteEvent
Bases:
_RawReprMixin
Represents the event payload for a
on_raw_bulk_message_delete()
event.- guild_id
The guild ID where the message got deleted, if applicable.
- Type:
Optional[
int
]
- cached_messages
The cached messages, if found in the internal message cache.
- Type:
List[
Message
]
RawMessageUpdateEvent
- class discord.RawMessageUpdateEvent
Bases:
_RawReprMixin
Represents the payload for a
on_raw_message_edit()
event.- guild_id
The guild ID where the message got updated, if applicable.
Added in version 1.7.
- Type:
Optional[
int
]
- cached_message
The cached message, if found in the internal message cache. Represents the message before it is modified by the data in
RawMessageUpdateEvent.data
.- Type:
Optional[
Message
]
RawReactionActionEvent
- class discord.RawReactionActionEvent
Bases:
_RawReprMixin
Represents the payload for a
on_raw_reaction_add()
oron_raw_reaction_remove()
event.- guild_id
The guild ID where the reaction got added or removed, if applicable.
- Type:
Optional[
int
]
- member
The member who added the reaction. Only available if event_type is REACTION_ADD and the reaction is inside a guild.
Added in version 1.3.
- Type:
Optional[
Member
]
- event_type
The event type that triggered this action. Can be
REACTION_ADD
for reaction addition orREACTION_REMOVE
for reaction removal.Added in version 1.3.
- Type:
RawReactionClearEvent
- class discord.RawReactionClearEvent
Bases:
_RawReprMixin
Represents the payload for a
on_raw_reaction_clear()
event.- guild_id
The guild ID where the reactions got cleared.
- Type:
Optional[
int
]
RawReactionClearEmojiEvent
- class discord.RawReactionClearEmojiEvent
Bases:
_RawReprMixin
Represents the payload for a
on_raw_reaction_clear_emoji()
event.Added in version 1.3.
- guild_id
The guild ID where the reactions got cleared.
- Type:
Optional[
int
]
VoiceChannelEffectSendEvent
- class discord.VoiceChannelEffectSendEvent
Bases:
_RawReprMixin
Represents the payload for an
on_voice_channel_effect_send()
event.Added in version 2.0.
- emoji
The emoji used when this is an emoji effect or the emoji associated to the sound.
- Type:
Optional[
PartialEmoji
]
- sound_id
The sound ID of the soundboard sound used, if any.
- Type:
Optional[
int
]
- sound_volume
The volume of the soundboard sound used, if any.
- Type:
Optional[
float
]