Discord Models

Models are classes that are received from Discord and are not meant to be created by the user of the library.

Danger

The classes listed below are not intended to be created by users and are also read-only.

For example, this means that you should not make your own User instances nor should you modify the User instance yourself.

If you want to get one of these model classes instances they’d have to be through the cache, and a common way of doing so is through the utils.find() function or attributes of model classes that you receive from the events specified in the Event Reference.

Note

Nearly all classes here have __slots__ defined which means that it is impossible to have dynamic attributes to the data classes.

ClientUser

class discord.ClientUser

Bases: BaseUser

Represents your Discord user.

Changed in version 2.0: The name attribute was renamed to username due to the (upcoming) username changes.

x == y

Checks if two users are equal.

x != y

Checks if two users are not equal.

hash(x)

Return the user’s hash.

str(x)

Returns the username if is_migrated is true, else the user’s name with discriminator.

Note

When the migration is complete, this will always return the username .

username

The user’s username.

Type:

str

global_name

The user’s global name if set. In the client UI, this is referred to as “Display Name”.

New in version 2.0.

Type:

Optional[str]

id

The user’s unique ID.

Type:

int

discriminator

The user’s discriminator. This is given when the username has conflicts.

Type:

str

avatar

The avatar hash the user has. Could be None.

Type:

Optional[str]

bot

Specifies if the user is a bot account.

Type:

bool

system

Specifies if the user is a system user (i.e. represents Discord officially).

Type:

bool

locale

The IETF language tag used to identify the language the user is using.

Type:

Optional[str]

mfa_enabled

Specifies if the user has MFA turned on and working.

Type:

bool

await edit(username=MISSING, global_name=MISSING, avatar=MISSING)

This function is a coroutine.

Edits the current profile of the client.

Note

To upload an avatar, a bytes-like object must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via open('some_filename', 'rb') and the bytes-like object is given through the use of fp.read().

The only image formats supported for uploading is JPEG and PNG.

Parameters:
  • username (str) – The new username you wish to change to.

  • global_name (str) – The new global name you wish to change to.

  • avatar (bytes) – A bytes-like object representing the image to upload. Could be None to denote no avatar.

Raises:
property accent_color

A colour object that represents the user’s banner colour.

Note

This information is only available via Client.fetch_user().

Type:

Optional[Colour]

property accent_colour

An alias for accent_color.

Type:

Optional[Colour]

avatar_decoration_url_as(*, format=None, size=1024)

Returns an Asset for the avatar decoration the user has. Could be None.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the avatar decoration to. If the format is None, then it is automatically detected into static_format.

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format, or invalid size.

Returns:

The resulting CDN asset if any.

Return type:

Optional[Asset]

property avatar_url

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

This is equivalent to calling avatar_url_as() with the default parameters (i.e. webp/gif detection and a size of 1024).

Type:

Asset

avatar_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the avatar to. If the format is None, then it is automatically detected into either ‘gif’ or static_format depending on the avatar being animated or not.

  • static_format (Optional[str]) – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or static_format, or invalid size.

Returns:

The resulting CDN asset.

Return type:

Asset

property banner_color

A colour object that represents the user’s banner colour.

Note

This information is only available via Client.fetch_user().

Type:

Optional[Colour]

property banner_colour

A colour object that represents the user’s banner colour.

Note

This information is only available via Client.fetch_user().

Type:

Optional[Colour]

property banner_url

Returns an asset for the banner the user has, if any. This is equal to calling banner_url_as() with the default arguments.

Returns:

The resulting CDN asset if any.

Return type:

Optional[Asset]

Type:

Optional[Asset]

banner_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the banner the user has. Could be None.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated banners. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the banner to. If the format is None, then it is automatically detected into either ‘gif’ or static_format depending on the banner being animated or not.

  • static_format (Optional[str]) – Format to attempt to convert only non-animated banner to. Defaults to ‘webp’

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or static_format, or invalid size.

Returns:

The resulting CDN asset if any.

Return type:

Optional[Asset]

property color

A property that returns a color denoting the rendered color for the user. This always returns Colour.default().

There is an alias for this named colour.

Type:

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.

Type:

Colour

property created_at

Returns the user’s creation time in UTC.

This is when the user’s Discord account was created.

Type:

datetime.datetime

property default_avatar

Returns the default avatar for a given user. For non-migrated users this is calculated by the user’s discriminator. For migrated users this is calculated by the user’s ID.

Type:

DefaultAvatar

property default_avatar_url

Returns a URL for a user’s default avatar.

Type:

Asset

property display_avatar

Returns the users display avatar.

For regular users this is equal to avatar_url.

Type:

Asset

property display_name

Returns the user’s display name.

For regular users this is just their global_name if set else their username, but if they have a guild specific nickname then that is returned instead.

Type:

str

property hex_banner_color

Returns a hexadecimal representation of the user’s banner colour, if available.

Type:

Optional[str]

is_avatar_animated()

bool: Indicates if the user has an animated avatar.

is_banner_animated()

bool: Indicates if the user has an animated banner.

property is_migrated

Indicates if the user has migrated to the new username system.

Type:

bool

property mention

Returns a string that allows you to mention the given user.

Type:

str

mentioned_in(message)

Checks if the user is mentioned in the specified message.

Parameters:

message (Message) – The message to check if you’re mentioned in.

Returns:

Indicates if the user is mentioned in the message.

Return type:

bool

property name

This is an alias of username which replaces the previous name attribute.

Note

It is recommended to use username instead as this might be removed in the future.

Type:

str

permissions_in(channel)

An alias for abc.GuildChannel.permissions_for().

Basically equivalent to:

channel.permissions_for(self)
Parameters:

channel (abc.GuildChannel) – The channel to check your permissions for.

property public_flags

The publicly available flags the user has.

Type:

PublicUserFlags

User

class discord.User

Bases: BaseUser, Messageable

Represents a Discord user.

Changed in version 2.0: The name attribute was renamed to username due to the (upcoming) username changes.

x == y

Checks if two users are equal.

x != y

Checks if two users are not equal.

hash(x)

Return the user’s hash.

str(x)

Returns the username if is_migrated is true, else the user’s name with discriminator.

Note

When the migration is complete, this will always return the username.

username

The user’s username.

Type:

str

global_name

The user’s global name if set. In the client UI, this is referred to as “Display Name”.

New in version 2.0.

Type:

Optional[str]

id

The user’s unique ID.

Type:

int

discriminator

The user’s discriminator.

Deprecated since version 2.0.

Important

This will be removed in the future. Read more about it here.

Type:

str

avatar

The avatar hash the user has. Could be None.

Type:

Optional[str]

banner

The banner hash the user has. Could be None.

Note

This is only available via Client.fetch_user().

New in version 2.0.

Type:

Optional[str]

avatar_decoration

The avatar decoration hash the user has. Could be None.

New in version 2.0.

Type:

Optional[str]

bot

Specifies if the user is a bot account.

Type:

bool

system

Specifies if the user is a system user (i.e. represents Discord officially).

Type:

bool

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)

Returns an AsyncIterator that enables receiving the destination’s message history.

You must have read_message_history permissions to use this.

Examples

Usage

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • after (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • around (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.

  • oldest_first (Optional[bool]) – If set to True, return messages in oldest->newest order. Defaults to True if after is specified, otherwise False.

Raises:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Yields:

Message – The message with the message data parsed.

async with typing()

Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

Note

This is both a regular context manager and an async context manager. This means that both with and async with work with this.

Example Usage:

async with channel.typing():
    # do expensive stuff here
    await asyncio.sleep(15)

await channel.send('done!')
property dm_channel

Returns the channel associated with this user if it exists.

If this returns None, you can create a DM channel by calling the create_dm() coroutine function.

Type:

Optional[DMChannel]

property mutual_guilds

The guilds that the user shares with the client.

Note

This will only return mutual guilds within the client’s internal cache.

New in version 1.7.

Type:

List[Guild]

property accent_color

A colour object that represents the user’s banner colour.

Note

This information is only available via Client.fetch_user().

Type:

Optional[Colour]

property accent_colour

An alias for accent_color.

Type:

Optional[Colour]

avatar_decoration_url_as(*, format=None, size=1024)

Returns an Asset for the avatar decoration the user has. Could be None.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the avatar decoration to. If the format is None, then it is automatically detected into static_format.

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format, or invalid size.

Returns:

The resulting CDN asset if any.

Return type:

Optional[Asset]

property avatar_url

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

This is equivalent to calling avatar_url_as() with the default parameters (i.e. webp/gif detection and a size of 1024).

Type:

Asset

avatar_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the avatar to. If the format is None, then it is automatically detected into either ‘gif’ or static_format depending on the avatar being animated or not.

  • static_format (Optional[str]) – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or static_format, or invalid size.

Returns:

The resulting CDN asset.

Return type:

Asset

property banner_color

A colour object that represents the user’s banner colour.

Note

This information is only available via Client.fetch_user().

Type:

Optional[Colour]

property banner_colour

A colour object that represents the user’s banner colour.

Note

This information is only available via Client.fetch_user().

Type:

Optional[Colour]

property banner_url

Returns an asset for the banner the user has, if any. This is equal to calling banner_url_as() with the default arguments.

Returns:

The resulting CDN asset if any.

Return type:

Optional[Asset]

Type:

Optional[Asset]

banner_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the banner the user has. Could be None.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated banners. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the banner to. If the format is None, then it is automatically detected into either ‘gif’ or static_format depending on the banner being animated or not.

  • static_format (Optional[str]) – Format to attempt to convert only non-animated banner to. Defaults to ‘webp’

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or static_format, or invalid size.

Returns:

The resulting CDN asset if any.

Return type:

Optional[Asset]

property color

A property that returns a color denoting the rendered color for the user. This always returns Colour.default().

There is an alias for this named colour.

Type:

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.

Type:

Colour

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:

DMChannel

property created_at

Returns the user’s creation time in UTC.

This is when the user’s Discord account was created.

Type:

datetime.datetime

property default_avatar

Returns the default avatar for a given user. For non-migrated users this is calculated by the user’s discriminator. For migrated users this is calculated by the user’s ID.

Type:

DefaultAvatar

property default_avatar_url

Returns a URL for a user’s default avatar.

Type:

Asset

property display_avatar

Returns the users display avatar.

For regular users this is equal to avatar_url.

Type:

Asset

property display_name

Returns the user’s display name.

For regular users this is just their global_name if set else their username, but if they have a guild specific nickname then that is returned instead.

Type:

str

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

This can only be used by bot accounts.

Parameters:

id (int) – The message ID to look for.

Raises:
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

property hex_banner_color

Returns a hexadecimal representation of the user’s banner colour, if available.

Type:

Optional[str]

is_avatar_animated()

bool: Indicates if the user has an animated avatar.

is_banner_animated()

bool: Indicates if the user has an animated banner.

property is_migrated

Indicates if the user has migrated to the new username system.

Type:

bool

property mention

Returns a string that allows you to mention the given user.

Type:

str

mentioned_in(message)

Checks if the user is mentioned in the specified message.

Parameters:

message (Message) – The message to check if you’re mentioned in.

Returns:

Indicates if the user is mentioned in the message.

Return type:

bool

property name

This is an alias of username which replaces the previous name attribute.

Note

It is recommended to use username instead as this might be removed in the future.

Type:

str

permissions_in(channel)

An alias for abc.GuildChannel.permissions_for().

Basically equivalent to:

channel.permissions_for(self)
Parameters:

channel (abc.GuildChannel) – The channel to check your permissions for.

await pins()

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

Raises:

HTTPException – Retrieving the pinned messages failed.

Returns:

The messages that are currently pinned.

Return type:

List[Message]

property public_flags

The publicly available flags the user has.

Type:

PublicUserFlags

await send(content=None, *, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content). If the content is set to None (the default), then the embed parameter must be provided.

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects.

If the embed parameter is provided, it must be of type Embed and it must be a rich embed type.

Parameters:
  • content (str) – The content of the message to send.

  • tts (bool) – Indicates if the message should be sent using text-to-speech.

  • embed (Embed) – The rich embed for the content.

  • embeds (List[Embed]) – A list containing up to ten embeds

  • components (List[Union[ActionRow, List[Union[Button, Select]]]]) – A list of up to five ActionRow`s or :class:`list, each containing up to five Button or one Select like object.

  • file (File) – The file to upload.

  • files (List[File]) – A list of files to upload. Must be a maximum of 10.

  • stickers (List[GuildSticker]) – A list of up to 3 discord.GuildSticker that should be sent with the message.

  • nonce (int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    New in version 1.4.

  • reference (Union[Message, MessageReference]) –

    A reference to the Message to which you are replying, this can be created using to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the replied_user attribute of allowed_mentions or by setting mention_author.

    New in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    New in version 1.6.

  • suppress_embeds (bool) – Whether to supress embeds send with the message, default to False

  • suppress_notifications (bool) –

    Whether to suppress desktop- & push-notifications for this message, default to False

    Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.

    New in version 2.0.

Raises:
Returns:

The message that was sent.

Return type:

Message

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

Typing indicator will go away after 10 seconds, or after a message is sent.

Attachment

class discord.Attachment

Bases: Hashable

Represents an attachment from Discord.

str(x)

Returns the URL of the attachment.

x == y

Checks if the attachment is equal to another attachment.

x != y

Checks if the attachment is not equal to another attachment.

hash(x)

Returns the hash of the attachment.

Changed in version 1.7: Attachment can now be cast to str and is hashable.

Changed in version 2.0: The ephemeral, description, duration and waveform attributes were added.

id

The attachment ID.

Type:

int

size

The attachment size in bytes.

Type:

int

height

The attachment’s height, in pixels. Only applicable to images and videos.

Type:

Optional[int]

width

The attachment’s width, in pixels. Only applicable to images and videos.

Type:

Optional[int]

filename

The attachment’s filename.

Type:

str

url

The attachment URL. If the message this attachment was attached to is deleted, then this will 404.

Type:

str

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:

str

content_type

The attachment’s media type

Type:

Optional[str]

ephemeral

Whether the attachment is ephemeral (part of an ephemeral message or was provided in a slash-command option).

Type:

bool

description

The description for the file.

Type:

Optional[str]

duration

The duration of the audio file (currently only for voice messages).

Type:

Optional[float]

is_spoiler()

bool: Whether this attachment contains a spoiler.

property waveform

The waveform of the audio file (currently only for voice messages).

Type:

Optional[List[:class:`int]]`

to_dict()

dict: A minimal dictionary containing the filename and description of the attachment.

await save(fp, *, seek_begin=True, use_cached=False)

This function is a coroutine.

Saves this attachment into a file-like object.

Parameters:
  • fp (Union[io.BufferedIOBase, os.PathLike]) – The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead.

  • seek_begin (bool) – Whether to seek to the beginning of the file after saving is successfully done.

  • use_cached (bool) – Whether to use proxy_url rather than url when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.

Raises:
Returns:

The number of bytes written.

Return type:

int

await read(*, use_cached=False)

This function is a coroutine.

Retrieves the content of this attachment as a bytes object.

New in version 1.1.

Parameters:

use_cached (bool) – Whether to use proxy_url rather than url when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.

Raises:
  • HTTPException – Downloading the attachment failed.

  • Forbidden – You do not have permissions to access this attachment

  • NotFound – The attachment was deleted.

Returns:

The contents of the attachment.

Return type:

bytes

await to_file(*, use_cached=False, spoiler=False, description=MISSING)

This function is a coroutine.

Converts the attachment into a File suitable for sending via abc.Messageable.send().

New in version 1.3.

Parameters:
  • use_cached (bool) –

    Whether to use proxy_url rather than url when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.

    New in version 1.4.

  • spoiler (bool) –

    Whether the file is a spoiler.

    New in version 1.4.

  • description (bool) –

    The description (alt text) for the file.

    This will be default to the description. Set the value to None to supress this. .. versionadded:: 2.0

Raises:
  • HTTPException – Downloading the attachment failed.

  • Forbidden – You do not have permissions to access this attachment

  • NotFound – The attachment was deleted.

Returns:

The attachment as a file suitable for sending.

Return type:

File

Asset

Methods
class discord.Asset

Bases: object

Represents a CDN asset on Discord.

str(x)

Returns the URL of the CDN asset.

len(x)

Returns the length of the CDN asset’s URL.

bool(x)

Checks if the Asset has a URL.

x == y

Checks if the asset is equal to another asset.

x != y

Checks if the asset is not equal to another asset.

hash(x)

Returns the hash of the asset.

await read()

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

Warning

PartialEmoji won’t have a connection state if user created, and a URL won’t be present if a custom image isn’t associated with the asset, e.g. a guild with no custom icon.

New in version 1.1.

Raises:
Returns:

The content of the asset.

Return type:

bytes

await save(fp, *, seek_begin=True)

This function is a coroutine.

Saves this asset into a file-like object.

Parameters:
Raises:
Returns:

The number of bytes written.

Return type:

int

Message

class discord.Message

Bases: Hashable, Generic[_MCH]

Represents a message from Discord.

x == y

Checks if two messages are equal.

x != y

Checks if two messages are not equal.

hash(x)

Returns the message’s hash.

tts

Specifies if the message was done with text-to-speech. This can only be accurately received in on_message() due to a discord limitation.

Type:

bool

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:

MessageType

author

A Member that sent the message. If channel is a private channel or the user has left the guild, then it is a User instead.

Type:

abc.User

content

The actual contents of the message.

Type:

str

nonce

The value used by the discord guild and the client to verify that the message is successfully sent. This is not stored long term within Discord’s servers and is only used ephemerally.

embeds

A list of embeds the message has.

Type:

List[Embed]

components

A list of components the message has.

Type:

List[ActionRow]:

channel

The TextChannel, ThreadChannel or VoiceChannel that the message was sent from. Could be a DMChannel or GroupChannel if it’s a private message.

Type:

Union[abc.Messageable, ThreadChannel]

reference

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

Type:

Optional[MessageReference]

mention_everyone

Specifies if the message mentions everyone.

Note

This does not check if the @everyone or the @here text is in the message itself. Rather this boolean indicates if either the @everyone or the @here text is in the message and it did end up mentioning.

Type:

bool

mentions

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_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]

id

The message ID.

Type:

int

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]

pinned

Specifies if the message is currently pinned.

Type:

bool

flags

Extra features of the message.

New in version 1.3.

Type:

MessageFlags

reactions

Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.

Type:

List[Reaction]

activity

The activity associated with this message. Sent with Rich-Presence related messages that for example, request joining, spectating, or listening to or with another member.

It is a dictionary with the following optional keys:

  • type: An integer denoting the type of message activity being requested.

  • party_id: The party ID associated with the party.

Type:

Optional[dict]

application

The rich presence enabled application associated with this message.

It is a dictionary with the following keys:

  • id: A string representing the application’s ID.

  • name: A string representing the application’s name.

  • description: A string representing the application’s description.

  • icon: A string representing the icon ID of the application.

  • cover_image: A string representing the embed’s image asset ID.

Type:

Optional[dict]

stickers

A list of stickers given to the message.

New in version 1.6.

Type:

List[Sticker]

interaction

The interaction this message is a response to, if any.

New in version 2.0.

Type:

Optional[MessageInteraction]

role_subscription

The data of the role subscription purchase or renewal that prompted this MessageType.role_subscription_purchase message.

New in version 2.0.

Type:

Optional[RoleSubscriptionInfo]

position

A generally increasing integer with potentially gaps or duplicates that represents the approximate position of the message in a thread.

New in version 2.0.

Type:

Optional[int]

guild

The guild that the message belongs to if any.

Type:

Optional[Guild]

raw_mentions

A property that returns an array of user IDs matched with the syntax of <@user_id> in the message content.

This allows you to receive the user IDs of mentioned users even in a private message context.

Type:

List[int]

raw_channel_mentions

A property that returns an array of channel IDs matched with the syntax of <#channel_id> in the message content.

Type:

List[int]

raw_role_mentions

A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content.

Type:

List[int]

clean_content

A property that returns the content in a “cleaned up” manner. This basically means that mentions are transformed into the way the client shows it. e.g. <#id> will transform into #name.

This will also transform @everyone and @here mentions into non-mentions.

Note

This does not affect markdown. If you want to escape or remove markdown then use utils.escape_markdown() or utils.remove_markdown() respectively, along with this function.

Type:

str

property created_at

The message’s creation time in UTC.

Type:

datetime.datetime

property edited_at

A naive UTC datetime object containing the edited time of the message.

Type:

Optional[datetime.datetime]

property jump_url

Returns a URL that allows the client to jump to this message.

Type:

str

is_system()

bool: Whether the message is a system message.

New in version 1.3.

system_content

A property that returns the content that is rendered regardless of the Message.type.

In the case of MessageType.default, this just returns the regular Message.content. Otherwise, this returns an English message denoting the contents of the system message.

Type:

str

property all_components

Returns all Button’s and Select like objects that are contained in the message

property all_buttons

Returns all Button’s that are contained in the message

property all_select_menus

Returns all Select like objects that are contained in the message

property thread

The thread that belongs to this message, if there is one

Type:

Optional[ThreadChannel]

await delete(*, delay=None, reason=None)

This function is a coroutine.

Deletes the message.

Your own messages could be deleted without any proper permissions. However, to delete other people’s messages, you need the manage_messages permission.

Changed in version 1.1: Added the new delay keyword-only parameter.

Parameters:
  • delay (Optional[float]) – If provided, the number of seconds to wait in the background before deleting the message. If the deletion fails then it is silently ignored.

  • reason (Optional[str]) – The reason for deleting this message. Shows up on the audit log.

Raises:
  • Forbidden – You do not have proper permissions to delete the message.

  • NotFound – The message was deleted already

  • HTTPException – Deleting the message failed.

await edit(*, content=MISSING, embed=MISSING, embeds=MISSING, components=MISSING, attachments=MISSING, keep_existing_attachments=False, delete_after=None, allowed_mentions=MISSING, suppress_embeds=MISSING)

This function is a coroutine.

Edits the message.

The content must be able to be transformed into a string via str(content).

Warning

Since API v10, the attachments must contain all attachments that should be present after edit, including retained and new attachments.

Changed in version 1.3: The suppress keyword-only parameter was added.

Changed in version 2.0: The suppress keyword-only parameter was renamed to suppress_embeds.

Changed in version 2.0: The components`, ``attachments and keep_existing_attachments keyword-only parameters were added.

Parameters:
  • content (Optional[str]) – The new content to replace the message with. Could be None to remove the content.

  • embed (Optional[Embed]) – The new embed to replace the original with. Could be None to remove all embeds.

  • embeds (Optional[List[Embed]]) –

    A list containing up to 10 embeds to send. If None or empty, all embeds will be removed.

    If passed, embed does also count towards the limit of 10 embeds.

  • components (List[Union[ActionRow, List[Union[Button, Select]]]]) – A list of up to five ActionRow`s or :class:`list, each containing up to five Button or one Select like object.

  • attachments (List[Union[Attachment, File]]) –

    A list containing previous attachments to keep as well as new files to upload. You can use keep_existing_attachments to auto-add the existing attachments to the list. If None or empty, all attachments will be removed.

    Note

    New files will always appear under existing ones.

  • keep_existing_attachments (bool) –

    Whether to auto-add existing attachments to attachments, defaults to False.

    Note

    Only needed when attachments are passed, otherwise will be ignored.

  • suppress_embeds (bool) – Whether to suppress embeds for the message. This removes all the embeds if set to True. If set to False this brings the embeds back if they were suppressed. Requires manage_messages permissions for messages that aren’t from the bot.

  • delete_after (Optional[float]) – If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.

  • allowed_mentions (Optional[AllowedMentions]) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    New in version 1.4.

Raises:
  • HTTPException – Editing the message failed.

  • Forbidden – Tried to suppress a message without permissions or edited a message’s content or embed that isn’t yours.

await publish()

This function is a coroutine.

Publishes this message to your announcement channel.

If the message is not your own then the manage_messages permission is needed.

Raises:
  • Forbidden – You do not have the proper permissions to publish this message.

  • HTTPException – Publishing the message failed.

await pin(*, suppress_system_message=False, reason=None)

This function is a coroutine.

Pins the message.

You must have the manage_messages permission to do this in a non-private channel context.

Parameters:
  • suppress_system_message (bool) –

    When set to True, the function will wait 5 seconds for the system message and delete it. Defaults to False.

    New in version 2.0.

  • 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.

  • TimeoutError – Waiting for the system message timed out.

await unpin(*, reason=None)

This function is a coroutine.

Unpins the message.

You must have the manage_messages permission to do this in a non-private channel context.

Parameters:

reason (Optional[str]) –

The reason for unpinning the message. Shows up on the audit log.

New in version 1.4.

Raises:
  • Forbidden – You do not have permissions to unpin the message.

  • NotFound – The message or channel was not found or deleted.

  • HTTPException – Unpinning the message failed.

await add_reaction(emoji)

This function is a coroutine.

Add a reaction to the message.

The emoji may be a unicode emoji or a custom guild Emoji.

You must have the read_message_history permission to use this. If nobody else has reacted to the message using this emoji, the add_reactions permission is required.

Parameters:

emoji (Union[Emoji, Reaction, PartialEmoji, str]) – The emoji to react with.

Raises:
  • HTTPException – Adding the reaction failed.

  • Forbidden – You do not have the proper permissions to react to the message.

  • NotFound – The emoji you specified was not found.

  • InvalidArgument – The emoji parameter is invalid.

await remove_reaction(emoji, member)

This function is a coroutine.

Remove a reaction by the member from the message.

The emoji may be a unicode emoji or a custom guild Emoji.

If the reaction is not your own (i.e. member parameter is not you) then the manage_messages permission is needed.

The member parameter must represent a member and meet the abc.Snowflake abc.

Parameters:
Raises:
  • HTTPException – Removing the reaction failed.

  • Forbidden – You do not have the proper permissions to remove the reaction.

  • NotFound – The member or emoji you specified was not found.

  • InvalidArgument – The emoji parameter is invalid.

await clear_reaction(emoji)

This function is a coroutine.

Clears a specific reaction from the message.

The emoji may be a unicode emoji or a custom guild Emoji.

You need the manage_messages permission to use this.

New in version 1.3.

Parameters:

emoji (Union[Emoji, Reaction, PartialEmoji, str]) – The emoji to clear.

Raises:
  • HTTPException – Clearing the reaction failed.

  • Forbidden – You do not have the proper permissions to clear the reaction.

  • NotFound – The emoji you specified was not found.

  • InvalidArgument – The emoji parameter is invalid.

await clear_reactions()

This function is a coroutine.

Removes all the reactions from the message.

You need the manage_messages permission to use this.

Raises:
  • HTTPException – Removing the reactions failed.

  • Forbidden – You do not have the proper permissions to remove all the reactions.

await reply(content=None, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)

This function is a coroutine.

A shortcut method to abc.Messageable.send() to reply to the Message.

New in version 1.6.

Raises:
  • HTTPException – Sending the message failed.

  • Forbidden – You do not have the proper permissions to send the message.

  • InvalidArgument – The files list is not of the appropriate size or you specified both file and files.

Returns:

The message that was sent.

Return type:

Message

await create_thread(name, auto_archive_duration=None, slowmode_delay=0, reason=None)

This function is a coroutine.

Creates a new thread in the channel of the message with this message as the starter_message.

Parameters:
  • name (str) – The name of the thread.

  • auto_archive_duration (Optional[AutoArchiveDuration]) – Amount of time after that the thread will auto-hide from the channel list

  • slowmode_delay (int) – Amount of seconds a user has to wait before sending another message (0-21600)

  • reason (Optional[str]) – The reason for creating the thread. Shows up in the audit log.

Raises:
  • TypeError – The channel of the message is not a text or news channel, or the message has already a thread, or auto_archive_duration is not a valid member of AutoArchiveDuration

  • ValueError – The name is of invalid length

  • Forbidden – The bot is missing permissions to create threads in this channel

  • HTTPException – Creating the thread failed

Returns:

The created thread on success

Return type:

ThreadChannel

to_reference(*, fail_if_not_exists=True)

Creates a MessageReference from the current message.

New in version 1.6.

Parameters:

fail_if_not_exists (bool) –

Whether replying using the message reference should raise HTTPException if the message no longer exists or Discord could not fetch the message.

New in version 1.7.

Returns:

The reference to this message.

Return type:

MessageReference

EphemeralMessage

class discord.EphemeralMessage

Bases: object

Like a normal Message but with a modified edit() method and without delete() method.

guild

The guild that the message belongs to, if applicable.

Type:

Optional[Guild]

property all_components

Union[Button, Select]: Yields all buttons and selects that are contained in the message

property all_buttons

Returns all Button’s that are contained in the message

property all_select_menus

Returns all Select’s that are contained in the message

await edit(*, content=MISSING, embed=MISSING, embeds=MISSING, components=MISSING, attachments=MISSING, keep_existing_attachments=False, allowed_mentions=MISSING, suppress_embeds=False, delete_after=None)

This function is a coroutine.

Edits the message.

Parameters:
  • content (Optional[str]) – The new content to replace the message with. Could be None to remove the content.

  • embed (Optional[Embed]) – The new embed to replace the original with. Could be None to remove all embeds.

  • embeds (Optional[List[Embed]]) –

    A list containing up to 10 embeds to send. If None or empty, all embeds will be removed.

    If passed, embed does also count towards the limit of 10 embeds.

  • components (List[Union[ActionRow, List[Union[Button, Select]]]]) – A list of up to five ActionRow`s or :class:`list, each containing up to five Button or one Select like object.

  • attachments (List[Union[Attachment, File]]) –

    A list containing previous attachments to keep as well as new files to upload. You can use keep_existing_attachments to auto-add the existing attachments to the list. If an empty list ([]) is passed, all attachment will be removed.

    Note

    New files will always appear under existing ones.

  • keep_existing_attachments (bool) –

    Whether to auto-add existing attachments to attachments, default False.

    Note

    Only needed when attachments are passed, otherwise will be ignored.

  • suppress_embeds (bool) – Whether to suppress embeds for the message. If True this will remove all embeds from the message. If ´False` it adds them back.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the response we just edited. If the deletion fails, then it is silently ignored.

  • allowed_mentions (Optional[AllowedMentions]) – Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

await delete(*, delay=None)

This function is a coroutine.

Deletes the message.

Note

This can only be used while the interaction token is valid. So within 15 minutes after the interaction.

Parameters:

delay (Optional[float]) – If provided, the number of seconds to wait in the background before deleting the message. If the deletion fails then it is silently ignored.

Raises:
  • NotFound – The message was deleted already or the interaction token expired

  • HTTPException – Deleting the message failed.

MessageInteraction

Attributes
class discord.MessageInteraction

Bases: object

Represents the interaction object of a message that is a response to an interaction without an existing message.

Note

This means responses to ComponentInteraction does not include this, instead including a reference as components always exist on preexisting messages.

New in version 2.0.

id

The interaction’s ID.

Type:

int

type

The type of the interaction.

Type:

InteractionType

name

The name of the ApplicationCommand, including subcommands and subcommand groups.

Type:

str

user

The user who invoked the interaction.

Type:

User

RoleSubscriptionInfo

class discord.RoleSubscriptionInfo

Bases: object

Represents a message’s role subscription information.

This is currently only attached to messages of type MessageType.role_subscription_purchase.

New in version 2.0.

role_subscription_listing_id

The ID of the SKU and listing that the user is subscribed to.

Type:

int

tier_name

The name of the tier that the user is subscribed to.

Type:

str

total_months_subscribed

The cumulative number of months that the user has been subscribed for.

Type:

int

is_renewal

Whether this notification is for a renewal rather than a new purchase.

Type:

bool

DeletedReferencedMessage

Attributes
class discord.DeletedReferencedMessage

Bases: object

A special sentinel type that denotes whether the resolved message referenced message had since been deleted.

The purpose of this class is to separate referenced messages that could not be fetched and those that were previously fetched but have since been deleted.

New in version 1.6.

property id

The message ID of the deleted referenced message.

Type:

int

property channel_id

The channel ID of the deleted referenced message.

Type:

int

property guild_id

The guild ID of the deleted referenced message.

Type:

Optional[int]

Reaction

Methods
class discord.Reaction

Bases: object

Represents a reaction to a message.

Depending on the way this object was created, some attributes can have a value of None

x == y

Checks if two reactions are equal. This works by checking if the emoji is the same. So two messages with the same reaction will be considered “equal”.

x != y

Checks if two reactions are not equal.

hash(x)

Returns the reaction’s hash.

str(x)

Returns the string form of the reaction’s emoji.

emoji

The reaction emoji. Might be a custom emoji, or a unicode emoji.

Type:

Union[Emoji, PartialEmoji, str]

count

Number of times this reaction was made.

Type:

int

me

If the user sent this reaction.

Type:

bool

message

Message this reaction is for.

Type:

Message

async for ... in users(limit=None, after=None)

Returns an AsyncIterator representing the users that have reacted to the message.

The after parameter must represent a member and meet the abc.Snowflake abc.

Examples

Usage

# I do not actually recommend doing this.
async for user in reaction.users():
    await channel.send('{0} has reacted with {1.emoji}!'.format(user, reaction))

Flattening into a list:

users = await reaction.users().flatten()
# users is now a list of User...
winner = random.choice(users)
await channel.send('{} has won the raffle.'.format(winner))
Parameters:
  • limit (int) – The maximum number of results to return. If not provided, returns all the users who reacted to the message.

  • after (abc.Snowflake) – For pagination, reactions are sorted by member.

Raises:

HTTPException – Getting the users for the reaction failed.

Yields:

Union[User, Member] – The member (if retrievable) or the user that has reacted to this message. The case where it can be a Member is in a guild message context. Sometimes it can be a User if the member has left the guild.

property custom_emoji

If this is a custom emoji.

Type:

bool

property type

The type of this reaction; normal or burst.

Type:

ReactionType

is_burst()

bool: Whether this is a burst reaction or not.

await remove(user)

This function is a coroutine.

Remove the reaction by the provided User from the message.

If the reaction is not your own (i.e. user parameter is not you) then the manage_messages permission is needed.

The user parameter must represent a user or member and meet the abc.Snowflake abc.

Parameters:

user (abc.Snowflake) – The user or member from which to remove the reaction.

Raises:
  • HTTPException – Removing the reaction failed.

  • Forbidden – You do not have the proper permissions to remove the reaction.

  • NotFound – The user you specified, or the reaction’s message was not found.

await clear()

This function is a coroutine.

Clears this reaction from the message.

You need the manage_messages permission to use this.

New in version 1.3.

Raises:
  • HTTPException – Clearing the reaction failed.

  • Forbidden – You do not have the proper permissions to clear the reaction.

  • NotFound – The emoji you specified was not found.

  • InvalidArgument – The emoji parameter is invalid.

Guild

class discord.Guild

Bases: Hashable

Represents a Discord guild.

This is referred to as a “server” in the official Discord UI.

x == y

Checks if two guilds are equal.

x != y

Checks if two guilds are not equal.

hash(x)

Returns the guild’s hash.

str(x)

Returns the guild’s name.

name

The guild name.

Type:

str

emojis

All emojis that the guild owns.

Type:

Tuple[Emoji, …]

afk_timeout

The timeout to get sent to the AFK channel.

Type:

int

afk_channel

The channel that denotes the AFK channel. None if it doesn’t exist.

Type:

Optional[VoiceChannel]

icon

The guild’s icon.

Type:

Optional[str]

id

The guild’s ID.

Type:

int

owner_id

The guild owner’s ID. Use Guild.owner instead.

Type:

int

unavailable

Indicates if the guild is unavailable. If this is True then the reliability of other attributes outside of Guild.id is slim, and they might all be None. It is best to not do anything with the guild if it is unavailable.

Check the on_guild_unavailable() and on_guild_available() events.

Type:

bool

max_presences

The maximum amount of presences for the guild.

Type:

Optional[int]

max_members

The maximum amount of members for the guild.

Note

This attribute is only available via Client.fetch_guild().

Type:

Optional[int]

max_video_channel_users

The maximum amount of users in a video channel.

New in version 1.4.

Type:

Optional[int]

banner

The guild’s banner.

Type:

Optional[str]

description

The guild’s description.

Type:

Optional[str]

mfa_level

Indicates the guild’s two-factor authorisation level. If this value is 0 then the guild does not require 2FA for their administrative members. If the value is 1 then they do.

Type:

int

verification_level

The guild’s verification level.

Type:

VerificationLevel

explicit_content_filter

The guild’s explicit content filter.

Type:

ContentFilter

default_notifications

The guild’s notification settings.

Type:

NotificationLevel

features

A list of features that the guild has. They are currently as follows:

  • VIP_REGIONS: Guild has VIP voice regions

  • VANITY_URL: Guild can have a vanity invite URL (e.g. discord.gg/discord-api)

  • INVITE_SPLASH: Guild’s invite page can have a special splash.

  • VERIFIED: Guild is a verified server.

  • PARTNERED: Guild is a partnered server.

  • MORE_EMOJI: Guild is allowed to have more than 50 custom emoji.

  • MORE_STICKER: Guild is allowed to have more than 60 custom sticker.

  • DISCOVERABLE: Guild shows up in Server Discovery.

  • FEATURABLE: Guild is able to be featured in Server Discovery.

  • COMMUNITY: Guild is a community server.

  • PUBLIC: Guild is a public guild.

  • NEWS: Guild can create news channels.

  • BANNER: Guild can upload and use a banner (i.e. banner_url()).

  • ANIMATED_ICON: Guild can upload an animated icon.

  • PUBLIC_DISABLED: Guild cannot be public.

  • WELCOME_SCREEN_ENABLED: Guild has enabled the welcome screen

  • MEMBER_VERIFICATION_GATE_ENABLED: Guild has Membership Screening enabled.

  • PREVIEW_ENABLED: Guild can be viewed before being accepted via Membership Screening.

Type:

List[str]

splash

The guild’s invite splash.

Type:

Optional[str]

premium_tier

The premium tier for this guild. Corresponds to “Nitro Server” in the official UI. The number goes from 0 to 3 inclusive.

Type:

int

premium_subscription_count

The number of “boosts” this guild currently has.

Type:

int

preferred_locale

The preferred locale for the guild. Used when filtering Server Discovery results to a specific language.

Type:

Optional[Locale]

discovery_splash

The guild’s discovery splash. .. versionadded:: 1.3

Type:

str

premium_progress_bar_enabled

Whether the guild has the boost progress bar enabled.

Type:

bool

invites_disabled_until

When this is set to a time in the future, then invites to the guild are disabled until that time. .. versionadded:: 2.0

Type:

Optional[datetime]

dms_disabled_until

When this is set to a time in the future, then direct messages to members of the guild are disabled (unless users are friends to each other) until that time. .. versionadded:: 2.0

Type:

Optional[datetime]

async for ... in fetch_members(*, limit=1000, after=None)

Retrieves an AsyncIterator that enables receiving the guild’s members. In order to use this, Intents.members() must be enabled.

Note

This method is an API call. For general usage, consider members instead.

New in version 1.3.

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of members to retrieve. Defaults to 1000. Pass None to fetch all members. Note that this is potentially slow.

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve members after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.

Raises:
Yields:

Member – The member with the member data parsed.

Examples

Usage

async for member in guild.fetch_members(limit=150):
    print(member.name)

Flattening into a list

members = await guild.fetch_members(limit=150).flatten()
# members is now a list of Member...
async for ... in audit_logs(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)

Returns an AsyncIterator that enables receiving the guild’s audit logs.

You must have the view_audit_log permission to use this.

Examples

Getting the first 100 entries:

async for entry in guild.audit_logs(limit=100):
    print('{0.user} did {0.action} to {0.target}'.format(entry))

Getting entries for a specific action:

async for entry in guild.audit_logs(action=discord.AuditLogAction.ban):
    print('{0.user} banned {0.target}'.format(entry))

Getting entries made by a specific user:

entries = await guild.audit_logs(limit=None, user=guild.me).flatten()
await channel.send('I made {} moderation actions.'.format(len(entries)))
Parameters:
  • limit (Optional[int]) – The number of entries to retrieve. If None retrieve all entries.

  • before (Union[abc.Snowflake, datetime.datetime]) – Retrieve entries before this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • after (Union[abc.Snowflake, datetime.datetime]) – Retrieve entries after this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • oldest_first (bool) – If set to True, return entries in oldest->newest order. Defaults to True if after is specified, otherwise False.

  • user (abc.Snowflake) – The moderator to filter entries from.

  • action (AuditLogAction) – The action to filter with.

Raises:
  • Forbidden – You are not allowed to fetch audit logs

  • HTTPException – An error occurred while fetching the audit logs.

Yields:

AuditLogEntry – The audit log entry.

property application_commands

A list of application-commands from this application that are registered only in this guild.

Type:

List[ApplicationCommand]

get_application_command(id)

Optional[ApplicationCommand]: Returns an application-command from this application that are registered only in this guild with the given id

property channels

A list of channels that belongs to this guild.

Type:

List[abc.GuildChannel, ThreadChannel, ForumPost]

stage_instances()

List[StageInstance]: A list of stage instances that belongs to this guild.

property server_guide_channels

A list of channels that are part of the servers guide.

Type:

List[abc.GuildChannel]

property events

A list of scheduled events that belong to this guild.

Type:

List[GuildScheduledEvent]

property scheduled_events

A list of scheduled events that belong to this guild.

Type:

List[GuildScheduledEvent]

property cached_automod_rules

A list of auto moderation rules that are cached.

Reliable Fetching

This property is only reliable if automod_rules() was used before. To ensure that the rules are up-to-date, use automod_rules() instead.

Type:

List[AutoModRules]

get_event(id)

Returns a scheduled event with the given ID.

Parameters:

id (int) – The ID of the event to get.

Returns:

The scheduled event or None if not found.

Return type:

Optional[GuildScheduledEvent]

get_scheduled_event(id)

Returns a scheduled event with the given ID.

Parameters:

id (int) – The ID of the event to get.

Returns:

The scheduled event or None if not found.

Return type:

Optional[GuildScheduledEvent]

property large

Indicates if the guild is a ‘large’ guild.

A large guild is defined as having more than large_threshold count members, which for this library is set to the maximum of 250.

Type:

bool

property voice_channels

A list of voice channels that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.

Type:

List[VoiceChannel]

property stage_channels

A list of voice channels that belongs to this guild.

New in version 1.7.

This is sorted by the position and are in UI order from top to bottom.

Type:

List[StageChannel]

property me

Similar to Client.user except an instance of Member. This is essentially used to get the member version of yourself.

Type:

Member

property voice_client

Returns the VoiceProtocol associated with this guild, if any.

Type:

Optional[VoiceProtocol]

property text_channels

A list of text channels that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.

Type:

List[TextChannel]

property thread_channels

A list of cached thread channels the guild has.

This is sorted by the position of the threads parent and are in UI order from top to bottom.

Type:

List[ThreadChannel]

property forum_channels

A list of forum channels the guild has.

This is sorted by the position of the forums parent and are in UI order from top to bottom.

Type:

List[ForumChannel]

property forum_posts

A list of cached forum posts the guild has.

This is sorted by the position of the forums parent and are in UI order from top to bottom.

Type:

List[ForumPost]

property guide_channels

A list of channels that are part of the server guide.

There is an alias for this called resource_channels.

Type:

List[GuildChannel]

property resource_channels

A list of channels that are part of the server guide.

There is an alias for this called resource_channels.

Type:

List[GuildChannel]

property categories

A list of categories that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.

Type:

List[CategoryChannel]

by_category()

Returns every CategoryChannel and their associated channels.

These channels and categories are sorted in the official Discord UI order.

If the channels do not have a category, then the first element of the tuple is None.

Returns:

The categories and their associated channels.

Return type:

List[Tuple[Optional[CategoryChannel], List[abc.GuildChannel]]]

get_channel(channel_id)

Returns a channel with the given ID.

Parameters:

channel_id (int) – The ID to search for.

Returns:

The channel or None if not found.

Return type:

Optional[Union[abc.GuildChannel, ThreadChannel, ForumPost]]

property system_channel

Returns the guild’s channel used for system messages.

If no channel is set, then this returns None.

Type:

Optional[TextChannel]

property system_channel_flags

Returns the guild’s system channel settings.

Type:

SystemChannelFlags

property rules_channel

Return’s the guild’s channel used for the rules. The guild must be a Community guild.

If no channel is set, then this returns None.

New in version 1.3.

Type:

Optional[TextChannel]

property public_updates_channel

Return’s the guild’s channel where admins and moderators of the guilds receive notices from Discord. The guild must be a Community guild.

If no channel is set, then this returns None.

New in version 2.0.

Type:

Optional[TextChannel]

property safety_alerts_channel

Return’s the guild’s channel where Discord sends safety alerts in. The guild must be a Community guild.

If no channel is set, then this returns None.

New in version 2.0.

Type:

Optional[TextChannel]

property emoji_limit

The maximum number of emoji slots this guild has.

Type:

int

property sticker_limit

The maximum number of sticker slots this guild has.

Type:

int

property bitrate_limit

The maximum bitrate for voice channels this guild can have.

Type:

float

property filesize_limit

The maximum number of bytes files can have when uploaded to this guild.

Type:

int

property members

A list of members that belong to this guild.

Type:

List[Member]

get_member(user_id)

Returns a member with the given ID.

Parameters:

user_id (int) – The ID to search for.

Returns:

The member or None if not found.

Return type:

Optional[Member]

property premium_subscribers

A list of members who have “boosted” this guild.

Type:

List[Member]

property roles

Returns a list of the guild’s roles in hierarchy order.

The first element of this list will be the lowest role in the hierarchy.

Type:

List[Role]

get_role(role_id)

Returns a role with the given ID.

Parameters:

role_id (int) – The ID to search for.

Returns:

The role or None if not found.

Return type:

Optional[Role]

property default_role

Gets the @everyone role that all members have by default.

Type:

Role

property premium_subscriber_role

Gets the premium subscriber role, AKA “boost” role, in this guild.

New in version 1.6.

Type:

Optional[Role]

property self_role

Gets the role associated with this client’s user, if any.

New in version 1.6.

Type:

Optional[Role]

property owner

The member that owns the guild.

Type:

Optional[Member]

property icon_url

Returns the guild’s icon asset.

Type:

Asset

is_icon_animated()

bool: Returns True if the guild has an animated icon.

icon_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the guild’s icon.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the icon to. If the format is None, then it is automatically detected into either ‘gif’ or static_format depending on the icon being animated or not.

  • static_format (Optional[str]) – Format to attempt to convert only non-animated icons to.

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or invalid size.

Returns:

The resulting CDN asset.

Return type:

Asset

property banner_url

Returns the guild’s banner asset.

Type:

Asset

banner_url_as(*, format='webp', size=2048)

Returns an Asset for the guild’s banner.

The format must be one of ‘webp’, ‘jpeg’, or ‘png’. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (str) – The format to attempt to convert the banner to.

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or invalid size.

Returns:

The resulting CDN asset.

Return type:

Asset

property splash_url

Returns the guild’s invite splash asset.

Type:

Asset

splash_url_as(*, format='webp', size=2048)

Returns an Asset for the guild’s invite splash.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (str) – The format to attempt to convert the splash to.

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or invalid size.

Returns:

The resulting CDN asset.

Return type:

Asset

property discovery_splash_url

Returns the guild’s discovery splash asset.

New in version 1.3.

Type:

Asset

discovery_splash_url_as(*, format='webp', size=2048)

Returns an Asset for the guild’s discovery splash.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’. The size must be a power of 2 between 16 and 4096.

New in version 1.3.

Parameters:
  • format (str) – The format to attempt to convert the splash to.

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or invalid size.

Returns:

The resulting CDN asset.

Return type:

Asset

property member_count

Returns the true member count regardless of it being loaded fully or not.

Warning

Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires Intents.members to be specified.

Type:

int

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 internal members cache.

If this value returns False, then you should request for offline members.

Type:

bool

property shard_id

Returns the shard ID for this guild if applicable.

Type:

Optional[int]

property created_at

Returns the guild’s creation time in UTC.

Type:

datetime.datetime

get_member_named(name)

Returns the first member found that matches the name provided.

The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However, the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.

If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.

If no member is found, None is returned.

Parameters:

name (str) – The name of the member to lookup with an optional discriminator.

Returns:

The member in this guild with the associated name. If not found then None is returned.

Return type:

Optional[Member]

await create_text_channel(name, *, overwrites=None, category=None, reason=None, **options)

This function is a coroutine.

Creates a TextChannel for the guild.

Note that you need the manage_channels permission to create the channel.

The overwrites parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a dict of overwrites with the target (either a Member or a Role) as the key and a PermissionOverwrite as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to edit() will be required to update the position of the channel in the channel list.

Examples

Creating a basic channel:

channel = await guild.create_text_channel('cool-channel')

Creating a “secret” channel:

overwrites = {
    guild.default_role: discord.PermissionOverwrite(read_messages=False),
    guild.me: discord.PermissionOverwrite(read_messages=True)
}

channel = await guild.create_text_channel('secret', overwrites=overwrites)
Parameters:
  • name (str) – The channel’s name.

  • overwrites – A dict of target (either a role or a member) to PermissionOverwrite to apply upon creation of a channel. Useful for creating secret channels.

  • category (Optional[CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.

  • position (int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

  • topic (Optional[str]) – The new channel’s topic.

  • slowmode_delay (int) – Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is 21600.

  • default_thread_slowmode_delay (int) – The initial slowmode_delay to set on newly created threads in the channel. This field is copied to the thread at creation time and does not live update.

  • nsfw (bool) – To mark the channel as NSFW or not.

  • reason (Optional[str]) – The reason for creating this channel. Shows up on the audit log.

Raises:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

  • InvalidArgument – The permission overwrite information is not in proper form.

Returns:

The channel that was just created.

Return type:

TextChannel

await create_voice_channel(name, *, overwrites=None, category=None, reason=None, **options)

This function is a coroutine.

This is similar to create_text_channel() except makes a VoiceChannel instead, in addition to having the following new parameters.

Parameters:
  • bitrate (int) – The channel’s preferred audio bitrate in bits per second.

  • user_limit (int) – The channel’s limit for number of members that can be in a voice channel.

  • rtc_region (Optional[VoiceRegion]) –

    The region for the voice channel’s voice communication. A value of None indicates automatic voice region detection.

    New in version 1.7.

Raises:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

  • InvalidArgument – The permission overwrite information is not in proper form.

Returns:

The channel that was just created.

Return type:

VoiceChannel

await create_stage_channel(name, *, topic=None, category=None, overwrites=None, reason=None, position=None)

This function is a coroutine.

This is similar to create_text_channel() except makes a StageChannel instead, in addition to having the following new parameters.

Parameters:
  • topic (Optional[str]) – The topic of the Stage instance (1-120 characters)

  • note:: (..) – The slowmode_delay and nsfw parameters are not supported in this function.

  • versionadded: (..) – 1.7:

Raises:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

  • InvalidArgument – The permission overwrite information is not in proper form.

Returns:

The channel that was just created.

Return type:

StageChannel

await create_forum_channel(name, *, topic=None, slowmode_delay=None, default_post_slowmode_delay=None, default_auto_archive_duration=None, overwrites=None, nsfw=None, category=None, position=None, reason=None)

This function is a coroutine.

Same as create_text_channel() excepts that it creates a forum channel instead

Parameters:
  • name (str) – The name of the channel

  • overwrites – A dict of target (either a role or a member) to PermissionOverwrite to apply upon creation of a channel. Useful for creating secret channels.

  • category (Optional[CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.

  • position (int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

  • topic (Optional[str]) – The new channel’s topic.

  • slowmode_delay (int) – Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is 21600.

  • default_post_slowmode_delay (int) – The initial slowmode_delay to set on newly created threads in the channel. This field is copied to the thread at creation time and does not live update.

  • default_auto_archive_duration (AutoArchiveDuration) – The default duration that the clients use (not the API) for newly created threads in the channel, in minutes, to automatically archive the thread after recent activity

  • nsfw (bool) – To mark the channel as NSFW or not.

  • reason (Optional[str]) – The reason for creating this channel. Shows up on the audit log.

Raises:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

  • InvalidArgument – The permission overwrite information is not in proper form, or the default_auto_archive_duration is not a valid member of AutoArchiveDuration

Returns:

The channel that was just created

Return type:

ForumChannel

await create_category(name, *, overwrites=None, reason=None, position=None)

This function is a coroutine.

Same as create_text_channel() except makes a CategoryChannel instead.

Note

The category parameter is not supported in this function since categories cannot have categories.

Raises:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

  • InvalidArgument – The permission overwrite information is not in proper form.

Returns:

The channel that was just created.

Return type:

CategoryChannel

await create_category_channel(name, *, overwrites=None, reason=None, position=None)

This function is a coroutine.

Same as create_text_channel() except makes a CategoryChannel instead.

Note

The category parameter is not supported in this function since categories cannot have categories.

Raises:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

  • InvalidArgument – The permission overwrite information is not in proper form.

Returns:

The channel that was just created.

Return type:

CategoryChannel

await leave()

This function is a coroutine.

Leaves the guild.

Note

You cannot leave the guild that you own, you must delete it instead via delete().

Raises:

HTTPException – Leaving the guild failed.

await delete()

This function is a coroutine.

Deletes the guild. You must be the guild owner to delete the guild.

Raises:
await edit(name=MISSING, description=MISSING, features=MISSING, icon=MISSING, banner=MISSING, splash=MISSING, discovery_splash=MISSING, region=MISSING, afk_channel=MISSING, afk_timeout=MISSING, system_channel=MISSING, system_channel_flags=MISSING, rules_channel=MISSING, public_updates_channel=MISSING, preferred_locale=MISSING, verification_level=MISSING, default_notifications=MISSING, explicit_content_filter=MISSING, vanity_code=MISSING, owner=MISSING, *, reason=None)

This function is a coroutine.

Edits the guild.

You must have the manage_guild permission to edit the guild.

Changed in version 1.4: The rules_channel and public_updates_channel keyword-only parameters were added.

Parameters:
  • name (str) – The new name of the guild.

  • description (str) – The new description of the guild. This is only available to guilds that contain PUBLIC in Guild.features.

  • features (GuildFeatures) – Features to enable/disable will be merged in to the current features. See the discord api documentation for a list of currently mutable features and the required permissions.

  • icon (bytes) – A bytes-like object representing the icon. Only PNG/JPEG is supported. GIF is only available to guilds that contain ANIMATED_ICON in Guild.features. Could be None to denote removal of the icon.

  • banner (bytes) – A bytes-like object representing the banner. Could be None to denote removal of the banner.

  • splash (bytes) – A bytes-like object representing the invite splash. Only PNG/JPEG supported. Could be None to denote removing the splash. This is only available to guilds that contain INVITE_SPLASH in Guild.features.

  • discovery_splash (bytes) – A bytes-like object representing the discovery splash. Only PNG/JPEG supported. Could be None to denote removing the splash. This is only available to guilds that contain DISCOVERABLE in Guild.features.

  • region (VoiceRegion) – Deprecated: The new region for the guild’s voice communication.

  • afk_channel (Optional[VoiceChannel]) – The new channel that is the AFK channel. Could be None for no AFK channel.

  • afk_timeout (int) – The number of seconds until someone is moved to the AFK channel.

  • owner (Member) – The new owner of the guild to transfer ownership to. Note that you must be owner of the guild to do this.

  • verification_level (VerificationLevel) – The new verification level for the guild.

  • default_notifications (NotificationLevel) – The new default notification level for the guild.

  • explicit_content_filter (ContentFilter) – The new explicit content filter for the guild.

  • vanity_code (str) – The new vanity code for the guild.

  • system_channel (Optional[TextChannel]) – The new channel that is used for the system channel. Could be None 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 or ja or zh-CN.

  • rules_channel (Optional[TextChannel]) – The new channel that is used for rules. This is only available to guilds that contain PUBLIC in Guild.features. Could be None 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 contain PUBLIC in Guild.features. Could be None for no public updates channel.

  • reason (Optional[str]) – The reason for editing this guild. Shows up on the audit log.

Raises:
  • Forbidden – You do not have permissions to edit the guild.

  • HTTPException – Editing the guild failed.

  • InvalidArgument – The image format passed in to icon is invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer.

await fetch_channels()

This function is a coroutine.

Retrieves all abc.GuildChannel that the guild has.

Note

This method is an API call. For general usage, consider channels instead.

New in version 1.2.

Raises:
Returns:

All channels in the guild.

Return type:

List[abc.GuildChannel]

await fetch_active_threads()

This function is a coroutine.

Returns all active threads and forum posts in the guild. This includes all public and private threads as long as the current user has permissions to access them. Threads are ordered by their id, in descending order.

Note

This method is an API call.

New in version 2.0.

Returns:

The active threads and forum posts in the guild.

Return type:

List[Union[ThreadChannel, ForumPost]]

await fetch_member(member_id)

This function is a coroutine.

Retrieves a Member from a guild ID, and a member ID.

Note

This method is an API call. If you have Intents.members and member cache enabled, consider get_member() instead.

Parameters:

member_id (int) – The member’s ID to fetch from.

Raises:
Returns:

The member from the member ID.

Return type:

Member

await fetch_ban(user)

This function is a coroutine.

Retrieves the BanEntry for a user.

You must have the ban_members permission to get this information.

Parameters:

user (abc.Snowflake) – The user to get ban information from.

Raises:
  • Forbidden – You do not have proper permissions to get the information.

  • NotFound – This user is not banned.

  • HTTPException – An error occurred while fetching the information.

Returns:

The BanEntry object for the specified user.

Return type:

BanEntry

bans(limit=None, before=None, after=None)

Retrieves an AsyncIterator that enables receiving the guild’s bans.

You must have the ban_members permission to get this information.

Note

This method is an API call. Use it careful.

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of bans to retrieve. Defaults to all. Note that this is potentially slow.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve members before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Retrieve members after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.

Raises:
  • Forbidden – You do not have proper permissions to get the information.

  • HTTPException – Getting the bans failed.

Yields:

BanEntry – The ban entry containing the user and an optional reason.

Examples

Usage

async for ban_entry in guild.bans(limit=150):
    print(ban_entry.user)

Flattening into a list

ban_entries = await guild.bans(limit=150).flatten()
# ban_entries is now a list of BanEntry...
await prune_members(*, days, compute_prune_count=True, roles=None, reason=None)

This function is a coroutine.

Prunes the guild from its inactive members.

The inactive members are denoted if they have not logged on in days number of days, and they have no roles.

You must have the kick_members permission to use this.

To check how many members you would prune without actually pruning, see the estimate_pruned_members() function.

To prune members that have specific roles see the roles parameter.

Changed in version 1.4: The roles keyword-only parameter was added.

Parameters:
  • days (int) – The number of days before counting as inactive.

  • reason (Optional[str]) – The reason for doing this action. Shows up on the audit log.

  • compute_prune_count (bool) – Whether to compute the prune count. This defaults to True which makes it prone to timeouts in very large guilds. In order to prevent timeouts, you must set this to False. If this is set to False, then this function will always return None.

  • roles (Optional[List[abc.Snowflake]]) – A list of abc.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:
Returns:

The number of members pruned. If compute_prune_count is False then this returns None.

Return type:

Optional[int]

await templates()

This function is a coroutine.

Gets the list of templates from this guild.

Requires manage_guild permissions.

New in version 1.7.

Raises:

Forbidden – You don’t have permissions to get the templates.

Returns:

The templates for this guild.

Return type:

List[Template]

await webhooks()

This function is a coroutine.

Gets the list of webhooks from this guild.

Requires manage_webhooks permissions.

Raises:

Forbidden – You don’t have permissions to get the webhooks.

Returns:

The webhooks for this guild.

Return type:

List[Webhook]

await estimate_pruned_members(*, days, roles=None)

This function is a coroutine.

Similar to prune_members() except instead of actually pruning members, it returns how many members it would prune from the guild had it been called.

Parameters:
  • days (int) – The number of days before counting as inactive.

  • roles (Optional[List[abc.Snowflake]]) –

    A list of abc.Snowflake that represent roles to include in the estimate. If a member has a role that is not specified, they’ll be excluded.

    New in version 1.7.

Raises:
  • Forbidden – You do not have permissions to prune members.

  • HTTPException – An error occurred while fetching the prune members estimate.

  • InvalidArgument – An integer was not passed for days.

Returns:

The number of members estimated to be pruned.

Return type:

int

await invites()

This function is a coroutine.

Returns a list of all active instant invites from the guild.

You must have the manage_guild permission to get this information.

Raises:
  • Forbidden – You do not have proper permissions to get the information.

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

await create_template(*, name, description=None)

This function is a coroutine.

Creates a template for the guild.

You must have the manage_guild permission to do this.

New in version 1.7.

Parameters:
  • name (str) – The name of the template.

  • description (Optional[str]) – The description of the template.

await create_integration(*, type, id)

This function is a coroutine.

Attaches an integration to the guild.

You must have the manage_guild permission to do this.

New in version 1.4.

Parameters:
  • type (str) – The integration type (e.g. Twitch).

  • id (int) – The integration ID.

Raises:
  • Forbidden – You do not have permission to create the integration.

  • HTTPException – The account could not be found.

await integrations()

This function is a coroutine.

Returns a list of all integrations attached to the guild. You must have the manage_guild permission to do this. .. versionadded:: 1.4 :raises Forbidden: You do not have permission to create the integration. :raises HTTPException: Fetching the integrations failed.

Returns:

The list of integrations that are attached to the guild.

Return type:

List[Integration]

await fetch_emojis()

This function is a coroutine.

Retrieves all custom Emojis from the guild.

Note

This method is an API call. For general usage, consider emojis instead.

Raises:

HTTPException – An error occurred fetching the emojis.

Returns:

The retrieved emojis.

Return type:

List[Emoji]

await fetch_emoji(emoji_id)

This function is a coroutine.

Retrieves a custom Emoji from the guild.

Note

This method is an API call. For general usage, consider iterating over emojis instead.

Parameters:

emoji_id (int) – The emoji’s ID.

Raises:
  • NotFound – The emoji requested could not be found.

  • HTTPException – An error occurred fetching the emoji.

Returns:

The retrieved emoji.

Return type:

Emoji

await create_custom_emoji(*, name, image, roles=None, reason=None)

This function is a coroutine.

Creates a custom Emoji for the guild.

There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the MORE_EMOJI feature which extends the limit to 200.

You must have the manage_emojis permission to do this.

Parameters:
  • name (str) – The emoji name. Must be at least 2 characters.

  • image (bytes) – The bytes-like object representing the image data to use. Only JPG, PNG and GIF images are supported.

  • roles (Optional[List[Role]]) – A list of Roles 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:
Returns:

The created emoji.

Return type:

Emoji

await fetch_roles()

This function is a coroutine.

Retrieves all Role that the guild has.

Note

This method is an API call. For general usage, consider roles instead.

New in version 1.3.

Raises:

HTTPException – Retrieving the roles failed.

Returns:

All roles in the guild.

Return type:

List[Role]

await create_role(*, name=MISSING, permissions=MISSING, color=MISSING, colour=MISSING, hoist=False, mentionable=False, icon=None, unicode_emoji=None, reason=None)

This function is a coroutine.

Creates a Role for the guild.

All fields are optional.

You must have the manage_roles permission to do this.

Changed in version 1.6: Can now pass int to colour keyword-only parameter.

New in version 2.0: Added the icon and unicode_emoji keyword-only parameters.

Note

The icon and unicode_emoji can’t be used together. Both of them can only be used when ROLE_ICONS is in the guild features().

Parameters:
  • name (str) – The role name. Defaults to ‘new role’.

  • permissions (Permissions) – The permissions to have. Defaults to no permissions.

  • color (Union[Colour, int]) – The colour for the role. Defaults to Colour.default().

  • colour (Union[Colour, int]) – The colour for the role. Defaults to Colour.default(). This is aliased to color as well.

  • hoist (bool) – Indicates if the role should be shown separately in the member list. Defaults to False.

  • mentionable (bool) – Indicates if the role should be mentionable by others. Defaults to False.

  • icon (Optional[bytes]) – The bytes-like object representing the image data to use as the role icon.

  • unicode_emoji (Optional[str]) – The unicode emoji to use as the role unicode_emoji.

  • reason (Optional[str]) – The reason for creating this role. Shows up on the audit log.

Raises:
Returns:

The newly created role.

Return type:

Role

await edit_role_positions(positions, *, reason=None)

This function is a coroutine.

Bulk edits a list of Role in the guild.

You must have the manage_roles permission to do this.

New in version 1.4.

Example:

positions = {
    bots_role: 1, # penultimate role
    tester_role: 2,
    admin_role: 6
}

await guild.edit_role_positions(positions=positions)
Parameters:
  • positions – A dict of Role to int to change the positions of each given role.

  • reason (Optional[str]) – The reason for editing the role positions. Shows up on the audit log.

Raises:
Returns:

A list of all the roles in the guild.

Return type:

List[Role]

await kick(user, *, reason=None)

This function is a coroutine.

Kicks a user from the guild.

The user must meet the abc.Snowflake abc.

You must have the kick_members permission to do this.

Parameters:
  • user (abc.Snowflake) – The user to kick from their guild.

  • reason (Optional[str]) – The reason the user got kicked.

Raises:
await ban(user, *, delete_message_days=None, delete_message_seconds=0, reason=None)

This function is a coroutine.

Bans a user from the guild.

The user must meet the abc.Snowflake abc.

You must have the ban_members permission to do this.

Parameters:
  • user (abc.Snowflake) – The user to ban from their guild.

  • delete_message_days (int) –

    The number of days worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 7.

    Deprecated since version 2.0.

  • delete_message_seconds (int) –

    The number of days worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (7 days).

    New in version 2.0.

  • reason (Optional[str]) – The reason the user got banned.

Raises:
await unban(user, *, reason=None)

This function is a coroutine.

Unbans a user from the guild.

The user must meet the abc.Snowflake abc.

You must have the ban_members permission to do this.

Parameters:
  • user (abc.Snowflake) – The user to unban.

  • reason (Optional[str]) – The reason for doing this action. Shows up on the audit log.

Raises:
await vanity_invite()

This function is a coroutine.

Returns the guild’s special vanity invite.

The guild must have VANITY_URL in features.

You must have the manage_guild permission to use this as well.

Raises:
  • Forbidden – You do not have the proper permissions to get this.

  • HTTPException – Retrieving the vanity invite failed.

Returns:

The special vanity invite.

Return type:

Invite

await widget()

This function is a coroutine.

Returns the widget of the guild.

Note

The guild must have the widget enabled to get this information.

Raises:
Returns:

The guild’s widget.

Return type:

Widget

await chunk(*, cache=True)

This function is a coroutine.

Requests all members that belong to this guild. In order to use this, Intents.members() must be enabled.

This is a websocket operation and can be slow.

New in version 1.5.

Parameters:

cache (bool) – Whether to cache the members as well.

Raises:

ClientException – The members intent is not enabled.

await query_members(query=None, *, limit=5, user_ids=None, presences=False, cache=True)

This function is a coroutine.

Request members that belong to this guild whose username starts with the query given.

This is a websocket operation and can be slow.

New in version 1.3.

Parameters:
  • query (Optional[str]) – The string that the username’s start with.

  • limit (int) – The maximum number of members to send back. This must be a number between 5 and 100.

  • presences (bool) –

    Whether to request for presences to be provided. This defaults to False.

    New in version 1.6.

  • cache (bool) – Whether to cache the members internally. This makes operations such as get_member() work for those that matched.

  • user_ids (Optional[List[int]]) –

    List of user IDs to search for. If the user ID is not in the guild then it won’t be returned.

    New in version 1.4.

Raises:
Returns:

The list of members that have matched the query.

Return type:

List[Member]

await change_voice_state(*, channel, self_mute=False, self_deaf=False)

This function is a coroutine.

Changes client’s voice state in the guild.

New in version 1.4.

Parameters:
  • channel (Optional[VoiceChannel]) – Channel the client wants to join. Use None to disconnect.

  • self_mute (bool) – Indicates if the client should be self-muted.

  • self_deaf (bool) – Indicates if the client should be self-deafened.

await create_sticker(name, file, tags, description=None, *, reason=None)

This function is a coroutine.

Create a new sticker for the guild.

Requires the MANAGE_EMOJIS_AND_STICKERS permission.

Parameters:
  • name (str) – The name of the sticker (2-30 characters).

  • tags (Union[str, List[str]]) – Autocomplete/suggestion tags for the sticker separated by , or in a list. (max 200 characters).

  • description (Optional[str]) – The description of the sticker (None or 2-100 characters).

  • file (Union[UploadFile, str]) – The sticker file to upload or the path to it, must be a PNG, APNG, GIF or Lottie JSON file, max 500 KB

  • reason (Optional[str]) – The reason for creating the sticker., shows up in the audit-log.

Raises:
  • discord.Forbidden: – You don’t have the permissions to upload stickers in this guild.

  • discord.HTTPException: – Creating the sticker failed.

  • ValueError – Any of name, description or tags is too short/long.

Returns:

The new GuildSticker created on success.

Return type:

GuildSticker

await fetch_events(with_user_count=True)

This function is a coroutine.

Retrieves a list of scheduled events the guild has.

Note

This method is an API call. For general usage, consider iterating over events instead.

Parameters:

with_user_count (bool) – Whether to include the number of interested users the event has, default True.

Returns:

A list of scheduled events the guild has.

Return type:

Optional[List[GuildScheduledEvent]]

await fetch_event(id, with_user_count=True)

This function is a coroutine.

Fetches the GuildScheduledEvent with the given id.

Parameters:
  • id (int) – The id of the event to fetch.

  • with_user_count (bool) – Whether to include the number of interested users the event has, default True.

Returns:

The event on success.

Return type:

Optional[GuildScheduledEvent]

await create_scheduled_event(name, entity_type, start_time, end_time=None, channel=None, description=None, location=None, cover_image=None, *, reason=None)

This function is a coroutine.

Schedules a new Event in this guild. Requires MANAGE_EVENTS at least in the channel or in the entire guild if type is external.

Parameters:
  • name (str) – The name of the scheduled event. 1-100 characters long.

  • entity_type (EventEntityType) –

    The entity_type of the scheduled event.

    Important

    end_time and location must be provided if entity_type is external, otherwise channel

  • start_time (datetime.datetime) – The time when the event will start. Must be a valid date in the future.

  • end_time (Optional[datetime.datetime]) –

    The time when the event will end. Must be a valid date in the future.

    Important

    If entity_type is external this must be provided.

  • channel (Optional[Union[StageChannel, VoiceChannel]]) – The channel in which the event takes place. Must be provided if entity_type is stage or voice.

  • description (Optional[str]) – The description of the scheduled event. 1-1000 characters long.

  • location (Optional[str]) –

    The location where the event will take place. 1-100 characters long.

    Important

    This must be provided if entity_type is external

  • cover_image (Optional[bytes]) – The cover image of the scheduled event.

  • reason (Optional[str]) – The reason for scheduling the event, shows up in the audit-log.

Returns:

The scheduled event on success.

Return type:

GuildScheduledEvent

Raises:
  • TypeError: – Any parameter is of wrong type.

  • errors.InvalidArgument: – entity_type is stage or voice but channel is not provided or external but no location and/or end_time provided.

  • ValueError: – The value of any parameter is invalid. (e.g. to long/short)

  • errors.Forbidden: – You don’t have permissions to schedule the event.

  • discord.HTTPException: – Scheduling the event failed.

await welcome_screen()

This function is a coroutine.

Fetches the welcome screen from the guild if any.

New in version 2.0.

Returns:

The welcome screen of the guild if any.

Return type:

Optional[WelcomeScreen]

await onboarding()

This function is a coroutine.

Fetches the onboarding configuration for the guild.

New in version 2.0.

Returns:

The onboarding configuration fetched.

Return type:

Onboarding

await edit_onboarding(*, prompts=MISSING, default_channels=MISSING, enabled=MISSING, mode=MISSING, reason=None)

This function is a coroutine.

Edits the onboarding configuration for the guild.

New in version 2.0.

Parameters:
  • prompts (List[PartialOnboardingPrompt]) – The prompts that will be shown to new members (if is_onboarding is True, otherwise only in customise community).

  • default_channels (List[Snowflake]) – The channels that will be added to new members’ channel list by default.

  • enabled (bool) – Whether the onboarding configuration is enabled.

  • mode (OnboardingMode) – The mode that will be used for the onboarding configuration.

  • reason (Optional[str]) – The reason for editing the onboarding configuration. Shows up in the audit log.

Raises:
  • Forbidden – You do not have permissions to edit the onboarding configuration.

  • HTTPException – Editing the onboarding configuration failed.

Returns:

The new onboarding configuration.

Return type:

Onboarding

await automod_rules()

This function is a coroutine.

Fetches the Auto Moderation rules for this guild

Warning

This is an API-call, use it carefully.

Returns:

A list of AutoMod rules the guild has

Return type:

List[AutoModRule]

await fetch_automod_rule(rule_id)

This function is a coroutine.

Fetches a Auto Moderation rule for this guild by their ID

Raises:
Returns:

The AutoMod rule

Return type:

AutoModRule

await create_automod_rule(name, event_type, trigger_type, trigger_metadata, actions, enabled=True, exempt_roles=[], exempt_channels=[], *, reason=None)

This function is a coroutine.

Creates a new AutoMod rule for this guild

Parameters:
  • name (str) – The name, the rule should have. Only valid if it’s not a preset rule.

  • event_type (AutoModEventType) – Indicates in what event context a rule should be checked.

  • trigger_type (AutoModTriggerType) – Characterizes the type of content which can trigger the rule.

  • trigger_metadata (AutoModTriggerMetadata) – Additional data used to determine whether a rule should be triggered. Different fields are relevant based on the value of trigger_type.

  • actions (List[AutoModAction]) – The actions which will execute when the rule is triggered.

  • enabled (bool) – Whether the rule is enabled, default True.

  • exempt_roles (List[Snowflake]) – Up to 20 Role’s, that should not be affected by the rule.

  • exempt_channels (List[Snowflake]) – Up to 50 TextChannel/VoiceChannel’s, that should not be affected by the rule.

  • reason (Optional[str]) – The reason for creating the rule. Shows up in the audit log.

Raises:
Returns:

The AutoMod rule created

Return type:

AutoModRule

await edit_incidents_actions(*, invites_disabled_until, dms_disabled_until, reason=None)

This function is a coroutine.

Edits the incident actions of the guild. This requires the manage_guild permission.

Parameters:
  • invites_disabled_until (Optional[datetime.datetime]) – When invites should be possible again (up to 24h in the future). Set to None to enable invites again.

  • dms_disabled_until (Optional[datetime.datetime]) – When direct messages should be enabled again (up to 24h in the future). Set to None to enable direct messages again.

  • reason (Optional[str]) – The reason for editing the incident actions. Shows up in the audit log.

Raises:
  • Forbidden – You don’t have permissions to edit the incident actions.

  • HTTPException – Editing the incident actions failed.

class discord.GuildFeatures

Bases: Iterable[str], dict

Represents a guild’s features.

This class mainly exists to make it easier to edit a guild’s features.

New in version 2.0.

'FEATURE_NAME' in features

Checks if the guild has the feature.

features.FEATURE_NAME

Checks if the guild has the feature. Returns False if it doesn’t.

features.FEATURE_NAME = True

Enables the feature in the features object, but does not enable it in the guild itself except if you pass it to Guild.edit().

features.FEATURE_NAME = False

Disables the feature in the features object, but does not disable it in the guild itself except if you pass it to Guild.edit().

del features.FEATURE_NAME

The same as features.FEATURE_NAME = False

features.parsed()

Returns a list of all features that are/should be enabled.

features.merge(other)

Returns a new object with the features of both objects merged. If a feature is missing in the other object, it will be ignored.

features == other

Checks if two feature objects are equal.

features != other

Checks if two feature objects are not equal.

iter(features)

Returns an iterator over the enabled features.

Parameters:
  • initial (list) – The initial features to set.

  • **features (bool) – The features to set. If the value is True then the feature is/will be enabled. If the value is False then the feature will be disabled.

keys() a set-like object providing a view on D's keys
values() an object providing a view on D's values
items() a set-like object providing a view on D's items
class discord.BanEntry

A namedtuple which represents a ban returned from bans().

reason

The reason this user was banned.

Type:

Optional[str]

user

The User that was banned.

Type:

User

GuildScheduledEvent

class discord.GuildScheduledEvent

Bases: Hashable

Represents a scheduled event in a guild

Warning

Do not initialize this class manually. Use fetch_event()/fetch_events() or to create one create_scheduled_event() instead.

id

The id of the event

Type:

int

name

The name of the event

Type:

str

description

The description of the event

Type:

str

start_time

When the event will start

Type:

datetime.datetime

end_time

Optional, when the event will end

Type:

Optional[datetime.datetime]

creator

The creator of the event

Type:

User

status

The status of the event

Type:

EventStatus

entity_type

The type of the scheduled event

Type:

EventEntityType

image

Optional, the image hash of the event

Type:

Optional[str]

broadcast_to_directory_channels

Whether the event will be broadcasted to directory channels

Note

This is only possible when the guild the event belongs to is part of a student hub.

Type:

bool

async for ... in await users(limit=100, before=None, after=None, with_member=False)

Returns an AsyncIterator that enables receiving the interest users of the event.

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of users to retrieve. If None, retrieves every user of the event. Note, however, that this would make it a slow operation.

  • before (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve users before this user. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • after (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve users after this user. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • with_member (Optional[bool]) – If set to True, return the Member instead of the User if it is part of the guild the event is in.

Examples

# Usage

counter = 0
async for user in event.users(limit=200):
    if user.id > 264905529753600000:  # all accounts created before 2018
        counter += 1

# Flattening into a list

users = await event.users(limit=123).flatten()
# users is now a list of Member/User...
Raises:
  • Forbidden – You do not have permissions to get the event users.

  • HTTPException – The request to get event users failed.

Yields:

Union[Member, User] – The user or member.

property location

The location of the event if entity_type is external.

Type:

Optional[str]

property channel

Optional[Union[StageChannel, VoiceChannel]]: The channel the event is scheduled in if entity_type is stage or voice.

property icon_url

Returns the event image asset.

Type:

Asset

icon_url_as(*, format='webp', size=1024)

Returns an Asset for the event image.

The format must be one of ‘webp’, ‘jpeg’, or ‘png’. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (str) – The format to attempt to convert the icon to.

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or invalid size.

Returns:

The resulting CDN asset.

Return type:

Asset

await edit(*, name=MISSING, description=MISSING, start_time=MISSING, end_time=MISSING, status=MISSING, entity_type=MISSING, location=MISSING, channel=MISSING, cover_image=MISSING, reason=None)

This function is a coroutine.

Modify the event. Requires manage_events permissions. All parameters are optional.

Parameters:
  • name (str) – The new name of the event

  • description (str) – The new description of the event

  • start_time (datetime.datetime) – The new start time of the event

  • end_time (Optional[datetime.datetime]) – The new end time of the event

  • status (EventStatus) – The new status of the event.

  • entity_type (EventEntityType) – The new type of the scheduled event

  • location (str) – The new location of the event. If entity_type is external

  • channel (Optional[Union[StageChannel, :class:`VoiceChannel]]) – The new channel the event is scheduled in if entity_type is EventEntityType.stage or EventEntityType.voice.

  • cover_image (Optional[bytes]) – The new cover image of the event. Must be a bytes object representing a jpeg or png image.

  • reason (Optional[str]) – The reason for editing the event, shows up in the audit-log.

Returns:

The updatet event.

Return type:

GuildScheduledEvent

await delete(*, reason=None)

Deletes the event. Requires MANAGE_EVENTS permissions.

Parameters:

reason (Optional[str]) – The reason for deleting the event, shows up in the audit-log.

Return type:

None

AutoModRule

class discord.AutoModRule

Bases: object

Represents a rule for auto moderation

Warning

Do not initialize this class directly. Use create_automod_rule() instead.

id

The id of this rule

Type:

int

guild

The guild this rule belongs to

Type:

Guild

name

The name of the rule

Type:

str

creator_id

The id of the user wich created this rule

Type:

int

event_type

The event wich will trigger this rule

Type:

AutoModEventType

trigger_type

The type of content which will trigger the rule

Type:

AutoModEventType

trigger_metadata

Additional data used to determine whether a rule should be triggered. Different fields are relevant based on the value of trigger_type.

Type:

AutoModTriggerMetadata

actions

The actions which will execute when the rule is triggered

Type:

List[AutoModAction]

enabled

Whether the rule is enabled

Type:

bool

property exempt_roles

Yields the roles that should not be affected by the rule (Maximum of 20)

Note

This is equal to

for role_id in self._exempt_roles:
    role = self.guild.get_role(int(role_id))
    yield role or Object(int(role_id))
Yields:

Union[Role, Object] – An excluded role or an object with the id if the role is not found

property exempt_channels

Yields the channels that should not be affected by the rule (Maximum of 20)

Note

This is equal to

for channel_id in self._exempt_channels:
    channel = self.guild.get_role(int(channel_id))
    yield channel or Object(channel_id, type=GuildChannel, state=self._state)
Yields:

Union[Role, Object] – An excluded channel or an object with the id if the channel is not found

property creator

Returns the creator of the rule

Note

The Intents.members must be enabled, otherwise this may return `` None``

Raises:

ClientException: – If the member is not found and members intent is not enabled.

Returns:

The member, that created the rule.

Return type:

Optional[Member]

property created_at

When the rule was created in UTC

Type:

datetime.datetime

await delete(*, reason)

This function is a coroutine.

Deletes the automod rule, this requires the manage_server permission.

Parameters:

reason (Optional[str]) – The reason for deleting this rule. Shows up in the audit log.

Raises:
await edit(*, name=MISSING, event_type=MISSING, trigger_type=MISSING, trigger_metadata=MISSING, actions=MISSING, enabled=MISSING, exempt_roles=MISSING, exempt_channels=MISSING, reason=None)

This function is a coroutine.

Edits the automod rule, this requires the manage_server permission.

You only need to provide the parameters you want to edit the.

Parameters:
  • name (str) – The name, the rule should have. Only valid if it’s not a preset rule.

  • event_type (AutoModEventType) – Indicates in what event context a rule should be checked.

  • trigger_type (AutoModTriggerType) – Characterizes the type of content which can trigger the rule

  • trigger_metadata (AutoModTriggerMetadata) – Additional data used to determine whether a rule should be triggered. Different fields are relevant based on the value of trigger_type.

  • actions (List[AutoModAction]) – The actions which will execute when the rule is triggered.

  • enabled (bool) – Whether the rule is enabled.

  • exempt_roles (List[Snowflake]) – Up to 20 Role’s, that should not be affected by the rule.

  • exempt_channels (List[Snowflake]) – Up to 50 TextChannel/VoiceChannel/StageChannel’s, that should not be affected by the rule.

  • reason (Optional[str]) – The reason for editing the rule. Shows up in the audit log.

Raises:
Returns:

The updated rule on success.

Return type:

AutoModRule

AutoModActionPayload

class discord.AutoModActionPayload

Bases: object

Represents the payload for an on_automod_action() event

guild_id

The id of the guild in which action was executed

Type:

int

action

The action wich was executed

Type:

AutoModAction

rule_id

The id of the rule which action belongs to

Type:

int

rule_trigger_type

The trigger type of rule wich was triggered

Type:

AutoModTriggerType

user_id

The id of the user which generated the content which triggered the rule

Type:

int

channel_id

The id of the channel in which user content was posted

Type:

Optional[int]

message_id

The id of any user message which content belongs to

Note

This wil not exists if message was blocked by automod or content was not part of any message

Type:

Optional[int]

alert_system_message_id

The id of any system auto moderation messages posted as the result of this action

Note

This will only exist if the type of the action is send_alert_message

Type:

Optional[int]

content

The user generated text content

Important

The Intents.message_content intent is required to get a non-empty value for this field

Type:

str

matched_keyword

The word ot phrase configured in the rule that triggered the rule

Type:

str

matched_content

The substring in content that triggered the rule

Important

The message_content intent is required to get a non-empty value for this field

Type:

str

property guild

The guild in which action was executed

Returns:

The guild object

Return type:

Guild

property channel

The channel in wich user content was posted, if any.

Returns:

The TextChannel, VoiceChannel or ThreadChannel the user content was posted in.

Return type:

Optional[abc.GuildChannel]

property user

The user which content triggered the rule

Note

This can return None if the user is not in the cache

Returns:

The user that triggered the rule

Return type:

User

property member

The corresponding Member of the user in the guild.

Note

Intents.members must be enabled in order to use this

Raises:

ClientException: – If the member is not found and members intent is not enabled.

Returns:

The guild member

Return type:

Optional[Member]

WelcomeScreen

class discord.WelcomeScreen

Bases: object

Represents a welcome screen for a guild returned by welcome_screen().

Warning

Do not initialize this class directly. Use welcome_screen() instead.

guild

The guild the welcome screen belongs to

Type:

Guild

description

The description of the welcome screen

Type:

str

welcome_channels
Type:

List[WelcomeScreenChannel]

Integration

class discord.Integration

Bases: object

Represents a guild integration.

New in version 1.4.

id

The integration ID.

Type:

int

name

The integration name.

Type:

str

guild

The guild of the integration.

Type:

Guild

type

The integration type (i.e. Twitch).

Type:

str

enabled

Whether the integration is currently enabled.

Type:

bool

account

The account linked to this integration.

Type:

IntegrationAccount

user

The user that added this integration.

Type:

User

await delete()

This function is a coroutine. Deletes the integration. You must have the manage_guild permission to do this.

Raises:
  • Forbidden – You do not have permission to delete the integration.

  • HTTPException – Deleting the integration failed.

class discord.IntegrationAccount

Bases: object

Represents an integration account.

New in version 1.4.

id

The account ID.

Type:

int

name

The account name.

Type:

str

Member

class discord.Member

Bases: Messageable, _BaseUser

Represents a Discord member to a Guild.

This implements a lot of the functionality of User.

x == y

Checks if two members are equal. Note that this works with User instances too.

x != y

Checks if two members are not equal. Note that this works with User instances too.

hash(x)

Returns the member’s hash.

str(x)

Returns the members username if is_migrated is true, else the member’s name with discriminator.

Note

When the migration is complete, this will always return the username.

joined_at

A datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.

Type:

Optional[datetime.datetime]

activities

The activities that the user is currently doing.

Note

Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.

Type:

Tuple[Union[BaseActivity, Spotify]]

guild

The guild that the member belongs to.

Type:

Guild

nick

The guild specific nickname of the user.

Type:

Optional[str]

pending

Whether the member is pending member verification.

New in version 1.6.

Type:

bool

premium_since

A datetime object that specifies the date and time in UTC when the member used their Nitro boost on the guild, if available. This could be None.

Type:

Optional[datetime.datetime]

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)

Returns an AsyncIterator that enables receiving the destination’s message history.

You must have read_message_history permissions to use this.

Examples

Usage

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

Flattening into a list:

messages = await channel.history(limit=123).flatten()
# messages is now a list of Message...

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

  • before (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • after (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • around (Optional[Union[Snowflake, datetime.datetime]]) – Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.

  • oldest_first (Optional[bool]) – If set to True, return messages in oldest->newest order. Defaults to True if after is specified, otherwise False.

Raises:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Yields:

Message – The message with the message data parsed.

async with typing()

Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

Note

This is both a regular context manager and an async context manager. This means that both with and async with work with this.

Example Usage:

async with channel.typing():
    # do expensive stuff here
    await asyncio.sleep(15)

await channel.send('done!')
property name

Equivalent to User.name

property username

Equivalent to User.username

property global_name

Equivalent to User.global_name

property id

Equivalent to User.id

property discriminator

Equivalent to User.discriminator

property bot

Equivalent to User.bot

property system

Equivalent to User.system

property created_at

Equivalent to User.created_at

property default_avatar

Equivalent to User.default_avatar

property avatar

Equivalent to User.avatar

property dm_channel

Equivalent to User.dm_channel

await create_dm()

This function is a coroutine.

Creates a DMChannel with this user.

This should be rarely called, as this is done transparently for most people.

Returns:

The channel that was created.

Return type:

DMChannel

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 flags

Guild specific flags for the member.

Type:

GuildMemberFlags

property raw_status

The member’s overall status as a string value.

New in version 1.5.

Type:

str

property status

The member’s overall status. If the value is unknown, then it will be a str instead.

Type:

Status

property mobile_status

The member’s status on a mobile device, if applicable.

Type:

Status

property desktop_status

The member’s status on the desktop client, if applicable.

Type:

Status

property web_status

The member’s status on the web client, if applicable.

Type:

Status

is_on_mobile()

bool: A helper function that determines if a member is active on a mobile device.

property colour

A property that returns a colour denoting the rendered colour for the member. If the default colour is the one rendered then an instance of Colour.default() is returned.

There is an alias for this named color.

Type:

Colour

property color

A property that returns a color denoting the rendered color for the member. If the default color is the one rendered then an instance of Colour.default() is returned.

There is an alias for this named colour.

Type:

Colour

property role_ids

An iterable of int contain the ID’s of the roles the member has. You can use this to check on an efficient way whether a member has a role or not

Type:

utils.SnowflakeList

property roles

A list of Role that the member belongs to. Note that the first element of this list is always the default @everyone’ role.

These roles are sorted by their position in the role hierarchy.

Type:

List[Role]

property mention

Returns a string that allows you to mention the member.

Type:

str

property display_name

Returns the user’s display name.

This is either the guild nick, the global_name or the username of the user.

Type:

str

property guild_avatar_url

Returns the guild-specific banner asset for the member if any.

Type:

Optional[Asset]

guild_avatar_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the guild-specific avatar of the member if any, else None.

The format must be one of ‘webp’, ‘jpeg’, or ‘png’. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (str) – The format to attempt to convert the avatar to.

  • static_format (str) – The format to attempt to convert the avatar to if the avatar is animated.

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or invalid size.

Returns:

The resulting CDN asset if any.

Return type:

Optional[Asset]

is_guild_avatar_animated()

bool: Indicates if the member has an animated guild-avatar.

property display_avatar_url

Asset: Returns the displayed avatar of the member.

This is in the following order: - Guild-specific avatar if available - User avatar if available - Default avatar

property display_avatar

An alias for display_avatar_url.

Type:

Asset

display_avatar_url_as(format=None, static_format='webp', size=1024)

Asset: Same behaviour as User.avatar_url_as() and guild_avatar_url_as() but it prefers the guild-specific avatar

property guild_banner_url

Returns the guild-specific banner asset for the member if any.

Type:

Optional[Asset]

guild_banner_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the guild-specific banner of the member if any, else None.

The format must be one of ‘webp’, ‘jpeg’, ‘gif’ or ‘png’. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (str) – The format to attempt to convert the banner to.

  • static_format (str) – The format to attempt to convert the banner to if the banner is animated.

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or invalid size.

Returns:

The resulting CDN asset if any.

Return type:

Optional[Asset}

is_guild_banner_animated()

bool: Indicates if the member has an animated guild-banner.

property display_banner_url

Returns the guild-specific banner asset for the member if he has one, else the default banner asset if any.

Type:

Optional[Asset]

display_banner_url_as(format=None, static_format='webp', size=1024)

Optional[Asset]: Same behaviour as User.banner_url_as() and guild_banner_url_as() but it prefers the guild-specific banner

property activity

Returns the primary activity the user is currently doing. Could be None if no activity is being done.

Note

Due to a Discord API limitation, this may be None if the user is listening to a song on Spotify with a title longer than 128 characters. See GH-1738 for more information.

Note

A user may have multiple activities, these can be accessed under activities.

Type:

Union[BaseActivity, Spotify]

mentioned_in(message)

Checks if the member is mentioned in the specified message.

Parameters:

message (Message) – The message to check if you’re mentioned in.

Returns:

Indicates if the member is mentioned in the message.

Return type:

bool

permissions_in(channel)

An alias for abc.GuildChannel.permissions_for().

Basically equivalent to:

channel.permissions_for(self)
Parameters:

channel (abc.GuildChannel) – The channel to check your permissions for.

Returns:

The resolved permissions for the member.

Return type:

Permissions

property top_role

Returns the member’s highest role.

This is useful for figuring where a member stands in the role hierarchy chain.

Type:

Role

property guild_permissions

Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use either permissions_in() or abc.GuildChannel.permissions_for().

This does take into consideration guild ownership and the administrator implication.

Type:

Permissions

property voice

Returns the member’s current voice state.

Type:

Optional[VoiceState]

property communication_disabled_until

The time until the member is timeouted, if any

Type:

Optional[datetime.datetime]

property timed_out

Returns True when the member is timed out.

New in version 2.0.

Type:

class.`bool`

await timeout(until, *, reason=None)

This function is a coroutine.

A shortcut method to timeout a member. This just calls edit() with the communication_disabled_until field set.

The moderate_members permission is needed to do this.

Parameters:
  • until (Union[datetime, timedelta]) –

    Until when the member should be timeouted. This can be a timezone aware datetime object or a timedelta that will be added to the current time.

    Note

    This can be max 28 days from current time!

  • reason (Optional[str]) – The reason for sending the member to timeout - Shows up in the audit-log

Raises:
await remove_timeout(*, reason=None)

This function is a coroutine.

A shortcut method to remove a member from timeout.

The moderate_members permission is needed to do this.

Parameters:

reason (Optional[str]) – The reason for removing the member from timeout - Shows up in the audit-log

Raises:
  • Forbidden – The bot missing access to remove this member from timeout

  • HTTPException – Removing the member from timeout failed

await ban(delete_message_days=None, delete_message_seconds=0, reason=None)

This function is a coroutine.

Bans this member. Equivalent to Guild.ban().

await unban(*, reason=None)

This function is a coroutine.

Unbans this member. Equivalent to Guild.unban().

await kick(*, reason=None)

This function is a coroutine.

Kicks this member. Equivalent to Guild.kick().

await edit(*, nick=MISSING, mute=MISSING, deafen=MISSING, suppress=MISSING, roles=MISSING, voice_channel=MISSING, flags=MISSING, communication_disabled_until=MISSING, reason=None)

This function is a coroutine.

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below:

All parameters are optional.

Changed in version 1.1: Can now pass None to voice_channel to kick a member from voice.

Parameters:
  • nick (Optional[str]) – The member’s new nickname. Use None to remove the nickname.

  • mute (bool) – Indicates if the member should be guild muted or un-muted.

  • deafen (bool) – Indicates if the member should be guild deafened or un-deafened.

  • suppress (bool) –

    Indicates if the member should be suppressed in stage channels.

    New in version 1.7.

  • roles (Optional[List[Role]]) – The member’s new list of roles. This replaces the roles.

  • voice_channel (Optional[VoiceChannel]) – The voice channel to move the member to. Pass None to kick them from voice.

  • flags (Optional[GuildMemberFlags]) – The new flags for this member. Note that you are currently only able to update the GuildMemberFlags.bypasses_verification flag.

  • communication_disabled_until (Optional[datetime.datetime]) –

    Temporarily puts the member in timeout until this time. If None, then the member is removed from timeout.

    Note

    The datetime object must be timezone aware.

  • reason (Optional[str]) – The reason for editing this member. Shows up on the audit log.

Raises:
  • TypeError – The datetime object passed to communication_disabled_until is not timezone aware

  • Forbidden – You do not have the proper permissions to the action requested.

  • HTTPException – The operation failed.

await request_to_speak()

This function is a coroutine.

Request to speak in the connected channel.

Only applies to stage channels.

Note

Requesting members that are not the client is equivalent to edit providing suppress as False.

New in version 1.7.

Raises:
  • Forbidden – You do not have the proper permissions to the action requested.

  • HTTPException – The operation failed.

property avatar_decoration

Equivalent to User.avatar_decoration

avatar_decoration_url_as(*, format=None, size=1024)

Returns an Asset for the avatar decoration the user has. Could be None.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the avatar decoration to. If the format is None, then it is automatically detected into static_format.

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format, or invalid size.

Returns:

The resulting CDN asset if any.

Return type:

Optional[Asset]

property avatar_url

Equivalent to User.avatar_url

avatar_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the avatar to. If the format is None, then it is automatically detected into either ‘gif’ or static_format depending on the avatar being animated or not.

  • static_format (Optional[str]) – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or static_format, or invalid size.

Returns:

The resulting CDN asset.

Return type:

Asset

property banner_color

Equivalent to User.banner_color

property banner_colour

Equivalent to User.banner_colour

property banner_url

Equivalent to User.banner_url

banner_url_as(*, format=None, static_format='webp', size=1024)

Returns an Asset for the banner the user has. Could be None.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated banners. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the banner to. If the format is None, then it is automatically detected into either ‘gif’ or static_format depending on the banner being animated or not.

  • static_format (Optional[str]) – Format to attempt to convert only non-animated banner to. Defaults to ‘webp’

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or static_format, or invalid size.

Returns:

The resulting CDN asset if any.

Return type:

Optional[Asset]

property default_avatar_url

Equivalent to User.default_avatar_url

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

This can only be used by bot accounts.

Parameters:

id (int) – The message ID to look for.

Raises:
  • NotFound – The specified message was not found.

  • Forbidden – You do not have the permissions required to get a message.

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

property hex_banner_color

Equivalent to User.hex_banner_color

is_avatar_animated()

bool: Indicates if the user has an animated avatar.

is_banner_animated()

bool: Indicates if the user has an animated banner.

property is_migrated

Equivalent to User.is_migrated

await move_to(channel, *, reason=None)

This function is a coroutine.

Moves a member to a new voice channel (they must be connected first).

You must have the move_members permission to use this.

This raises the same exceptions as edit().

Changed in version 1.1: Can now pass None to kick a member from voice.

Parameters:
  • channel (Optional[Union[VoiceChannel, StageChannel]) – The new voice channel to move the member to. Pass None to kick them from voice.

  • reason (Optional[str]) – The reason for doing this action. Shows up on the audit log.

await pins()

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the Message objects returned by this method do not contain complete Message.reactions data.

Raises:

HTTPException – Retrieving the pinned messages failed.

Returns:

The messages that are currently pinned.

Return type:

List[Message]

await send(content=None, *, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content). If the content is set to None (the default), then the embed parameter must be provided.

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects.

If the embed parameter is provided, it must be of type Embed and it must be a rich embed type.

Parameters:
  • content (str) – The content of the message to send.

  • tts (bool) – Indicates if the message should be sent using text-to-speech.

  • embed (Embed) – The rich embed for the content.

  • embeds (List[Embed]) – A list containing up to ten embeds

  • components (List[Union[ActionRow, List[Union[Button, Select]]]]) – A list of up to five ActionRow`s or :class:`list, each containing up to five Button or one Select like object.

  • file (File) – The file to upload.

  • files (List[File]) – A list of files to upload. Must be a maximum of 10.

  • stickers (List[GuildSticker]) – A list of up to 3 discord.GuildSticker that should be sent with the message.

  • nonce (int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

  • allowed_mentions (AllowedMentions) –

    Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    New in version 1.4.

  • reference (Union[Message, MessageReference]) –

    A reference to the Message to which you are replying, this can be created using to_reference() or passed directly as a Message. You can control whether this mentions the author of the referenced message using the replied_user attribute of allowed_mentions or by setting mention_author.

    New in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    New in version 1.6.

  • suppress_embeds (bool) – Whether to supress embeds send with the message, default to False

  • suppress_notifications (bool) –

    Whether to suppress desktop- & push-notifications for this message, default to False

    Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.

    New in version 2.0.

Raises:
Returns:

The message that was sent.

Return type:

Message

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

Typing indicator will go away after 10 seconds, or after a message is sent.

await add_roles(*roles, reason=None, atomic=True)

This function is a coroutine.

Gives the member a number of Roles.

You must have the manage_roles permission to use this, and the added Roles must appear lower in the list of roles than the highest role of the member.

Parameters:
  • *roles (abc.Snowflake) – An argument list of abc.Snowflake representing a Role 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:
await remove_roles(*roles, reason=None, atomic=True)

This function is a coroutine.

Removes Roles from this member.

You must have the manage_roles permission to use this, and the removed Roles must appear lower in the list of roles than the highest role of the member.

Parameters:
  • *roles (abc.Snowflake) – An argument list of abc.Snowflake representing a Role to remove from the member.

  • reason (Optional[str]) – The reason for removing these roles. Shows up on the audit log.

  • atomic (bool) – Whether to atomically remove roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.

Raises:
  • Forbidden – You do not have permissions to remove these roles.

  • HTTPException – Removing the roles failed.

GuildMemberFlags

class discord.GuildMemberFlags

Bases: BaseFlags

Wraps up the Discord Guild Member flags.

x == y

Checks if two GuildMemberFlags are equal.

x != y

Checks if two GuildMemberFlags are not equal.

hash(x)

Return the flag’s hash.

iter(x)

Returns an iterator of (name, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

value

The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.

Type:

int

rejoined

Returns True if the member has left and rejoined the guild

Type:

bool

completed_onboarding

Returns True if the member has completed onboarding

Type:

bool

bypasses_verification

Returns True if the member bypasses guild verification requirements

Note

This flag is editable and let you manually “verify” the member. This requires moderate_members permissions.

Type:

bool

started_onboarding

Returns True if the member has started onboarding

Type:

bool

Spotify

class discord.Spotify

Bases: object

Represents a Spotify listening activity from Discord. This is a special case of Activity that makes it easier to work with the Spotify integration.

x == y

Checks if two activities are equal.

x != y

Checks if two activities are not equal.

hash(x)

Returns the activity’s hash.

str(x)

Returns the string ‘Spotify’.

property type

Returns the activity’s type. This is for compatibility with Activity.

It always returns ActivityType.listening.

Type:

ActivityType

property created_at

When the user started listening in UTC.

New in version 1.3.

Type:

Optional[datetime.datetime]

property colour

Returns the Spotify integration colour, as a Colour.

There is an alias for this named color

Type:

Colour

property color

Returns the Spotify integration colour, as a Colour.

This is an alias for colour.

Type:

Colour

property name

The activity’s name. This will always return “Spotify”.

Type:

str

property title

The title of the song being played.

Type:

str

property artists

The artists of the song being played.

Type:

List[str]

property artist

The artist of the song being played.

This does not attempt to split the artist information into multiple artists. Useful if there’s only a single artist.

Type:

str

property album

The album that the song being played belongs to.

Type:

str

property album_cover_url

The album cover image URL from Spotify’s CDN.

Type:

str

property track_id

The track ID used by Spotify to identify this song.

Type:

str

property start

When the user started playing this song in UTC.

Type:

datetime.datetime

property end

When the user will stop playing this song in UTC.

Type:

datetime.datetime

property duration

The duration of the song being played.

Type:

datetime.timedelta

property position

The current position of the song being played.

Type:

float

property party_id

The party ID of the listening party.

Type:

str

VoiceState

class discord.VoiceState

Bases: object

Represents a Discord user’s voice state.

await voice(...)
Acts as a shortcut to :meth:`VoiceProtocol.connect`.
Raises :exc:`NotInVoiceChannel` if :attr:`channel` is ``None``.
deaf

Indicates if the user is currently deafened by the guild.

Type:

bool

mute

Indicates if the user is currently muted by the guild.

Type:

bool

self_mute

Indicates if the user is currently muted by their own accord.

Type:

bool

self_deaf

Indicates if the user is currently deafened by their own accord.

Type:

bool

self_stream

Indicates if the user is currently streaming via ‘Go Live’ feature.

New in version 1.3.

Type:

bool

self_video

Indicates if the user is currently broadcasting video.

Type:

bool

suppress

Indicates if the user is suppressed from speaking.

Only applies to stage channels.

New in version 1.7.

Type:

bool

requested_to_speak_at

A datetime object that specifies the date and time in UTC that the member requested to speak. It will be None if they are not requesting to speak anymore or have been accepted to speak.

Only applicable to stage channels.

New in version 1.7.

Type:

Optional[datetime.datetime]

afk

Indicates if the user is currently in the AFK channel in the guild.

Type:

bool

channel

The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.

Type:

Optional[Union[VoiceChannel, StageChannel]]

Emoji

class discord.Emoji

Bases: _EmojiTag

Represents a custom emoji.

Depending on the way this object was created, some of the attributes can have a value of None.

x == y

Checks if two emoji are the same.

x != y

Checks if two emoji are not the same.

hash(x)

Return the emoji’s hash.

iter(x)

Returns an iterator of (field, value) pairs. This allows this class to be used as an iterable in list/dict/etc constructions.

str(x)

Returns the emoji rendered for discord.

name

The name of the emoji.

Type:

str

id

The emoji’s ID.

Type:

int

require_colons

If colons are required to use this emoji in the client (:PJSalt: vs PJSalt).

Type:

bool

animated

Whether an emoji is animated or not.

Type:

bool

managed

If this emoji is managed by a Twitch integration.

Type:

bool

guild_id

The guild ID the emoji belongs to.

Type:

int

available

Whether the emoji is available for use.

Type:

bool

user

The user that created the emoji. This can only be retrieved using Guild.fetch_emoji() and having the manage_emojis permission.

Type:

Optional[User]

property created_at

Returns the emoji’s creation time in UTC.

Type:

datetime.datetime

property url

Returns the asset of the emoji.

This is equivalent to calling url_as() with the default parameters (i.e. png/gif detection).

Type:

Asset

property roles

A list of roles that is allowed to use this emoji.

If roles is empty, the emoji is unrestricted.

Type:

List[Role]

property guild

The guild this emoji belongs to.

Type:

Guild

url_as(*, format=None, static_format='png')

Returns an Asset for the emoji’s url.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’. ‘gif’ is only valid for animated emojis.

New in version 1.6.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the emojis to. If the format is None, then it is automatically detected as either ‘gif’ or static_format, depending on whether the emoji is animated or not.

  • static_format (Optional[str]) – Format to attempt to convert only non-animated emoji’s to. Defaults to ‘png’

Raises:

InvalidArgument – Bad image format passed to format or static_format.

Returns:

The resulting CDN asset.

Return type:

Asset

is_usable()

bool: Whether the bot can use this emoji.

New in version 1.3.

await delete(*, reason=None)

This function is a coroutine.

Deletes the custom emoji.

You must have manage_emojis permission to do this.

Parameters:

reason (Optional[str]) – The reason for deleting this emoji. Shows up on the audit log.

Raises:
await edit(*, name=None, roles=None, reason=None)

This function is a coroutine.

Edits the custom emoji.

You must have manage_emojis permission to do this.

Parameters:
  • name (str) – The new emoji name.

  • roles (Optional[list[Role]]) – A list of Roles that can use this emoji. Leave empty to make it available to everyone.

  • reason (Optional[str]) – The reason for editing this emoji. Shows up on the audit log.

Raises:

PartialEmoji

class discord.PartialEmoji

Bases: _EmojiTag

Represents a “partial” emoji.

This model will be given in two scenarios:

x == y

Checks if two emoji are the same.

x != y

Checks if two emoji are not the same.

hash(x)

Return the emoji’s hash.

str(x)

Returns the emoji rendered for discord.

name

The custom emoji name, if applicable, or the unicode codepoint of the non-custom emoji. This can be None if the emoji got deleted (e.g. removing a reaction with a deleted emoji).

Type:

Optional[str]

animated

Whether the emoji is animated or not.

Type:

bool

id

The ID of the custom emoji, if applicable.

Type:

Optional[int]

classmethod from_string(string)

Converts a (custom) emoji as they are in a message into a partial emoji object.

Note

To get them, type a custom emoji into the chat, put an \ in front of it and send it. You can then use what comes out when you add a reaction or similar.

Warning

This does not support the :emoji: format for (standard) emojis

Returns:

The emoji object if the string was valid.

Return type:

PartialEmoji

is_custom_emoji()

bool: Checks if this is a custom non-Unicode emoji.

is_unicode_emoji()

bool: Checks if this is a Unicode emoji.

property created_at

Returns the emoji’s creation time in UTC, or None if Unicode emoji.

New in version 1.6.

Type:

Optional[datetime.datetime]

property url

Returns the asset of the emoji, if it is custom.

This is equivalent to calling url_as() with the default parameters (i.e. png/gif detection).

Type:

Asset

url_as(*, format=None, static_format='png')

Returns an Asset for the emoji’s url, if it is custom.

The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’. ‘gif’ is only valid for animated emojis.

New in version 1.7.

Parameters:
  • format (Optional[str]) – The format to attempt to convert the emojis to. If the format is None, then it is automatically detected as either ‘gif’ or static_format, depending on whether the emoji is animated or not.

  • static_format (Optional[str]) – Format to attempt to convert only non-animated emoji’s to. Defaults to ‘png’

Raises:

InvalidArgument – Bad image format passed to format or static_format.

Returns:

The resulting CDN asset.

Return type:

Asset

Role

class discord.Role

Bases: Hashable

Represents a Discord role in a Guild.

x == y

Checks if two roles are equal.

x != y

Checks if two roles are not equal.

x > y

Checks if a role is higher than another in the hierarchy.

x < y

Checks if a role is lower than another in the hierarchy.

x >= y

Checks if a role is higher or equal to another in the hierarchy.

x <= y

Checks if a role is lower or equal to another in the hierarchy.

hash(x)

Return the role’s hash.

str(x)

Returns the role’s name.

id

The ID for the role.

Type:

int

name

The name of the role.

Type:

str

guild

The guild the role belongs to.

Type:

Guild

hoist

Indicates if the role will be displayed separately from other members.

Type:

bool

icon

The role-icon hash

Type:

Optional[str]

unicode_emoji

The unicode emoji of the role (shows as role-icon)

Type:

Optional[str]

position

The position of the role. This number is usually positive. The bottom role has a position of 0.

Type:

int

managed

Indicates if the role is managed by the guild through some form of integrations such as Twitch.

Type:

bool

mentionable

Indicates if the role can be mentioned by users.

Type:

bool

tags

The role tags associated with this role.

Type:

Optional[RoleTags]

is_default()

bool: Checks if the role is the default role.

is_bot_managed()

bool: Whether the role is associated with a bot.

New in version 1.6.

is_premium_subscriber()

bool: Whether the role is the premium subscriber, AKA “boost”, role for the guild.

New in version 1.6.

is_integration()

bool: Whether the role is managed by an integration.

New in version 1.6.

property permissions

Returns the role’s permissions.

Type:

Permissions

property colour

Returns the role colour. An alias exists under color.

Type:

Colour

property color

Returns the role color. An alias exists under colour.

Type:

Colour

property created_at

Returns the role’s creation time in UTC.

Type:

datetime.datetime

property mention

Returns a string that allows you to mention a role.

Type:

str

property members

Returns all the members with this role.

Type:

List[Member]

property icon_url

Returns the role icon asset.

Type:

Asset

icon_url_as(*, format='webp', size=1024)

Returns an Asset for the role icon.

The format must be one of ‘webp’, ‘jpeg’, or ‘png’. The size must be a power of 2 between 16 and 4096.

Parameters:
  • format (str) – The format to attempt to convert the icon to.

  • size (int) – The size of the image to display.

Raises:

InvalidArgument – Bad image format passed to format or invalid size.

Returns:

The resulting CDN asset.

Return type:

Asset

await edit(*, reason=None, **fields)

This function is a coroutine.

Edits the role.

You must have the manage_roles permission to use this.

All fields are optional.

Changed in version 1.4: Can now pass int to colour keyword-only parameter.

Parameters:
  • name (str) – The new role name to change to.

  • permissions (Permissions) – The new permissions to change to.

  • colour (Union[Colour, int]) – The new colour to change to. (aliased to color as well)

  • hoist (bool) – Indicates if the role should be shown separately in the member list.

  • mentionable (bool) – Indicates if the role should be mentionable by others.

  • position (int) – The new role’s position. This must be below your top role’s position or it will fail.

  • unicode_emoji (str) – The new role-icon as a unicode-emoji This is only available for guilds that contain ROLE_ICON in Guild.features.

  • icon (bytes) – A bytes-like object representing the new role-icon. Only PNG/JPEG is supported. This is only available for guilds that contain ROLE_ICON in Guild.features. Could be None to denote removal of the icon.

  • reason (Optional[str]) – The reason for editing this role. Shows up on the audit log.

Raises:
  • Forbidden – You do not have permissions to change the role.

  • HTTPException – Editing the role failed.

  • InvalidArgument – An invalid position was given or the default role was asked to be moved.

await delete(*, reason=None)

This function is a coroutine.

Deletes the role.

You must have the manage_roles permission to use this.

Parameters:

reason (Optional[str]) – The reason for deleting this role. Shows up on the audit log.

Raises:

RoleTags

class discord.RoleTags

Bases: object

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 and Guild classes as well.

New in version 1.6.

bot_id

The bot’s user ID that manages this role.

Type:

Optional[int]

integration_id

The integration ID that manages the role.

Type:

Optional[int]

is_bot_managed()

bool: Whether the role is associated with a bot.

is_premium_subscriber()

bool: Whether the role is the premium subscriber, AKA “boost”, role for the guild.

is_integration()

bool: Whether the role is managed by an integration.

TextChannel

class discord.TextChannel

Bases: Messageable, GuildChannel, Hashable

Represents a Discord guild text channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns the channel’s name.

name

The channel name.

Type:

str

guild

The guild the channel belongs to.

Type:

Guild

id

The channel ID.

Type:

int

category_id

The category channel ID this channel belongs to, if applicable.

Type:

Optional[int]

topic

The channel’s topic. None if it doesn’t exist.

Type:

Optional[str]