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.
- defis_animated
- asyncread
- defreplace
- asyncsave
- defwith_format
- defwith_size
- defwith_static_format
- class discord.Asset(state, *, url, key, animated=False)[source]#
Represents a CDN asset on Discord.
- str(x)
Returns the URL of the CDN asset.
- len(x)
Returns the length of the CDN asset’s URL.
- x == y
Checks if the asset is equal to another asset.
- x != y
Checks if the asset is not equal to another asset.
- hash(x)
Returns the hash of the asset.
- property url#
Returns the underlying URL of the asset.
- property key#
Returns the identifying key of the asset.
- replace(*, size=..., format=..., static_format=...)[source]#
Returns a new asset with the passed components replaced.
- Parameters:
- Returns:
The newly updated asset.
- Return type:
- Raises:
InvalidArgument – An invalid size or format was passed.
- with_size(size, /)[source]#
Returns a new asset with the specified size.
- Parameters:
size (
int
) – The new size of the asset.- Returns:
The new updated asset.
- Return type:
- Raises:
InvalidArgument – The asset had an invalid size.
- with_format(format, /)[source]#
Returns a new asset with the specified format.
- Parameters:
format (
str
) – The new format of the asset.- Returns:
The new updated asset.
- Return type:
- Raises:
InvalidArgument – The asset has an invalid format.
- with_static_format(format, /)[source]#
Returns a new asset with the specified static format.
This only changes the format if the underlying asset is not animated. Otherwise, the asset is not changed.
- Parameters:
format (
str
) – The new static format of the asset.- Returns:
The new updated asset.
- Return type:
- Raises:
InvalidArgument – The asset had an invalid format.
- await read()#
This function is a coroutine.
Retrieves the content of this asset as a
bytes
object.- Returns:
The content of the asset.
- Return type:
- Raises:
DiscordException – There was no internal connection state.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- await save(fp, *, seek_begin=True)#
This function is a coroutine.
Saves this asset into a file-like object.
- Parameters:
fp (Union[
io.BufferedIOBase
,os.PathLike
]) – The file-like object to save this 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.
- Returns:
The number of bytes written.
- Return type:
- Raises:
DiscordException – There was no internal connection state.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- class discord.Spotify[source]#
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
.
- property created_at#
When the user started listening in UTC.
New in version 1.3.
- property colour#
Returns the Spotify integration colour, as a
Colour
.There is an alias for this named
color
- property color#
Returns the Spotify integration colour, as a
Colour
.There is an alias for this named
colour
- property name#
The activity’s name. This will always return “Spotify”.
- property title#
The title of the song being played.
- property artists#
The artists of the song being played.
- 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.
- property album#
The album that the song being played belongs to.
- property album_cover_url#
The album cover image URL from Spotify’s CDN.
- property track_id#
The track ID used by Spotify to identify this song.
- property track_url#
The track URL to listen on Spotify.
New in version 2.0.
- property start#
When the user started playing this song in UTC.
- property end#
When the user will stop playing this song in UTC.
- property duration#
The duration of the song being played.
- property party_id#
The party ID of the listening party.
- class discord.VoiceState(*, data, channel=None)[source]#
Represents a Discord user’s voice state.
- self_stream#
Indicates if the user is currently streaming via ‘Go Live’ feature.
New in version 1.3.
- Type:
- suppress#
Indicates if the user is suppressed from speaking.
Only applies to stage channels.
New in version 1.7.
- Type:
- requested_to_speak_at#
An aware datetime object that specifies the date and time in UTC that the member requested to speak. It will be
None
if they are not requesting to speak anymore or have been accepted to speak.Only applicable to stage channels.
New in version 1.7.
- Type:
Optional[
datetime.datetime
]
- channel#
The voice channel that the user is currently connected to.
None
if the user is not currently in a voice channel.- Type:
Optional[Union[
VoiceChannel
,StageChannel
]]
- Parameters:
data (VoiceStatePayload | GuildVoiceStatePayload) –
channel (VocalGuildChannel | None) –
- defcan_send
- asyncfetch_message
- defget_partial_message
- defhistory
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
- class discord.PartialMessageable(state, id, type=None)[source]#
Represents a partial messageable to aid with working messageable channels when only a channel ID are present.
The only way to construct this class is through
Client.get_partial_messageable()
.Note that this class is trimmed down and has no rich attributes.
New in version 2.0.
- x == y
Checks if two partial messageables are equal.
- x != y
Checks if two partial messageables are not equal.
- hash(x)
Returns the partial messageable’s hash.
- type#
The channel type associated with this partial messageable, if given.
- Type:
Optional[
ChannelType
]
- Parameters:
state (ConnectionState) –
id (int) –
type (ChannelType | None) –
- can_send(*objects)#
Returns a
bool
indicating whether you have the permissions to send the object(s).
- await fetch_message(id, /)#
This function is a coroutine.
Retrieves a single
Message
from the destination.- Parameters:
id (
int
) – The message ID to look for.- Returns:
The message asked for.
- Return type:
- 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.
- 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.- Parameters:
limit (Optional[
int
]) – The number of messages to retrieve. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) – If set toTrue
, return messages in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.
- Yields:
Message
– The message with the message data parsed.- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Return type:
HistoryIterator
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.
- 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.- Returns:
The messages that are currently pinned.
- Return type:
List[
Message
]- Raises:
HTTPException – Retrieving the pinned messages failed.
- await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, silent=None)#
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. Specifying both parameters will lead to an exception.To upload a single embed, the
embed
parameter should be used with a singleEmbed
object. To upload multiple embeds, theembeds
parameter should be used with alist
ofEmbed
objects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
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.file (
File
) – The file to upload.files (List[
File
]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
str
,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.enforce_nonce (Optional[
bool
]) –Whether
nonce
is enforced to be validated.New in version 2.5.
delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
,PartialMessage
]) –A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
view (
discord.ui.View
) – A Discord UI View to add to the message.embeds (List[
Embed
]) –A list of embeds to upload. Must be a maximum of 10.
New in version 2.0.
stickers (Sequence[Union[
GuildSticker
,StickerItem
]]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
suppress (
bool
) – Whether to suppress embeds for the message.silent (
bool
) –Whether to suppress push and desktop notifications for the message.
New in version 2.4.
poll (
Poll
) –The poll to send.
New in version 2.6.
- Returns:
The message that was sent.
- Return type:
- 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 you specified bothembed
andembeds
, or thereference
object is not aMessage
,MessageReference
orPartialMessage
.
- 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.
- Return type:
- 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. :rtype:
Typing
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(): # simulate something heavy await asyncio.sleep(10) await channel.send('done!')
- get_partial_message(message_id, /)[source]#
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.
- Parameters:
message_id (
int
) – The message ID to create a partial message for.- Returns:
The partial message.
- Return type:
Users#
- asyncedit
- defmentioned_in
- class discord.ClientUser(*, state, data)[source]#
Represents your Discord user.
- x == y
Checks if two users are equal.
- x != y
Checks if two users are not equal.
- hash(x)
Return the user’s hash.
- str(x)
Returns the user’s name with discriminator or global_name.
- discriminator#
The user’s discriminator. This is given when the username has conflicts.
Note
If the user has migrated to the new username system, this will always be 0.
- Type:
- system#
Specifies if the user is a system user (i.e. represents Discord officially).
New in version 1.3.
- Type:
- Parameters:
state (
ConnectionState
) –data (
User
) –
- await edit(*, username=..., avatar=..., banner=...)[source]#
This function is a coroutine.
Edits the current profile of the client.
Note
To upload an avatar or banner, a bytes-like object must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via
open('some_filename', 'rb')
and the bytes-like object is given through the use offp.read()
.The only image formats supported for uploading are JPEG, PNG, and GIF.
Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned.
Changed in version 2.6: The
banner
keyword-only parameter was added.- Parameters:
username (
str
) – The new username you wish to change to.avatar (
bytes
) – A bytes-like object representing the image to upload. Could beNone
to denote no avatar.banner (
bytes
) – A bytes-like object representing the image to upload. Could beNone
to denote no banner.
- Returns:
The newly edited client user.
- Return type:
- Raises:
HTTPException – Editing your profile failed.
InvalidArgument – Wrong image format passed for
avatar
orbanner
.
- property accent_color#
Returns the user’s accent color, if applicable.
There is an alias for this named
accent_colour
.New in version 2.0.
Note
This information is only available via
Client.fetch_user()
.
- property accent_colour#
Returns the user’s accent colour, if applicable.
There is an alias for this named
accent_color
.New in version 2.0.
Note
This information is only available via
Client.fetch_user()
.
- property avatar#
Returns an
Asset
for the avatar the user has.If the user does not have a traditional avatar,
None
is returned. If you want the avatar that a user has displayed, considerdisplay_avatar
.
- property avatar_decoration#
Returns the user’s avatar decoration, if available.
New in version 2.5.
- property banner#
Returns the user’s banner asset, if available.
New in version 2.0.
Note
This information is only available via
Client.fetch_user()
.
- 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
.
- 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
.
- property created_at#
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
- property default_avatar#
Returns the default avatar for a given user. This is calculated by the user’s ID if they’re on the new username system, otherwise their discriminator.
- property display_avatar#
Returns the user’s display avatar.
For regular users this is just their default avatar or uploaded avatar.
New in version 2.0.
- property display_name#
Returns the user’s display name. This will be their global name if set, otherwise their username.
- property is_migrated#
Checks whether the user is already migrated to global name.
- property jump_url#
Returns a URL that allows the client to jump to the user.
New in version 2.0.
- property mention#
Returns a string that allows you to mention the given user.
- mentioned_in(message)#
Checks if the user is mentioned in the specified message.
- property public_flags#
The publicly available flags the user has.
- defcan_send
- asynccreate_dm
- asynccreate_test_entitlement
- defentitlements
- asyncfetch_message
- defhistory
- defmentioned_in
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
- class discord.User(*, state, data)[source]#
Represents a Discord user.
- x == y
Checks if two users are equal.
- x != y
Checks if two users are not equal.
- hash(x)
Return the user’s hash.
- str(x)
Returns the user’s name with discriminator or global_name.
- discriminator#
The user’s discriminator. This is given when the username has conflicts.
Note
If the user has migrated to the new username system, this will always be “0”.
- Type:
- Parameters:
state (
ConnectionState
) –data (
User
) –
- 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.- Parameters:
limit (Optional[
int
]) – The number of messages to retrieve. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) – If set toTrue
, return messages in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.
- Yields:
Message
– The message with the message data parsed.- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Return type:
HistoryIterator
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.
- 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. :rtype:
Typing
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(): # simulate something heavy await asyncio.sleep(10) 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.
- property mutual_guilds#
The guilds that the user shares with the client.
Note
This will only return mutual guilds within the client’s internal cache.
New in version 1.7.
- await create_dm()[source]#
This function is a coroutine.
Creates a
DMChannel
with this user.This should be rarely called, as this is done transparently for most people.
- Returns:
The channel that was created.
- Return type:
- await create_test_entitlement(sku)[source]#
This function is a coroutine.
Creates a test entitlement for the user.
- Parameters:
sku (
Snowflake
) – The SKU to create a test entitlement for.- Returns:
The created entitlement.
- Return type:
- property accent_color#
Returns the user’s accent color, if applicable.
There is an alias for this named
accent_colour
.New in version 2.0.
Note
This information is only available via
Client.fetch_user()
.
- property accent_colour#
Returns the user’s accent colour, if applicable.
There is an alias for this named
accent_color
.New in version 2.0.
Note
This information is only available via
Client.fetch_user()
.
- property avatar#
Returns an
Asset
for the avatar the user has.If the user does not have a traditional avatar,
None
is returned. If you want the avatar that a user has displayed, considerdisplay_avatar
.
- property avatar_decoration#
Returns the user’s avatar decoration, if available.
New in version 2.5.
- property banner#
Returns the user’s banner asset, if available.
New in version 2.0.
Note
This information is only available via
Client.fetch_user()
.
- can_send(*objects)#
Returns a
bool
indicating whether you have the permissions to send the object(s).
- 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
.
- 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
.
- property created_at#
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
- property default_avatar#
Returns the default avatar for a given user. This is calculated by the user’s ID if they’re on the new username system, otherwise their discriminator.
- property display_avatar#
Returns the user’s display avatar.
For regular users this is just their default avatar or uploaded avatar.
New in version 2.0.
- property display_name#
Returns the user’s display name. This will be their global name if set, otherwise their username.
- entitlements(skus=None, before=None, after=None, limit=100, exclude_ended=False)[source]#
Returns an
AsyncIterator
that enables fetching the user’s entitlements.This is identical to
Client.entitlements()
with theuser
parameter.New in version 2.6.
- Parameters:
skus (list[
abc.Snowflake
] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake
|datetime.datetime
| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake
|datetime.datetime
| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int
]) – The number of entitlements to retrieve. IfNone
, retrieves every entitlement, which may be slow. Defaults to100
.exclude_ended (
bool
) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse
.
- Yields:
Entitlement
– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- await fetch_message(id, /)#
This function is a coroutine.
Retrieves a single
Message
from the destination.- Parameters:
id (
int
) – The message ID to look for.- Returns:
The message asked for.
- Return type:
- 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.
- property is_migrated#
Checks whether the user is already migrated to global name.
- property jump_url#
Returns a URL that allows the client to jump to the user.
New in version 2.0.
- property mention#
Returns a string that allows you to mention the given user.
- mentioned_in(message)#
Checks if the user is mentioned in the specified message.
- 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.- Returns:
The messages that are currently pinned.
- Return type:
List[
Message
]- Raises:
HTTPException – Retrieving the pinned messages failed.
- property public_flags#
The publicly available flags the user has.
- await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, silent=None)#
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. Specifying both parameters will lead to an exception.To upload a single embed, the
embed
parameter should be used with a singleEmbed
object. To upload multiple embeds, theembeds
parameter should be used with alist
ofEmbed
objects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
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.file (
File
) – The file to upload.files (List[
File
]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
str
,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.enforce_nonce (Optional[
bool
]) –Whether
nonce
is enforced to be validated.New in version 2.5.
delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
,PartialMessage
]) –A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
view (
discord.ui.View
) – A Discord UI View to add to the message.embeds (List[
Embed
]) –A list of embeds to upload. Must be a maximum of 10.
New in version 2.0.
stickers (Sequence[Union[
GuildSticker
,StickerItem
]]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
suppress (
bool
) – Whether to suppress embeds for the message.silent (
bool
) –Whether to suppress push and desktop notifications for the message.
New in version 2.4.
poll (
Poll
) –The poll to send.
New in version 2.6.
- Returns:
The message that was sent.
- Return type:
- 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 you specified bothembed
andembeds
, or thereference
object is not aMessage
,MessageReference
orPartialMessage
.
Messages#
- defis_spoiler
- asyncread
- asyncsave
- asyncto_file
- class discord.Attachment(*, data, state)[source]#
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.- height#
The attachment’s height, in pixels. Only applicable to images and videos.
- Type:
Optional[
int
]
- title#
The attachment’s title. This is equal to the original
filename
(without an extension) if special characters were filtered from it.New in version 2.6.
- Type:
Optional[
str
]
- 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
]
- duration_secs#
The duration of the audio file (currently for voice messages).
New in version 2.5.
- Type:
Optional[
float
]
- waveform#
The base64 encoded bytearray representing a sampled waveform (currently for voice messages).
New in version 2.5.
- Type:
Optional[
str
]
- flags#
Extra attributes of the attachment.
New in version 2.5.
- Type:
- Parameters:
data (
Attachment
) –state (
ConnectionState
) –
- property expires_at#
This attachment URL’s expiry time in UTC.
- property issued_at#
The attachment URL’s issue time in UTC.
- await save(fp, *, seek_begin=True, use_cached=False)[source]#
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.
- Returns:
The number of bytes written.
- Return type:
- Raises:
HTTPException – Saving the attachment failed.
NotFound – The attachment was deleted.
- await read(*, use_cached=False)[source]#
This function is a coroutine.
Retrieves the content of this attachment as a
bytes
object.New in version 1.1.
- Parameters:
use_cached (
bool
) – Whether to useproxy_url
rather thanurl
when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed, and it does not work on some types of attachments.- Returns:
The contents of the attachment.
- Return type:
- Raises:
HTTPException – Downloading the attachment failed.
Forbidden – You do not have permissions to access this attachment
NotFound – The attachment was deleted.
- await to_file(*, use_cached=False, spoiler=False)[source]#
This function is a coroutine.
Converts the attachment into a
File
suitable for sending viaabc.Messageable.send()
.New in version 1.3.
- Parameters:
use_cached (
bool
) –Whether to use
proxy_url
rather thanurl
when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed, and it does not work on some types of attachments.New in version 1.4.
spoiler (
bool
) –Whether the file is a spoiler.
New in version 1.4.
- Returns:
The attachment as a file suitable for sending.
- Return type:
- Raises:
HTTPException – Downloading the attachment failed.
Forbidden – You do not have permissions to access this attachment
NotFound – The attachment was deleted.
- activity
- application
- attachments
- author
- call
- channel
- channel_mentions
- clean_content
- components
- content
- created_at
- edited_at
- embeds
- flags
- guild
- id
- interaction
- interaction_metadata
- jump_url
- mention_everyone
- mentions
- nonce
- pinned
- poll
- raw_channel_mentions
- raw_mentions
- raw_role_mentions
- reactions
- reference
- role_mentions
- stickers
- system_content
- thread
- tts
- type
- webhook_id
- asyncadd_reaction
- asyncclear_reaction
- asyncclear_reactions
- asynccreate_thread
- asyncdelete
- asyncedit
- asyncend_poll
- defis_system
- asyncpin
- asyncpublish
- asyncremove_reaction
- asyncreply
- defto_reference
- asyncunpin
- class discord.Message(*, state, channel, data)[source]#
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 the left the guild, then it is aUser
instead.
- 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.
- channel#
The
TextChannel
orThread
that the message was sent from. Could be aDMChannel
orGroupChannel
if it’s a private message.- Type:
Union[
TextChannel
,Thread
,DMChannel
,GroupChannel
,PartialMessageable
]
- reference#
The message that this message references. This is only applicable to messages of type
MessageType.pins_add
, crossposted messages created by a followed channel integration, or message replies.New in version 1.5.
- Type:
Optional[
MessageReference
]
- mention_everyone#
Specifies if the message mentions everyone.
Note
This does not check if the
@everyone
or the@here
text is in the message itself. Rather this boolean indicates if either the@everyone
or the@here
text is in the message and it did end up mentioning.- Type:
- mentions#
A list of
Member
that were mentioned. If the message is in a private message then the list will be ofUser
instead. For messages that are not of typeMessageType.default
, this array can be used to aid in system messages. For more information, seesystem_content
.Warning
The order of the mentions list is not in any particular order, so you should not rely on it. This is a Discord limitation, not one with the library.
- Type:
List[
abc.User
]
- channel_mentions#
A list of
abc.GuildChannel
that were mentioned. If the message is in a private message then the list is always empty.- Type:
List[
abc.GuildChannel
]
- role_mentions#
A list of
Role
that were mentioned. If the message is in a private message then the list is always empty.- Type:
List[
Role
]
- webhook_id#
If this message was sent by a webhook, then this is the webhook ID’s that sent this message.
- Type:
Optional[
int
]
- attachments#
A list of attachments given to a message.
- Type:
List[
Attachment
]
- flags#
Extra features of the message.
New in version 1.3.
- Type:
- reactions#
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
- Type:
List[
Reaction
]
- activity#
The activity associated with this message. Sent with Rich-Presence related messages that for example, request joining, spectating, or listening to or with another member.
It is a dictionary with the following optional keys:
type
: An integer denoting the type of message activity being requested.party_id
: The party ID associated with the party.
- Type:
Optional[
dict
]
- application#
The rich presence enabled application associated with this message.
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 sticker items given to the message.
New in version 1.6.
- Type:
List[
StickerItem
]
- interaction#
The interaction associated with the message, if applicable.
Deprecated since version 2.6: Use
interaction_metadata
instead.- Type:
Optional[
MessageInteraction
]
- interaction_metadata#
The interaction metadata associated with the message, if applicable.
New in version 2.6.
- Type:
Optional[
InteractionMetadata
]
- thread#
The thread created from this message, if applicable.
New in version 2.0.
- Type:
Optional[
Thread
]
- poll#
The poll associated with this message, if applicable.
New in version 2.6.
- Type:
Optional[
Poll
]
- call#
The call information associated with this message, if applicable.
New in version 2.6.
- Type:
Optional[
MessageCall
]
- Parameters:
state (
ConnectionState
) –channel (
Union
[TextChannel
,VoiceChannel
,StageChannel
,Thread
,DMChannel
,PartialMessageable
,GroupChannel
]) –data (
Message
) –
- 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.
- raw_channel_mentions#
A property that returns an array of channel IDs matched with the syntax of
<#channel_id>
in the message content.
- raw_role_mentions#
A property that returns an array of role IDs matched with the syntax of
<@&role_id>
in the message content.
- 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.
- property created_at#
The message’s creation time in UTC.
- property edited_at#
An aware UTC datetime object containing the edited time of the message.
- property jump_url#
Returns a URL that allows the client to jump to this message.
- is_system()[source]#
Whether the message is a system message.
A system message is a message that is constructed entirely by the Discord API in response to something. :rtype:
bool
New in version 1.3.
- system_content#
A property that returns the content that is rendered regardless of the
Message.type
.In the case of
MessageType.default
andMessageType.reply
, this just returns the regularMessage.content
. Otherwise, this returns an English message denoting the contents of the system message.
- await delete(*, delay=None, reason=None)[source]#
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.
- Return type:
None
- await edit(content=..., embed=..., embeds=..., file=..., files=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)[source]#
This function is a coroutine.
Edits the message.
The content must be able to be transformed into a string via
str(content)
.Changed in version 1.3: The
suppress
keyword-only parameter was 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 the embed.embeds (List[
Embed
]) –The new embeds to replace the original with. Must be a maximum of 10. To remove all embeds
[]
should be passed.New in version 2.0.
file (Sequence[
File
]) – A new file to add to the message.files (List[Sequence[
File
]]) – New files to add to the message.attachments (List[
Attachment
]) – A list of attachments to keep in the message. If[]
is passed then all attachments are removed.suppress (
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. Using this parameter requiresmanage_messages
.delete_after (Optional[
float
]) – If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.allowed_mentions (Optional[
AllowedMentions
]) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
view (Optional[
View
]) – The updated view to update this message with. IfNone
is passed then the view is removed.
- 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.
InvalidArgument – You specified both
embed
andembeds
, specified bothfile
andfiles
, or either``file`` orfiles
were of the wrong type.
- Return type:
- await publish()[source]#
This function is a coroutine.
Publishes this message to your announcement channel.
You must have the
send_messages
permission to do this.If the message is not your own then the
manage_messages
permission is also needed.- Raises:
Forbidden – You do not have the proper permissions to publish this message.
HTTPException – Publishing the message failed.
- Return type:
- await pin(*, reason=None)[source]#
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:
reason (Optional[
str
]) –The reason for pinning the message. Shows up on the audit log.
New in version 1.4.
- Raises:
Forbidden – You do not have permissions to pin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Pinning the message failed, probably due to the channel having more than 50 pinned messages.
- Return type:
None
- await unpin(*, reason=None)[source]#
This function is a coroutine.
Unpins the message.
You must have the
manage_messages
permission to do this in a non-private channel context.- Parameters:
reason (Optional[
str
]) –The reason for unpinning the message. Shows up on the audit log.
New in version 1.4.
- Raises:
Forbidden – You do not have permissions to unpin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Unpinning the message failed.
- Return type:
None
- await add_reaction(emoji)[source]#
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.
- Return type:
- await remove_reaction(emoji, member)[source]#
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.
- Return type:
None
- await clear_reaction(emoji)[source]#
This function is a coroutine.
Clears a specific reaction from the message.
The emoji may be a unicode emoji or a custom guild
Emoji
.You need the
manage_messages
permission to use this.New in version 1.3.
- Parameters:
emoji (Union[
Emoji
,Reaction
,PartialEmoji
,str
]) – The emoji to clear.- Raises:
HTTPException – Clearing the reaction failed.
Forbidden – You do not have the proper permissions to clear the reaction.
NotFound – The emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- Return type:
None
- await clear_reactions()[source]#
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.
- Return type:
- await create_thread(*, name, auto_archive_duration=..., slowmode_delay=...)[source]#
This function is a coroutine.
Creates a public thread from this message.
You must have
create_public_threads
in order to create a public thread from a message.The channel this message belongs in must be a
TextChannel
.New in version 2.0.
- Parameters:
name (
str
) – The name of the thread.auto_archive_duration (Optional[
int
]) – The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used.slowmode_delay (Optional[
int
]) – Specifies the slowmode rate limit for user in this thread, in seconds. A value of0
disables slowmode. The maximum value possible is21600
.
- Returns:
The created thread.
- Return type:
- Raises:
Forbidden – You do not have permissions to create a thread.
HTTPException – Creating the thread failed.
InvalidArgument – This message does not have guild info attached.
- await reply(content=None, **kwargs)[source]#
This function is a coroutine.
A shortcut method to
abc.Messageable.send()
to reply to theMessage
.New in version 1.6.
- Returns:
The message that was sent.
- Return type:
- 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
.
- Parameters:
content (str | None) –
- await end_poll()[source]#
This function is a coroutine.
Immediately ends the poll associated with this message. Only doable by the poll’s owner.
New in version 2.6.
- Returns:
The updated message.
- Return type:
- Raises:
Forbidden – You do not have permissions to end this poll.
HTTPException – Ending this poll failed.
- to_reference(*, fail_if_not_exists=True)[source]#
Creates a
MessageReference
from the current message.New in version 1.6.
- Parameters:
fail_if_not_exists (
bool
) –Whether replying using the message reference should raise
HTTPException
if the message no longer exists or Discord could not fetch the message.New in version 1.7.
- Returns:
The reference to this message.
- Return type:
- class discord.DeletedReferencedMessage(parent)[source]#
A special sentinel type that denotes whether the resolved message referenced message had since been deleted.
The purpose of this class is to separate referenced messages that could not be fetched and those that were previously fetched but have since been deleted.
New in version 1.6.
- Parameters:
parent (
MessageReference
) –
- property id#
The message ID of the deleted referenced message.
- property channel_id#
The channel ID of the deleted referenced message.
- property guild_id#
The guild ID of the deleted referenced message.
- asyncclear
- defis_custom_emoji
- asyncremove
- defusers
- class discord.Reaction(*, message, data, emoji=None)[source]#
Represents a reaction to a message.
Depending on the way this object was created, some of the attributes can have a value of
None
.- x == y
Checks if two reactions are equal. This works by checking if the emoji is the same. So two messages with the same reaction will be considered “equal”.
- x != y
Checks if two reactions are not equal.
- hash(x)
Returns the reaction’s hash.
- str(x)
Returns the string form of the reaction’s emoji.
- emoji#
The reaction emoji. May be a custom emoji, or a unicode emoji.
- Type:
Union[
Emoji
,PartialEmoji
,str
]
- Parameters:
message (Message) –
data (ReactionPayload) –
emoji (PartialEmoji | Emoji | str | None) –
- async for ... in users(*, limit=None, after=None, type=None)[source]#
Returns an
AsyncIterator
representing the users that have reacted to the message.The
after
parameter must represent a member and meet theabc.Snowflake
abc.- Parameters:
limit (Optional[
int
]) – The maximum number of results to return. If not provided, returns all the users who reacted to the message.after (Optional[
abc.Snowflake
]) – For pagination, reactions are sorted by member.type (Optional[
ReactionType
]) – The type of reaction to get users for. Defaults to normal.
- 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.- Raises:
HTTPException – Getting the users for the reaction failed.
- Return type:
ReactionIterator
Examples
Usage
# I do not actually recommend doing this. async for user in reaction.users(): await channel.send(f'{user} has reacted with {reaction.emoji}!')
Flattening into a list:
users = await reaction.users().flatten() # users is now a list of User... winner = random.choice(users) await channel.send(f'{winner} has won the raffle.')
Getting super reactors:
users = await reaction.users(type=ReactionType.burst).flatten()
- property burst_colours#
Returns a list possible
Colour
this super reaction can be.There is an alias for this named
burst_colors
.
- property burst_colors#
Returns a list possible
Colour
this super reaction can be.There is an alias for this named
burst_colours
.
- property count_details#
Returns
ReactionCountDetails
for the individual counts of normal and super reactions made.
- await remove(user)[source]#
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.
- Return type:
- await clear()[source]#
This function is a coroutine.
Clears this reaction from the message.
You need the
manage_messages
permission to use this. :rtype:None
New in version 1.3.
- Raises:
HTTPException – Clearing the reaction failed.
Forbidden – You do not have the proper permissions to clear the reaction.
NotFound – The emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
Monetization#
- class discord.SKU(*, data)[source]#
Represents a Discord SKU (stock-keeping unit).
New in version 2.5.
- Parameters:
data (
SKU
) –
- class discord.Entitlement(*, data, state)[source]#
Represents a Discord entitlement.
New in version 2.5.
- type#
The type of entitlement.
- Type:
- starts_at#
When the entitlement starts.
- Type:
Union[
datetime.datetime
,MISSING
]
- ends_at#
When the entitlement expires.
- Type:
Union[
datetime.datetime
,MISSING
]
- consumed#
Whether or not this entitlement has been consumed. This will always be
False
for entitlements that are not of typeEntitlementType.consumable
.- Type:
- Parameters:
data (
Entitlement
) –state (
ConnectionState
) –
- await consume()[source]#
This function is a coroutine.
Consumes this entitlement.
This can only be done on entitlements of type
EntitlementType.consumable
.- Raises:
TypeError – The entitlement is not consumable.
HTTPException – Consuming the entitlement failed.
- Return type:
- await delete()[source]#
This function is a coroutine.
Deletes a test entitlement.
A test entitlement is an entitlement that was created using
Guild.create_test_entitlement()
orUser.create_test_entitlement()
.- Raises:
HTTPException – Deleting the entitlement failed.
- Return type:
Guild#
- afk_channel
- afk_timeout
- approximate_member_count
- approximate_presence_count
- banner
- bitrate_limit
- categories
- channels
- chunked
- created_at
- default_notifications
- default_role
- description
- discovery_splash
- emoji_limit
- emojis
- explicit_content_filter
- features
- filesize_limit
- forum_channels
- icon
- id
- invites_disabled
- jump_url
- large
- max_members
- max_presences
- max_video_channel_users
- me
- member_count
- members
- mfa_level
- name
- nsfw_level
- owner
- owner_id
- preferred_locale
- premium_progress_bar_enabled
- premium_subscriber_role
- premium_subscribers
- premium_subscription_count
- premium_tier
- public_updates_channel
- roles
- rules_channel
- scheduled_events
- self_role
- shard_id
- splash
- stage_channels
- stage_instances
- sticker_limit
- stickers
- system_channel
- system_channel_flags
- text_channels
- threads
- unavailable
- verification_level
- voice_channels
- voice_client
- asyncactive_threads
- defaudit_logs
- asyncban
- asyncbans
- asyncbulk_ban
- defby_category
- asyncchange_voice_state
- asyncchunk
- asynccreate_auto_moderation_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_test_entitlement
- asynccreate_text_channel
- asynccreate_voice_channel
- asyncdelete
- asyncdelete_auto_moderation_rule
- asyncdelete_emoji
- asyncdelete_sticker
- asyncedit
- asyncedit_onboarding
- asyncedit_role_positions
- asyncedit_welcome_screen
- asyncedit_widget
- defentitlements
- asyncestimate_pruned_members
- asyncfetch_auto_moderation_rule
- asyncfetch_auto_moderation_rules
- asyncfetch_ban
- asyncfetch_channel
- asyncfetch_channels
- asyncfetch_emoji
- asyncfetch_emojis
- asyncfetch_member
- deffetch_members
- asyncfetch_roles
- asyncfetch_scheduled_event
- asyncfetch_scheduled_events
- asyncfetch_sticker
- asyncfetch_stickers
- defget_channel
- defget_channel_or_thread
- defget_member
- defget_member_named
- defget_role
- defget_scheduled_event
- defget_stage_instance
- defget_thread
- asyncintegrations
- asyncinvites
- asynckick
- asyncleave
- asynconboarding
- asyncprune_members
- asyncquery_members
- asyncsearch_members
- asyncset_mfa_required
- asynctemplates
- asyncunban
- asyncvanity_invite
- asyncwebhooks
- asyncwelcome_screen
- asyncwidget
- class discord.Guild(*, data, state)[source]#
Represents a Discord guild.
This is referred to as a “server” in the official Discord UI.
- x == y
Checks if two guilds are equal.
- x != y
Checks if two guilds are not equal.
- hash(x)
Returns the guild’s hash.
- str(x)
Returns the guild’s name.
- stickers#
All stickers that the guild owns.
New in version 2.0.
- Type:
Tuple[
GuildSticker
, …]
- afk_channel#
The channel that denotes the AFK channel.
None
if it doesn’t exist.- Type:
Optional[
VoiceChannel
]
- 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_members#
The maximum amount of members for the guild.
Note
This attribute is only available via
Client.fetch_guild()
.- Type:
Optional[
int
]
- max_video_channel_users#
The maximum amount of users in a video channel.
New in version 1.4.
- Type:
Optional[
int
]
- 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:
- verification_level#
The guild’s verification level.
- Type:
- explicit_content_filter#
The guild’s explicit content filter.
- Type:
- default_notifications#
The guild’s notification settings.
- Type:
- features#
A list of features that the guild has. The features that a guild can have are subject to arbitrary change by Discord. You can find a catalog of guild features here.
- Type:
List[
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:
Indicates if the guild has premium progress bar enabled.
New in version 2.0.
- Type:
- preferred_locale#
The preferred locale for the guild. Used when filtering Server Discovery results to a specific language.
- Type:
Optional[
str
]
- approximate_member_count#
The approximate number of members in the guild. This is
None
unless the guild is obtained usingClient.fetch_guild()
withwith_counts=True
.New in version 2.0.
- Type:
Optional[
int
]
- approximate_presence_count#
The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded. This is
None
unless the guild is obtained usingClient.fetch_guild()
withwith_counts=True
.New in version 2.0.
- Type:
Optional[
int
]
- Parameters:
data (
Guild
) –state (
ConnectionState
) –
- async for ... in fetch_members(*, limit=1000, after=None)[source]#
Retrieves an
AsyncIterator
that enables receiving the guild’s members. In order to use this,Intents.members()
must be enabled.Note
This method is an API call. For general usage, consider
members
instead.New in version 1.3.
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of members to retrieve. Defaults to 1000. PassNone
to fetch all members. Note that this is potentially slow.after (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Retrieve members after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
Member
– The member with the member data parsed.- Raises:
ClientException – The members intent is not enabled.
HTTPException – Getting the members failed.
- Return type:
MemberIterator
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, user=None, action=None)[source]#
Returns an
AsyncIterator
that enables receiving the guild’s audit logs.You must have the
view_audit_log
permission to use this.See API documentation for more information about the before and after parameters.
- 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 datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Union[
abc.Snowflake
,datetime.datetime
]) – Retrieve entries after this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.user (
abc.Snowflake
) – The moderator to filter entries from.action (
AuditLogAction
) – The action to filter with.
- Yields:
AuditLogEntry
– The audit log entry.- Raises:
Forbidden – You are not allowed to fetch audit logs
HTTPException – An error occurred while fetching the audit logs.
- Return type:
AuditLogIterator
Examples
Getting the first 100 entries:
async for entry in guild.audit_logs(limit=100): print(f'{entry.user} did {entry.action} to {entry.target}')
Getting entries for a specific action:
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban): print(f'{entry.user} banned {entry.target}')
Getting entries made by a specific user:
entries = await guild.audit_logs(limit=None, user=guild.me).flatten() await channel.send(f'I made {len(entries)} moderation actions.')
- property channels#
A list of channels that belong to this guild.
- property threads#
A list of threads that you have permission to view.
New in version 2.0.
- property jump_url#
Returns a URL that allows the client to jump to the guild.
New in version 2.0.
- 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.
- property voice_channels#
A list of voice channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- property stage_channels#
A list of stage channels that belong to this guild.
New in version 1.7.
This is sorted by the position and are in UI order from top to bottom.
- property forum_channels#
A list of forum channels that belong to this guild.
New in version 2.0.
This is sorted by the position and are in UI order from top to bottom.
- property me#
Similar to
Client.user
except an instance ofMember
. This is essentially used to get the member version of yourself.
- property voice_client#
Returns the
VoiceClient
associated with this guild, if any.
- property text_channels#
A list of text channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- property categories#
A list of categories that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- by_category()[source]#
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_or_thread(channel_id, /)[source]#
Returns a channel or thread with the given ID.
New in version 2.0.
- Parameters:
channel_id (
int
) – The ID to search for.- Returns:
The returned channel or thread or
None
if not found.- Return type:
Optional[Union[
Thread
,abc.GuildChannel
]]
- get_channel(channel_id, /)[source]#
Returns a channel with the given ID.
Note
This does not search for threads.
- Parameters:
channel_id (
int
) – The ID to search for.- Returns:
The returned channel or
None
if not found.- Return type:
Optional[
abc.GuildChannel
]
- property system_channel#
Returns the guild’s channel used for system messages.
If no channel is set, then this returns
None
.
- property system_channel_flags#
Returns the guild’s system channel settings.
- property rules_channel#
Return’s the guild’s channel used for the rules. The guild must be a Community guild.
If no channel is set, then this returns
None
.New in version 1.3.
- property public_updates_channel#
Return’s the guild’s channel where admins and moderators of the guilds receive notices from Discord. The guild must be a Community guild.
If no channel is set, then this returns
None
.New in version 1.4.
- property emoji_limit#
The maximum number of emoji slots this guild has.
- property sticker_limit#
The maximum number of sticker slots this guild has.
New in version 2.0.
- property bitrate_limit#
The maximum bitrate for voice channels this guild can have.
- property filesize_limit#
The maximum number of bytes files can have when uploaded to this guild.
- property members#
A list of members that belong to this guild.
A list of members who have “boosted” this guild.
- 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.
- property default_role#
Gets the @everyone role that all members have by default.
Gets the premium subscriber role, AKA “boost” role, in this guild.
New in version 1.6.
- property self_role#
Gets the role associated with this client’s user, if any.
New in version 1.6.
- property stage_instances#
Returns a
list
of the guild’s stage instances that are currently running.New in version 2.0.
- get_stage_instance(stage_instance_id, /)[source]#
Returns a stage instance with the given ID.
New in version 2.0.
- Parameters:
stage_instance_id (
int
) – The ID to search for.- Returns:
The stage instance or
None
if not found.- Return type:
Optional[
StageInstance
]
- property owner#
The member that owns the guild.
- property icon#
Returns the guild’s icon asset, if available.
- property banner#
Returns the guild’s banner asset, if available.
- property splash#
Returns the guild’s invite splash asset, if available.
- property discovery_splash#
Returns the guild’s discovery splash asset, if available.
- 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.
- 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.
- property shard_id#
Returns the shard ID for this guild if applicable.
- property created_at#
Returns the guild’s creation time in UTC.
- property invites_disabled#
Returns a boolean indicating if the guild invites are disabled.
- get_member_named(name, /)[source]#
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 look up 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, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)[source]#
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.- Parameters:
name (
str
) – The channel’s name.overwrites (Dict[Union[
Role
,Member
,Snowflake
],PermissionOverwrite
]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel
]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int
) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (
str
) – The new channel’s topic.slowmode_delay (
int
) – Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is 21600.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.
- Returns:
The channel that was just created.
- Return type:
- 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.
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)
- await create_voice_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=...)[source]#
This function is a coroutine.
This is similar to
create_text_channel()
except makes aVoiceChannel
instead.- Parameters:
name (
str
) – The channel’s name.overwrites (Dict[Union[
Role
,Member
,Snowflake
],PermissionOverwrite
]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel
]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int
) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.bitrate (
int
) – The channel’s preferred audio bitrate in bits per second.user_limit (
int
) – The channel’s limit for number of members that can be in a voice channel.rtc_region (Optional[
VoiceRegion
]) –The region for the voice channel’s voice communication. A value of
None
indicates automatic voice region detection.New in version 1.7.
video_quality_mode (
VideoQualityMode
) –The camera video quality for the voice channel’s participants.
New in version 2.0.
reason (Optional[
str
]) – The reason for creating this channel. Shows up on the audit log.
- Returns:
The channel that was just created.
- Return type:
- 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.
- await create_stage_channel(name, *, topic, position=..., overwrites=..., category=None, reason=None)[source]#
This function is a coroutine.
This is similar to
create_text_channel()
except makes aStageChannel
instead.New in version 1.7.
- Parameters:
name (
str
) – The channel’s name.topic (
str
) – The new channel’s topic.overwrites (Dict[Union[
Role
,Member
,Snowflake
],PermissionOverwrite
]) – The overwrites to apply to the 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.reason (Optional[
str
]) – The reason for creating this channel. Shows up on the audit log.
- Returns:
The channel that was just created.
- Return type:
- 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.
- await create_forum_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_reaction_emoji=...)[source]#
This function is a coroutine.
Creates a
ForumChannel
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.- Parameters:
name (
str
) – The channel’s name.overwrites (Dict[Union[
Role
,Member
,Snowflake
],PermissionOverwrite
]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel
]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int
) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (
str
) – The new channel’s topic.slowmode_delay (
int
) – Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is 21600.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.default_reaction_emoji (Optional[
Emoji
|int
|str
]) –The default reaction emoji. Can be a unicode emoji or a custom emoji in the forms:
Emoji
, snowflake ID, string representation (eg. ‘<a:emoji_name:emoji_id>’).New in version v2.5.
- Returns:
The channel that was just created.
- Return type:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The argument is not in proper form.
Examples
Creating a basic channel:
channel = await guild.create_forum_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_forum_channel('secret', overwrites=overwrites)
- await create_category(name, *, overwrites=..., reason=None, position=...)[source]#
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.- Returns:
The channel that was just created.
- Return type:
- 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.
- Parameters:
- await create_category_channel(name, *, overwrites=..., reason=None, position=...)#
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.- Returns:
The channel that was just created.
- Return type:
- 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.
- Parameters:
- await leave()[source]#
This function is a coroutine.
Leaves the guild. :rtype:
None
Note
You cannot leave the guild that you own, you must delete it instead via
delete()
.- Raises:
HTTPException – Leaving the guild failed.
- await delete()[source]#
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.
- Return type:
- await set_mfa_required(required, *, reason=None)[source]#
This function is a coroutine.
Set whether it is required to have MFA enabled on your account to perform moderation actions. You must be the guild owner to do this.
- Parameters:
- Raises:
HTTPException – The operation failed.
Forbidden – You are not the owner of the guild.
- Return type:
- await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., afk_channel=..., owner=..., afk_timeout=..., default_notifications=..., verification_level=..., explicit_content_filter=..., system_channel=..., system_channel_flags=..., preferred_locale=..., rules_channel=..., public_updates_channel=..., premium_progress_bar_enabled=..., disable_invites=...)[source]#
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.
Changed in version 2.0: The discovery_splash and community keyword-only parameters were added.
Changed in version 2.0: The newly updated guild is returned.
- Parameters:
name (
str
) – The new name of the guild.description (Optional[
str
]) – The new description of the guild. Could beNone
for no description. This is only available to guilds that containPUBLIC
inGuild.features
.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. This is only available to guilds that containBANNER
inGuild.features
.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
.community (
bool
) – Whether the guild should be a Community guild. If set toTrue
, bothrules_channel
andpublic_updates_channel
parameters are required.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.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.premium_progress_bar_enabled (
bool
) – Whether the guild should have premium progress bar enabled.disable_invites (
bool
) – Whether the guild should have server invites enabled or disabled.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.
- Returns:
The newly updated guild. Note that this has the same limitations as mentioned in
Client.fetch_guild()
and may not have full data.- Return type:
- await fetch_channels()[source]#
This function is a coroutine.
Retrieves all
abc.GuildChannel
that the guild has.Note
This method is an API call. For general usage, consider
channels
instead.New in version 1.2.
- Returns:
All channels in the guild.
- Return type:
Sequence[
abc.GuildChannel
]- Raises:
InvalidData – An unknown channel type was received from Discord.
HTTPException – Retrieving the channels failed.
- await active_threads()[source]#
This function is a coroutine.
Returns a list of active
Thread
that the client can access.This includes both private and public threads.
New in version 2.0.
- Returns:
The active threads
- Return type:
List[
Thread
]- Raises:
HTTPException – The request to get the active threads failed.
- await search_members(query, *, limit=1000)[source]#
Search for guild members whose usernames or nicknames start with the query string. Unlike
fetch_members()
, this does not requireIntents.members()
.Note
This method is an API call. For general usage, consider filtering
members
instead.New in version 2.6.
- Parameters:
- Returns:
The list of members that have matched the query.
- Return type:
List[
Member
]- Raises:
HTTPException – Getting the members failed.
- await fetch_member(member_id, /)[source]#
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.- Returns:
The member from the member ID.
- Return type:
- Raises:
Forbidden – You do not have access to the guild.
HTTPException – Fetching the member failed.
- await fetch_ban(user)[source]#
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.- Returns:
The
BanEntry
object for the specified user.- Return type:
- 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.
- await fetch_channel(channel_id, /)[source]#
This function is a coroutine.
Retrieves a
abc.GuildChannel
orThread
with the specified ID.Note
This method is an API call. For general usage, consider
get_channel_or_thread()
instead.New in version 2.0.
- Returns:
The channel from the ID.
- Return type:
Union[
abc.GuildChannel
,Thread
]- Raises:
InvalidData – An unknown channel type was received from Discord or the guild the channel belongs to is not the same as the one in this object points to.
HTTPException – Retrieving the channel failed.
NotFound – Invalid Channel ID.
Forbidden – You do not have permission to fetch this channel.
- Parameters:
channel_id (int) –
- bans(limit=None, before=None, after=None)[source]#
This function is a coroutine.
Retrieves an
AsyncIterator
that enables receiving the guild’s bans. In order to use this, you must have theban_members
permission. Users will always be returned in ascending order sorted by user ID. If both thebefore
andafter
parameters are provided, only before is respected.Changed in version 2.5: The
before
. andafter
parameters were changed. They are now of the typeabc.Snowflake
instead of SnowflakeTime to comply with the discord api.Changed in version 2.0: The
limit
,before
. andafter
parameters were added. Now returns aBanIterator
instead of a list ofBanEntry
objects.All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of bans to retrieve. Defaults to 1000.before (Optional[
abc.Snowflake
]) – Retrieve bans before the given user.after (Optional[
abc.Snowflake
]) – Retrieve bans after the given user.
- Yields:
BanEntry
– The ban entry for the ban.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Return type:
BanIterator
Examples
Usage
async for ban in guild.bans(limit=150): print(ban.user.name)
Flattening into a list
bans = await guild.bans(limit=150).flatten() # bans is now a list of BanEntry...
- await prune_members(*, days, compute_prune_count=True, roles=..., reason=None)[source]#
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 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 (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()[source]#
This function is a coroutine.
Gets the list of templates from this guild.
Requires
manage_guild
permissions.New in version 1.7.
- await webhooks()[source]#
This function is a coroutine.
Gets the list of webhooks from this guild.
Requires
manage_webhooks
permissions.
- await estimate_pruned_members(*, days, roles=...)[source]#
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 (List[
abc.Snowflake
]) –A list of
abc.Snowflake
that represent roles to include in the estimate. If a member has a role that is not specified, they’ll be excluded.New in version 1.7.
- Returns:
The number of members estimated to be pruned.
- Return type:
- 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
.
- await invites()[source]#
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.- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite
]- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- await create_template(*, name, description=...)[source]#
This function is a coroutine.
Creates a template for the guild.
You must have the
manage_guild
permission to do this.New in version 1.7.
- await create_integration(*, type, id)[source]#
This function is a coroutine.
Attaches an integration to the guild.
You must have the
manage_guild
permission to do this.New in version 1.4.
- Parameters:
- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – The account could not be found.
- Return type:
- await integrations()[source]#
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.New in version 1.4.
- Returns:
The list of integrations that are attached to the guild.
- Return type:
List[
Integration
]- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – Fetching the integrations failed.
- await fetch_stickers()[source]#
This function is a coroutine.
Retrieves a list of all
Sticker
s for the guild.New in version 2.0.
Note
This method is an API call. For general usage, consider
stickers
instead.- Raises:
HTTPException – An error occurred fetching the stickers.
- Returns:
The retrieved stickers.
- Return type:
List[
GuildSticker
]
- await fetch_sticker(sticker_id, /)[source]#
This function is a coroutine.
Retrieves a custom
Sticker
from the guild.New in version 2.0.
Note
This method is an API call. For general usage, consider iterating over
stickers
instead.- Parameters:
sticker_id (
int
) – The sticker’s ID.- Returns:
The retrieved sticker.
- Return type:
- Raises:
NotFound – The sticker requested could not be found.
HTTPException – An error occurred fetching the sticker.
- await create_sticker(*, name, description=None, emoji, file, reason=None)[source]#
This function is a coroutine.
Creates a
Sticker
for the guild.You must have
manage_emojis_and_stickers
permission to do this.New in version 2.0.
- Parameters:
name (
str
) – The sticker name. Must be 2 to 30 characters.description (Optional[
str
]) – The sticker’s description. If used, must be 2 to 100 characters.emoji (
str
) – The name of a unicode emoji that represents the sticker’s expression.file (
File
) – The file of the sticker to upload.reason (
str
) – The reason for creating this sticker. Shows up on the audit log.
- Returns:
The created sticker.
- Return type:
- Raises:
Forbidden – You are not allowed to create stickers.
HTTPException – An error occurred creating a sticker.
TypeError – The parameters for the sticker are not correctly formatted.
- await delete_sticker(sticker, *, reason=None)[source]#
This function is a coroutine.
Deletes the custom
Sticker
from the guild.You must have
manage_emojis_and_stickers
permission to do this.New in version 2.0.
- Parameters:
sticker (
abc.Snowflake
) – The sticker you are deleting.reason (Optional[
str
]) – The reason for deleting this sticker. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to delete stickers.
HTTPException – An error occurred deleting the sticker.
- Return type:
None
- await fetch_emojis()[source]#
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, /)[source]#
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.- Returns:
The retrieved emoji.
- Return type:
- Raises:
NotFound – The emoji requested could not be found.
HTTPException – An error occurred fetching the emoji.
- await create_custom_emoji(*, name, image, roles=..., reason=None)[source]#
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 (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 delete_emoji(emoji, *, reason=None)[source]#
This function is a coroutine.
Deletes the custom
Emoji
from the guild.You must have
manage_emojis
permission to do this.- Parameters:
emoji (
abc.Snowflake
) – The emoji you are deleting.reason (Optional[
str
]) – The reason for deleting this emoji. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to delete emojis.
HTTPException – An error occurred deleting the emoji.
- Return type:
None
- await fetch_roles()[source]#
This function is a coroutine.
Retrieves all
Role
that the guild has.Note
This method is an API call. For general usage, consider
roles
instead.New in version 1.3.
- Returns:
All roles in the guild.
- Return type:
List[
Role
]- Raises:
HTTPException – Retrieving the roles failed.
- await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., mentionable=..., reason=None, icon=..., unicode_emoji=...)[source]#
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.- Parameters:
name (
str
) – The role name. Defaults to ‘new role’.permissions (
Permissions
) – The permissions to have. Defaults to no permissions.colour (Union[
Colour
,int
]) – The colour for the role. Defaults toColour.default()
. This is aliased 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
.reason (Optional[
str
]) – The reason for creating this role. Shows up on the audit log.icon (Optional[
bytes
]) – A bytes-like object representing the icon. Only PNG/JPEG/WebP is supported. If this argument is passed,unicode_emoji
is set to None. Only available to guilds that containROLE_ICONS
inGuild.features
.unicode_emoji (Optional[
str
]) – The role’s unicode emoji. If this argument is passed,icon
is set to None. Only available to guilds that containROLE_ICONS
inGuild.features
.
- Returns:
The newly created role.
- Return type:
- Raises:
Forbidden – You do not have permissions to create the role.
HTTPException – Creating the role failed.
InvalidArgument – An invalid keyword argument was given.
- await edit_role_positions(positions, *, reason=None)[source]#
This function is a coroutine.
Bulk edits a list of
Role
in the guild.You must have the
manage_roles
permission to do this.New in version 1.4.
Example:
positions = { bots_role: 1, # penultimate role tester_role: 2, admin_role: 6 } await guild.edit_role_positions(positions=positions)
- Parameters:
- Returns:
A list of all the roles in the guild.
- Return type:
List[
Role
]- Raises:
Forbidden – You do not have permissions to move the roles.
HTTPException – Moving the roles failed.
InvalidArgument – An invalid keyword argument was given.
- await kick(user, *, reason=None)[source]#
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.
- Return type:
None
- await ban(user, *, delete_message_seconds=None, reason=None)[source]#
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_seconds (Optional[
int
]) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.reason (Optional[
str
]) – The reason the user got banned.
- Raises:
Forbidden – You do not have the proper permissions to ban.
HTTPException – Banning failed.
- Return type:
None
- await bulk_ban(*users, delete_message_seconds=None, reason=None)[source]#
This function is a coroutine.
Bulk ban users from the guild.
The users must meet the
abc.Snowflake
abc.You must have the
ban_members
permission to do this.Example Usage:
# Ban multiple users successes, failures = await guild.bulk_ban(user1, user2, user3, ..., reason="Raid") # Ban a list of users successes, failures = await guild.bulk_ban(*users)
- Parameters:
*users (
abc.Snowflake
) – An argument list of users to ban from the guild, up to 200.delete_message_seconds (Optional[
int
]) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.reason (Optional[
str
]) – The reason the users were banned.
- Returns:
Returns two lists: the first contains members that were successfully banned, while the second is members that could not be banned.
- Return type:
Tuple[List[
abc.Snowflake
], List[abc.Snowflake
]]- Raises:
ValueError – You tried to ban more than 200 users.
Forbidden – You do not have the proper permissions to ban.
HTTPException – No users were banned.
- await unban(user, *, reason=None)[source]#
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.
- Return type:
None
- await vanity_invite()[source]#
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.- Returns:
The special vanity invite. If
None
then the guild does not have a vanity invite set.- Return type:
Optional[
Invite
]- Raises:
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the vanity invite failed.
- await widget()[source]#
This function is a coroutine.
Returns the widget of the guild.
Note
The guild must have the widget enabled to get this information.
- Returns:
The guild’s widget.
- Return type:
- Raises:
Forbidden – The widget for this guild is disabled.
HTTPException – Retrieving the widget failed.
- await edit_widget(*, enabled=..., channel=...)[source]#
This function is a coroutine.
Edits the widget of the guild.
You must have the
manage_guild
permission to use thisNew in version 2.0.
- Parameters:
- Raises:
Forbidden – You do not have permission to edit the widget.
HTTPException – Editing the widget failed.
- Return type:
None
- await chunk(*, cache=True)[source]#
This function is a coroutine.
Requests all members that belong to this guild. In order to use this,
Intents.members()
must be enabled.This is a websocket operation and can be slow.
New in version 1.5.
- Parameters:
cache (
bool
) – Whether to cache the members as well.- Raises:
ClientException – The members intent is not enabled.
- Return type:
- await query_members(query=None, *, limit=5, user_ids=None, presences=False, cache=True)[source]#
This function is a coroutine.
Request members that belong to this guild whose username starts with the query given.
This is a websocket operation and can be slow.
New in version 1.3.
- Parameters:
query (Optional[
str
]) – The string that the username’s start with.user_ids (Optional[List[
int
]]) –List of user IDs to search for. If the user ID is not in the guild then it won’t be returned.
New in version 1.4.
limit (Optional[
int
]) – The maximum number of members to send back. If no query is passed, passingNone
returns all members. If aquery
oruser_ids
is passed, must be between 1 and 100. Defaults to 5.presences (Optional[
bool
]) –Whether to request for presences to be provided. This defaults to
False
.New in version 1.6.
cache (
bool
) – Whether to cache the members internally. This makes operations such asget_member()
work for those that matched. Defaults toTrue
.
- Returns:
The list of members that have matched the query.
- Return type:
List[
Member
]- 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.
- await change_voice_state(*, channel, self_mute=False, self_deaf=False)[source]#
This function is a coroutine.
Changes client’s voice state in the guild.
New in version 1.4.
- Parameters:
channel (Optional[Union[
VoiceChannel
,StageChannel
]]) – 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 welcome_screen()[source]#
This function is a coroutine.
Returns the
WelcomeScreen
of the guild.The guild must have
COMMUNITY
infeatures
.You must have the
manage_guild
permission in order to get this.New in version 2.0.
- Returns:
The welcome screen of guild.
- Return type:
- Raises:
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the welcome screen failed somehow.
NotFound – The guild doesn’t have a welcome screen or community feature is disabled.
- await edit_welcome_screen(**options)[source]#
This function is a coroutine.
A shorthand for
WelcomeScreen.edit
without fetching the welcome screen.You must have the
manage_guild
permission in the guild to do this.The guild must have
COMMUNITY
inGuild.features
- Parameters:
description (Optional[
str
]) – The new description of welcome screen.welcome_channels (Optional[List[
WelcomeScreenChannel
]]) – The welcome channels. The order of the channels would be same as the passed list order.enabled (Optional[
bool
]) – Whether the welcome screen should be displayed.reason (Optional[
str
]) – The reason that shows up on audit log.
- Returns:
The edited welcome screen.
- Return type:
- Raises:
HTTPException – Editing the welcome screen failed somehow.
Forbidden – You don’t have permissions to edit the welcome screen.
NotFound – This welcome screen does not exist.
- await fetch_scheduled_events(*, with_user_count=True)[source]#
This function is a coroutine.
Returns a list of
ScheduledEvent
in the guild.Note
This method is an API call. For general usage, consider
scheduled_events
instead.- Parameters:
with_user_count (Optional[
bool
]) – If the scheduled event should be fetched with the number of users that are interested in the events. Defaults toTrue
.- Returns:
The fetched scheduled events.
- Return type:
List[
ScheduledEvent
]- Raises:
ClientException – The scheduled events intent is not enabled.
HTTPException – Getting the scheduled events failed.
- await fetch_scheduled_event(event_id, /, *, with_user_count=True)[source]#
This function is a coroutine.
Retrieves a
ScheduledEvent
from event ID.Note
This method is an API call. If you have
Intents.scheduled_events
, considerget_scheduled_event()
instead.- Parameters:
- Returns:
The scheduled event from the event ID.
- Return type:
Optional[
ScheduledEvent
]- Raises:
HTTPException – Fetching the event failed.
NotFound – Event not found.
- get_scheduled_event(event_id, /)[source]#
Returns a Scheduled Event with the given ID.
- Parameters:
event_id (
int
) – The ID to search for.- Returns:
The scheduled event or
None
if not found.- Return type:
Optional[
ScheduledEvent
]
- await create_scheduled_event(*, name, description=..., start_time, end_time=..., location, privacy_level=<ScheduledEventPrivacyLevel.guild_only: 2>, reason=None, image=...)[source]#
This function is a coroutine. Creates a scheduled event.
- Parameters:
name (
str
) – The name of the scheduled event.description (Optional[
str
]) – The description of the scheduled event.start_time (
datetime.datetime
) – A datetime object of when the scheduled event is supposed to start.end_time (Optional[
datetime.datetime
]) – A datetime object of when the scheduled event is supposed to end.location (
ScheduledEventLocation
) – The location of where the event is happening.privacy_level (
ScheduledEventPrivacyLevel
) – The privacy level of the event. Currently, the only possible value isScheduledEventPrivacyLevel.guild_only
, which is default, so there is no need to change this parameter.reason (Optional[
str
]) – The reason to show in the audit log.image (Optional[
bytes
]) – The cover image of the scheduled event
- Returns:
The created scheduled event.
- Return type:
Optional[
ScheduledEvent
]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- property scheduled_events#
A list of scheduled events in this guild.
- await fetch_auto_moderation_rules()[source]#
This function is a coroutine.
Retrieves a list of auto moderation rules for this guild.
- Returns:
The auto moderation rules for this guild.
- Return type:
List[
AutoModRule
]- Raises:
HTTPException – Getting the auto moderation rules failed.
Forbidden – You do not have the Manage Guild permission.
- await fetch_auto_moderation_rule(id)[source]#
This function is a coroutine.
Retrieves a
AutoModRule
from rule ID.- Returns:
The requested auto moderation rule.
- Return type:
- Raises:
HTTPException – Getting the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- Parameters:
id (
int
) –
- await create_auto_moderation_rule(*, name, event_type, trigger_type, trigger_metadata, actions, enabled=False, exempt_roles=None, exempt_channels=None, reason=None)[source]#
Creates an auto moderation rule.
- Parameters:
name (
str
) – The name of the auto moderation rule.event_type (
AutoModEventType
) – The type of event that triggers the rule.trigger_type (
AutoModTriggerType
) – The rule’s trigger type.trigger_metadata (
AutoModTriggerMetadata
) – The rule’s trigger metadata.actions (List[
AutoModAction
]) – The actions to take when the rule is triggered.enabled (
bool
) – Whether the rule is enabled.exempt_roles (List[
abc.Snowflake
]) – A list of roles that are exempt from the rule.exempt_channels (List[
abc.Snowflake
]) – A list of channels that are exempt from the rule.reason (Optional[
str
]) – The reason for creating the rule. Shows up in the audit log.
- Returns:
The new auto moderation rule.
- Return type:
- Raises:
HTTPException – Creating the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- await onboarding()[source]#
This function is a coroutine.
Returns the
Onboarding
flow for the guild.New in version 2.5.
- Returns:
The onboarding flow for the guild.
- Return type:
- Raises:
HTTPException – Retrieving the onboarding flow failed somehow.
- await edit_onboarding(*, prompts=..., default_channels=..., enabled=..., mode=..., reason=...)[source]#
This function is a coroutine.
A shorthand for
Onboarding.edit
without fetching the onboarding flow.You must have the
manage_guild
andmanage_roles
permissions in the guild to do this.- Parameters:
prompts (Optional[List[
OnboardingPrompt
]]) – The new list of prompts for this flow.default_channels (Optional[List[
Snowflake
]]) – The new default channels that users are opted into.enabled (Optional[
bool
]) – Whether onboarding should be enabled. Setting this toTrue
requires the guild to haveCOMMUNITY
infeatures
and at least 7default_channels
.mode (Optional[
OnboardingMode
]) – The new onboarding mode.reason (Optional[
str
]) – The reason that shows up on Audit log.
- Returns:
The updated onboarding flow.
- Return type:
- Raises:
HTTPException – Editing the onboarding flow failed somehow.
Forbidden – You don’t have permissions to edit the onboarding flow.
- await delete_auto_moderation_rule(id, *, reason=None)[source]#
Deletes an auto moderation rule.
- Parameters:
- Raises:
HTTPException – Deleting the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- Return type:
None
- await create_test_entitlement(sku)[source]#
This function is a coroutine.
Creates a test entitlement for the guild.
- Parameters:
sku (
Snowflake
) – The SKU to create a test entitlement for.- Returns:
The created entitlement.
- Return type:
- entitlements(skus=None, before=None, after=None, limit=100, exclude_ended=False)[source]#
Returns an
AsyncIterator
that enables fetching the guild’s entitlements.This is identical to
Client.entitlements()
with theguild
parameter.New in version 2.6.
- Parameters:
skus (list[
abc.Snowflake
] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake
|datetime.datetime
| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake
|datetime.datetime
| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int
]) – The number of entitlements to retrieve. IfNone
, retrieves every entitlement, which may be slow. Defaults to100
.exclude_ended (
bool
) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse
.
- Yields:
Entitlement
– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- accent_color
- accent_colour
- activities
- activity
- avatar
- avatar_decoration
- banner
- bot
- color
- colour
- communication_disabled_until
- created_at
- default_avatar
- desktop_status
- discriminator
- display_avatar
- display_name
- dm_channel
- flags
- global_name
- guild
- guild_avatar
- guild_permissions
- id
- is_migrated
- joined_at
- jump_url
- mention
- mobile_status
- mutual_guilds
- name
- nick
- pending
- premium_since
- public_flags
- raw_status
- roles
- status
- system
- timed_out
- top_role
- voice
- web_status
- asyncadd_roles
- asyncban
- defcan_send
- asynccreate_dm
- asynccreate_test_entitlement
- asyncedit
- defentitlements
- asyncfetch_message
- defget_role
- defhistory
- defis_on_mobile
- asynckick
- defmentioned_in
- asyncmove_to
- asyncpins
- asyncremove_roles
- asyncremove_timeout
- asyncrequest_to_speak
- asyncsend
- asynctimeout
- asynctimeout_for
- asynctrigger_typing
- deftyping
- asyncunban
- class discord.Member(*, data, guild, state)[source]#
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 member’s name with the discriminator or global_name.
- joined_at#
An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be
None
.- Type:
Optional[
datetime.datetime
]
- 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.
- Type:
Tuple[Union[
BaseActivity
,Spotify
]]
An aware datetime object that specifies the date and time in UTC when the member used their “Nitro boost” on the guild, if available. This could be
None
.- Type:
Optional[
datetime.datetime
]
- communication_disabled_until#
An aware datetime object that specifies the date and time in UTC when the member will be removed from timeout.
New in version 2.0.
- Type:
Optional[
datetime.datetime
]
- flags#
Extra attributes of the member.
New in version 2.6.
- Type:
- Parameters:
data (
MemberWithUser
) –guild (
Guild
) –state (
ConnectionState
) –
- 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.- Parameters:
limit (Optional[
int
]) – The number of messages to retrieve. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) – If set toTrue
, return messages in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.
- Yields:
Message
– The message with the message data parsed.- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Return type:
HistoryIterator
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.
- 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. :rtype:
Typing
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(): # simulate something heavy await asyncio.sleep(10) await channel.send('done!')
- property discriminator#
Equivalent to
User.discriminator
- property system#
Equivalent to
User.system
- property created_at#
Equivalent to
User.created_at
- property default_avatar#
Equivalent to
User.default_avatar
- property avatar#
Equivalent to
User.avatar
- property 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 raw_status#
The member’s overall status as a string value.
New in version 1.5.
- property status#
The member’s overall status. If the value is unknown, then it will be a
str
instead.
- property mobile_status#
The member’s status on a mobile device, if applicable.
- property desktop_status#
The member’s status on the desktop client, if applicable.
- property web_status#
The member’s status on the web client, if applicable.
- property global_name#
The member’s global name, if applicable.
- is_on_mobile()[source]#
A helper function that determines if a member is active on a mobile device.
- Return type:
- property colour#
A property that returns a colour denoting the rendered colour for the member. If the default colour is the one rendered then an instance of
Colour.default()
is returned.There is an alias for this named
color
.
- 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
.
- 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.
- property mention#
Returns a string that allows you to mention the member.
- property display_name#
Returns the user’s display name. This will either be their guild specific nickname, global name or username.
- property display_avatar#
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
- property guild_avatar#
Returns an
Asset
for the guild avatar the member has. If unavailable,None
is returned.New in version 2.0.
- 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.Note
A user may have multiple activities, these can be accessed under
activities
.
- property top_role#
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
- property guild_permissions#
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use
abc.GuildChannel.permissions_for()
.This does take into consideration guild ownership and the administrator implication.
- property voice#
Returns the member’s current voice state.
- property timed_out#
Returns whether the member is timed out.
New in version 2.0.
- await ban(*, delete_message_seconds=None, reason=None)[source]#
This function is a coroutine.
Bans this member. Equivalent to
Guild.ban()
.
- await unban(*, reason=None)[source]#
This function is a coroutine.
Unbans this member. Equivalent to
Guild.unban()
.- Parameters:
reason (str | None) –
- Return type:
None
- await kick(*, reason=None)[source]#
This function is a coroutine.
Kicks this member. Equivalent to
Guild.kick()
.- Parameters:
reason (str | None) –
- Return type:
None
- await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., reason=None, communication_disabled_until=..., bypass_verification=...)[source]#
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
communication_disabled_until
bypass_verification
See note below
Note
bypass_verification may be edited under three scenarios:
Client has
Permissions.manage_guild
Client has
Permissions.manage_roles
Client has ALL THREE of
Permissions.moderate_members
,Permissions.kick_members
, andPermissions.ban_members
All parameters are optional.
Changed in version 1.1: Can now pass
None
tovoice_channel
to kick a member from voice.Changed in version 2.0: The newly member is now optionally returned, if applicable.
- Parameters:
nick (Optional[
str
]) – The member’s new nickname. UseNone
to remove the nickname.mute (
bool
) – Indicates if the member should be guild muted or un-muted.deafen (
bool
) – Indicates if the member should be guild deafened or un-deafened.suppress (
bool
) –Indicates if the member should be suppressed in stage channels.
New in version 1.7.
roles (List[
Role
]) – The member’s new list of roles. This replaces the roles.voice_channel (Optional[Union[
VoiceChannel
,StageChannel
]]) – The voice channel to move the member to. PassNone
to kick them from voice.reason (Optional[
str
]) – The reason for editing this member. Shows up on the audit log.communication_disabled_until (Optional[
datetime.datetime
]) –Temporarily puts the member in timeout until this time. If the value is
None
, then the user is removed from timeout.New in version 2.0.
bypass_verification (Optional[
bool
]) –Indicates if the member should bypass the guild’s verification requirements.
New in version 2.6.
- Returns:
The newly updated member, if applicable. This is only returned when certain fields are updated.
- Return type:
Optional[
Member
]- Raises:
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
- await timeout(until, *, reason=None)[source]#
This function is a coroutine.
Applies a timeout to a member in the guild until a set datetime.
You must have the
moderate_members
permission to timeout a member.- Parameters:
until (
datetime.datetime
) – The date and time to timeout the member for. If this isNone
then the member is removed from timeout.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to timeout members.
HTTPException – An error occurred doing the request.
- Return type:
None
- await timeout_for(duration, *, reason=None)[source]#
This function is a coroutine.
Applies a timeout to a member in the guild for a set duration. A shortcut method for
timeout()
, and equivalent totimeout(until=datetime.utcnow() + duration, reason=reason)
.You must have the
moderate_members
permission to timeout a member.- Parameters:
duration (
datetime.timedelta
) – The duration to timeout the member for.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to timeout members.
HTTPException – An error occurred doing the request.
- Return type:
None
- await remove_timeout(*, reason=None)[source]#
This function is a coroutine.
Removes the timeout from a member.
You must have the
moderate_members
permission to remove the timeout.This is equivalent to calling
timeout()
and passingNone
to theuntil
parameter.- Parameters:
reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to remove the timeout.
HTTPException – An error occurred doing the request.
- Return type:
None
- await request_to_speak()[source]#
This function is a coroutine.
Request to speak in the connected channel.
Only applies to stage channels. :rtype:
None
Note
Requesting members that are not the client is equivalent to
edit
providingsuppress
asFalse
.New in version 1.7.
- Raises:
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
- await move_to(channel, *, reason=None)[source]#
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.
- Return type:
None
- await add_roles(*roles, reason=None, atomic=True)[source]#
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.
- Return type:
None
- property avatar_decoration#
Equivalent to
User.avatar_decoration
- can_send(*objects)#
Returns a
bool
indicating whether you have the permissions to send the object(s).
- await create_test_entitlement(sku)#
This function is a coroutine.
Creates a test entitlement for the user.
- Parameters:
sku (
Snowflake
) – The SKU to create a test entitlement for.- Returns:
The created entitlement.
- Return type:
- entitlements(skus=None, before=None, after=None, limit=100, exclude_ended=False)#
Returns an
AsyncIterator
that enables fetching the user’s entitlements.This is identical to
Client.entitlements()
with theuser
parameter.New in version 2.6.
- Parameters:
skus (list[
abc.Snowflake
] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake
|datetime.datetime
| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake
|datetime.datetime
| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int
]) – The number of entitlements to retrieve. IfNone
, retrieves every entitlement, which may be slow. Defaults to100
.exclude_ended (
bool
) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse
.
- Yields:
Entitlement
– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- await fetch_message(id, /)#
This function is a coroutine.
Retrieves a single
Message
from the destination.- Parameters:
id (
int
) – The message ID to look for.- Returns:
The message asked for.
- Return type:
- 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.
- property is_migrated#
Equivalent to
User.is_migrated
- property jump_url#
Equivalent to
User.jump_url
- 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.- Returns:
The messages that are currently pinned.
- Return type:
List[
Message
]- Raises:
HTTPException – Retrieving the pinned messages failed.
- await remove_roles(*roles, reason=None, atomic=True)[source]#
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.
- Return type:
None
- await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, silent=None)#
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. Specifying both parameters will lead to an exception.To upload a single embed, the
embed
parameter should be used with a singleEmbed
object. To upload multiple embeds, theembeds
parameter should be used with alist
ofEmbed
objects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
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.file (
File
) – The file to upload.files (List[
File
]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
str
,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.enforce_nonce (Optional[
bool
]) –Whether
nonce
is enforced to be validated.New in version 2.5.
delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
,PartialMessage
]) –A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
view (
discord.ui.View
) – A Discord UI View to add to the message.embeds (List[
Embed
]) –A list of embeds to upload. Must be a maximum of 10.
New in version 2.0.
stickers (Sequence[Union[
GuildSticker
,StickerItem
]]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
suppress (
bool
) – Whether to suppress embeds for the message.silent (
bool
) –Whether to suppress push and desktop notifications for the message.
New in version 2.4.
poll (
Poll
) –The poll to send.
New in version 2.6.
- Returns:
The message that was sent.
- Return type:
- 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 you specified bothembed
andembeds
, or thereference
object is not aMessage
,MessageReference
orPartialMessage
.
- asynccreate_guild
- asyncdelete
- asyncedit
- asyncsync
- class discord.Template(*, state, data)[source]#
Represents a Discord template.
New in version 1.4.
- created_at#
An aware datetime in UTC representing when the template was created.
- Type:
- updated_at#
An aware datetime in UTC representing when the template was last updated. This is referred to as “last synced” in the official Discord client.
- Type:
- Parameters:
state (
ConnectionState
) –data (
Template
) –
- await create_guild(name, icon=None)[source]#
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.icon (
bytes
) – The bytes-like object representing the icon. SeeClientUser.edit()
for more details on what is expected.
- Returns:
The guild created. This is not the same guild that is added to cache.
- Return type:
- Raises:
HTTPException – Guild creation failed.
InvalidArgument – Invalid icon image format given. Must be PNG or JPG.
- await sync()[source]#
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.New in version 1.7.
Changed in version 2.0: The template is no longer synced in-place, instead it is returned.
- Returns:
The newly synced template.
- Return type:
- Raises:
HTTPException – Syncing the template failed.
Forbidden – You don’t have permissions to sync the template.
NotFound – This template does not exist.
- await edit(*, name=..., description=...)[source]#
This function is a coroutine.
Edit the template metadata.
You must have the
manage_guild
permission in the source guild to do this.New in version 1.7.
Changed in version 2.0: The template is no longer edited in-place, instead it is returned.
- Parameters:
- Returns:
The newly edited template.
- Return type:
- Raises:
HTTPException – Editing the template failed.
Forbidden – You don’t have permissions to edit the template.
NotFound – This template does not exist.
- await delete()[source]#
This function is a coroutine.
Delete the template.
You must have the
manage_guild
permission in the source guild to do this. :rtype:None
New in version 1.7.
- Raises:
HTTPException – Deleting the template failed.
Forbidden – You don’t have permissions to delete the template.
NotFound – This template does not exist.
- property url#
The template url.
New in version 2.0.
AutoMod#
- class discord.AutoModRule(*, state, data)[source]#
Represents a guild’s auto moderation rule.
New in version 2.0.
- x == y
Checks if two rules are equal.
- x != y
Checks if two rules are not equal.
- hash(x)
Returns the rule’s hash.
- str(x)
Returns the rule’s name.
- event_type#
Indicates in what context the rule is checked.
- Type:
- trigger_type#
Indicates what type of information is checked to determine whether the rule is triggered.
- Type:
- trigger_metadata#
The rule’s trigger metadata.
- Type:
- actions#
The actions to perform when the rule is triggered.
- Type:
List[
AutoModAction
]
- Parameters:
state (
ConnectionState
) –data (
AutoModRule
) –
- property guild#
The guild this rule belongs to.
- property creator#
The member who created this rule.
- property exempt_roles#
The roles that are exempt from this rule.
If a role is not found in the guild’s cache, then it will be returned as an
Object
.
- property exempt_channels#
The channels that are exempt from this rule.
If a channel is not found in the guild’s cache, then it will be returned as an
Object
.
- await delete(reason=None)[source]#
This function is a coroutine.
Deletes this rule.
- Parameters:
reason (Optional[
str
]) – The reason for deleting this rule. Shows up in the audit log.- Raises:
Forbidden – You do not have the Manage Guild permission.
HTTPException – The operation failed.
- Return type:
None
- await edit(*, name=..., event_type=..., trigger_metadata=..., actions=..., enabled=..., exempt_roles=..., exempt_channels=..., reason=None)[source]#
This function is a coroutine.
Edits this rule.
- Parameters:
name (
str
) – The rule’s new name.event_type (
AutoModEventType
) – The new context in which the rule is checked.trigger_metadata (
AutoModTriggerMetadata
) – The new trigger metadata.actions (List[
AutoModAction
]) – The new actions to perform when the rule is triggered.enabled (
bool
) – Whether this rule is enabled.exempt_roles (List[
abc.Snowflake
]) – The roles that will be exempt from this rule.exempt_channels (List[
abc.Snowflake
]) – The channels that will be exempt from this rule.reason (Optional[
str
]) – The reason for editing this rule. Shows up in the audit log.
- Returns:
The newly updated rule, if applicable. This is only returned when fields are updated.
- Return type:
Optional[
AutoModRule
]- Raises:
Forbidden – You do not have the Manage Guild permission.
HTTPException – The operation failed.
- class discord.AutoModAction(action_type, metadata)[source]#
Represents an action for a guild’s auto moderation rule.
New in version 2.0.
- type#
The action’s type.
- Type:
- metadata#
The action’s metadata.
- Type:
- Parameters:
action_type (
AutoModActionType
) –metadata (
AutoModActionMetadata
) –
- class discord.AutoModActionMetadata(channel_id=..., timeout_duration=..., custom_message=...)[source]#
Represents an action’s metadata.
Depending on the action’s type, different attributes will be used.
New in version 2.0.
- channel_id#
The ID of the channel to send the message to. Only for actions of type
AutoModActionType.send_alert_message
.- Type:
- timeout_duration#
How long the member that triggered the action should be timed out for. Only for actions of type
AutoModActionType.timeout
.- Type:
- custom_message#
An additional message shown to members when their message is blocked. Maximum 150 characters. Only for actions of type
AutoModActionType.block_message
.- Type:
- class discord.AutoModTriggerMetadata(keyword_filter=..., regex_patterns=..., presets=..., allow_list=..., mention_total_limit=...)[source]#
Represents a rule’s trigger metadata, defining additional data used to determine when a rule triggers.
Depending on the trigger type, different metadata attributes will be used:
Attribute
Trigger Types
AutoModTriggerType.keyword
,AutoModTriggerType.keyword_preset
Each attribute has limits that may change based on the trigger type. See here for information on attribute limits.
New in version 2.0.
- regex_patterns#
A list of regex patterns to filter using Rust-flavored regex, which is not fully compatible with regex syntax supported by the builtin re module.
New in version 2.4.
- Type:
List[
str
]
- presets#
A list of preset keyword sets to filter.
- Type:
List[
AutoModKeywordPresetType
]
Invites#
- class discord.PartialInviteGuild(state, data, id)[source]#
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.
- verification_level#
The partial guild’s verification level.
- Type:
- features#
A list of features the guild has. See
Guild.features
for more information.- Type:
List[
str
]
- Parameters:
state (
ConnectionState
) –data (
InviteGuild
) –id (
int
) –
- property created_at#
Returns the guild’s creation time in UTC.
- property icon#
Returns the guild’s icon asset, if available.
- property banner#
Returns the guild’s banner asset, if available.
- property splash#
Returns the guild’s invite splash asset, if available.
- class discord.PartialInviteChannel(data)[source]#
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.
- type#
The partial channel’s type.
- Type:
- Parameters:
data (
PartialChannel
) –
- property mention#
The string that allows you to mention the channel.
- property created_at#
Returns the channel’s creation time in UTC.
- asyncdelete
- defset_scheduled_event
- class discord.Invite(*, state, data, guild=None, channel=None)[source]#
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
Client.fetch_invite()
with with_counts enabledClient.fetch_invite()
with with_counts enabledClient.fetch_invite()
with with_expiration enabledIf it’s not in the table above then it is available by all methods.
- max_age#
How long before the invite expires in seconds. A value of
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
]]
- created_at#
An aware UTC datetime object denoting the time the invite was created.
- Type:
- 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_presence_count#
The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded.
- Type:
Optional[
int
]
- expires_at#
The expiration date of the invite. If the value is
None
when received through Client.fetch_invite with with_expiration enabled, the invite will never expire.New in version 2.0.
- Type:
Optional[
datetime.datetime
]
- channel#
The channel the invite is for.
- Type:
Union[
abc.GuildChannel
,Object
,PartialInviteChannel
]
- target_type#
The type of target for the voice channel invite.
New in version 2.0.
- Type:
- target_user#
The user whose stream to display for this invite, if any.
New in version 2.0.
- Type:
Optional[
User
]
- target_application#
The embedded application the invite targets, if any.
New in version 2.0.
- Type:
Optional[
PartialAppInfo
]
- scheduled_event#
The scheduled event linked with the invite.
- Type:
Optional[
ScheduledEvent
]
- Parameters:
state (ConnectionState) –
data (InvitePayload | VanityInvitePayload) –
guild (PartialInviteGuild | Guild | None) –
channel (PartialInviteChannel | GuildChannel | None) –
- property id#
Returns the proper code portion of the invite.
- property url#
A property that retrieves the invite URL.
- await delete(*, reason=None)[source]#
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)[source]#
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.New in version 2.0.
- Parameters:
event (
ScheduledEvent
) – The scheduled event object to link.- Return type:
Role#
- asyncdelete
- asyncedit
- defis_assignable
- defis_bot_managed
- defis_default
- defis_integration
- defis_premium_subscriber
- class discord.Role(*, guild, state, data)[source]#
Represents a Discord role in a
Guild
.- x == y
Checks if two roles are equal.
- x != y
Checks if two roles are not equal.
- x > y
Checks if a role is higher than another in the hierarchy.
- x < y
Checks if a role is lower than another in the hierarchy.
- x >= y
Checks if a role is higher or equal to another in the hierarchy.
- x <= y
Checks if a role is lower or equal to another in the hierarchy.
- hash(x)
Return the role’s hash.
- str(x)
Returns the role’s name.
- position#
The position of the role. This number is usually positive. The bottom role has a position of 0.
Warning
Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.
- Type:
- managed#
Indicates if the role is managed by the guild through some form of integrations such as Twitch.
- Type:
- unicode_emoji#
The role’s unicode emoji. Only available to guilds that contain
ROLE_ICONS
inGuild.features
.New in version 2.0.
- Type:
Optional[
str
]
- Parameters:
guild (
Guild
) –state (
ConnectionState
) –data (
Role
) –
- is_bot_managed()[source]#
Whether the role is associated with a bot. :rtype:
bool
New in version 1.6.
Whether the role is the premium subscriber, AKA “boost”, role for the guild. :rtype:
bool
New in version 1.6.
- is_integration()[source]#
Whether the role is managed by an integration. :rtype:
bool
New in version 1.6.
- is_assignable()[source]#
Whether the role is able to be assigned or removed by the bot. :rtype:
bool
New in version 2.0.
- property permissions#
Returns the role’s permissions.
- property colour#
Returns the role colour. An alias exists under
color
.
- property color#
Returns the role color. An alias exists under
colour
.
- property created_at#
Returns the role’s creation time in UTC.
- property mention#
Returns a string that allows you to mention a role.
- property members#
Returns all the members with this role.
- property icon#
Returns the role’s icon asset, if available.
New in version 2.0.
- await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., mentionable=..., position=..., reason=..., icon=..., unicode_emoji=...)[source]#
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.Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead. Added
icon
andunicode_emoji
.- 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.reason (Optional[
str
]) – The reason for editing this role. Shows up on the audit log.icon (Optional[
bytes
]) – A bytes-like object representing the icon. Only PNG/JPEG/WebP is supported. If this argument is passed,unicode_emoji
is set to None. Only available to guilds that containROLE_ICONS
inGuild.features
. Could beNone
to denote removal of the icon.unicode_emoji (Optional[
str
]) – The role’s unicode emoji. If this argument is passed,icon
is set to None. Only available to guilds that containROLE_ICONS
inGuild.features
.
- Returns:
The newly edited role.
- Return type:
- 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)[source]#
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.
- Return type:
None
- class discord.RoleTags(data)[source]#
Represents tags on a role.
A role tag is a piece of extra information attached to a managed role that gives it context for the reason the role is managed.
While this can be accessed, a useful interface is also provided in the
Role
andGuild
classes as well.New in version 1.6.
- Parameters:
data (
RoleTags
) –
Whether the role is the premium subscriber, AKA “boost”, role for the guild.
- Return type:
Scheduled Event#
- class discord.ScheduledEvent(*, state, guild, creator, data)[source]#
Represents a Discord Guild Scheduled Event.
- x == y
Checks if two scheduled events are equal.
- x != y
Checks if two scheduled events are not equal.
- hash(x)
Returns the scheduled event’s hash.
- str(x)
Returns the scheduled event’s name.
New in version 2.0.
- start_time#
The time when the event will start
- Type:
- end_time#
The time when the event is supposed to end.
- Type:
Optional[
datetime.datetime
]
- status#
The status of the scheduled event.
- Type:
- location#
The location of the event. See
ScheduledEventLocation
for more information.- Type:
- subscriber_count#
The number of users that have marked themselves as interested in the event.
- Type:
Optional[
int
]
- creator_id#
The ID of the user who created the event. It may be
None
because events created before October 25th, 2021 haven’t had their creators tracked.- Type:
Optional[
int
]
- privacy_level#
The privacy level of the event. Currently, the only possible value is
ScheduledEventPrivacyLevel.guild_only
, which is default, so there is no need to use this attribute.
- Parameters:
- property created_at#
Returns the scheduled event’s creation time in UTC.
- property interested#
An alias to
subscriber_count
- property url#
The url to reference the scheduled event.
- property cover#
Returns the scheduled event cover image asset, if available.
- await edit(*, reason=None, name=..., description=..., status=..., location=..., start_time=..., end_time=..., cover=..., privacy_level=<ScheduledEventPrivacyLevel.guild_only: 2>)[source]#
This function is a coroutine.
Edits the Scheduled Event’s data
All parameters are optional unless
location.type
isScheduledEventLocationType.external
, thenend_time
is required.Will return a new
ScheduledEvent
object if applicable.- Parameters:
name (
str
) – The new name of the event.description (
str
) – The new description of the event.location (
ScheduledEventLocation
) – The location of the event.status (
ScheduledEventStatus
) – The status of the event. It is recommended, however, to usestart()
,complete()
, andcancel()
to edit statuses instead.start_time (
datetime.datetime
) – The new starting time for the event.end_time (
datetime.datetime
) – The new ending time of the event.privacy_level (
ScheduledEventPrivacyLevel
) – The privacy level of the event. Currently, the only possible value isScheduledEventPrivacyLevel.guild_only
, which is default, so there is no need to change this parameter.reason (Optional[
str
]) – The reason to show in the audit log.cover (Optional[
bytes
]) – The cover image of the scheduled event.
- Returns:
The newly updated scheduled event object. This is only returned when certain fields are updated.
- Return type:
Optional[
ScheduledEvent
]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- await delete()[source]#
This function is a coroutine.
Deletes the scheduled event.
- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- Return type:
- await start(*, reason=None)[source]#
This function is a coroutine.
Starts the scheduled event. Shortcut from
edit()
.Note
This method can only be used if
status
isScheduledEventStatus.scheduled
.- Parameters:
reason (Optional[
str
]) – The reason to show in the audit log.- Returns:
The newly updated scheduled event object.
- Return type:
Optional[
ScheduledEvent
]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- await complete(*, reason=None)[source]#
This function is a coroutine.
Ends/completes the scheduled event. Shortcut from
edit()
.Note
This method can only be used if
status
isScheduledEventStatus.active
.- Parameters:
reason (Optional[
str
]) – The reason to show in the audit log.- Returns:
The newly updated scheduled event object.
- Return type:
Optional[
ScheduledEvent
]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- await cancel(*, reason=None)[source]#
This function is a coroutine.
Cancels the scheduled event. Shortcut from
edit()
.Note
This method can only be used if
status
isScheduledEventStatus.scheduled
.- Parameters:
reason (Optional[
str
]) – The reason to show in the audit log.- Returns:
The newly updated scheduled event object.
- Return type:
Optional[
ScheduledEvent
]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- subscribers(*, limit=100, as_member=False, before=None, after=None)[source]#
Returns an
AsyncIterator
representing the users or members subscribed to the event.The
after
andbefore
parameters must represent member or user objects and meet theabc.Snowflake
abc.Note
Even is
as_member
is set toTrue
, if the user is outside the guild, it will be aUser
object.- Parameters:
limit (Optional[
int
]) – The maximum number of results to return.as_member (Optional[
bool
]) – Whether to fetchMember
objects instead of user objects. There may still beUser
objects if the user is outside the guild.before (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Retrieves users before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Retrieves users after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields: