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

Added 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”.

Added 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().

Added in version 2.0.

Type:

Optional[str]

avatar_decoration

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

Added in version 2.0.

Type:

Optional[str]

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.

Added in version 1.7.

Type:

List[Guild]

property accent_color

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

Note

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

Type:

Optional[Colour]

property accent_colour

An alias for accent_color.

Type:

Optional[Colour]

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

Returns an Asset for the avatar decoration the user has. Could 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.

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

    Added in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

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

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

Added 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().

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

    Added in version 1.4.

  • spoiler (bool) –

    Whether the file is a spoiler.

    Added in version 1.4.

  • description (bool) –

    The description (alt text) for the file.

    This will be default to the description. Set the value 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.

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

Added in version 1.5.

Type:

Optional[MessageReference]

mention_everyone

Specifies if the message mentions everyone.

Note

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

Type:

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.

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

Added in version 1.6.

Type:

List[Sticker]

interaction

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

Added in version 2.0.

Type:

Optional[MessageInteraction]

role_subscription

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

Added in version 2.0.

Type:

Optional[RoleSubscriptionInfo]

position

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

Added in version 2.0.

Type:

Optional[int]

guild

The guild that the message belongs to if any.

Type:

Optional[Guild]

raw_mentions

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

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

Type:

List[int]

raw_channel_mentions

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

Type:

List[int]

raw_role_mentions

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

Type:

List[int]

clean_content

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

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

Note

This does not affect markdown. If you want to escape or remove markdown then use utils.escape_markdown() 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.

Added in version 1.3.

system_content

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

In the case of MessageType.default, this just returns the 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.

    Added in version 1.4.

Raises:
  • HTTPException – Editing the message failed.

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

await publish()

This function is a coroutine.

Publishes this message to your announcement channel.

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

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

  • HTTPException – Publishing the message failed.

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

This function is a coroutine.

Pins the message.

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

Parameters:
  • suppress_system_message (bool) –

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

    Added in version 2.0.

  • reason (Optional[str]) –

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

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

Added in version 1.4.

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

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

  • HTTPException – Unpinning the message failed.

await add_reaction(emoji)

This function is a coroutine.

Add a reaction to the message.

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

You must have the read_message_history permission to use this. If nobody else has reacted to the message using this emoji, 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.

Added in version 1.3.

Parameters:

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

Raises:
  • HTTPException – Clearing the reaction failed.

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

  • NotFound – The emoji you specified was not found.

  • InvalidArgument – The emoji parameter is invalid.

await clear_reactions()

This function is a coroutine.

Removes all the reactions from the message.

You need the manage_messages permission to use this.

Raises:
  • HTTPException – Removing the reactions failed.

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

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

This function is a coroutine.

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

Added in version 1.6.

Raises:
  • HTTPException – Sending the message failed.

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

  • InvalidArgument – The files list is not of the appropriate size or you specified 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.

Added in version 1.6.

Parameters:

fail_if_not_exists (bool) –

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

Added in version 1.7.

Returns:

The reference to this message.

Return type:

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.

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

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

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

Added in version 1.3.

Raises:
  • HTTPException – Clearing the reaction failed.

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

  • NotFound – The emoji you specified was not found.

  • InvalidArgument – The emoji parameter is invalid.

Guild

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.

Added in version 1.4.

Type:

Optional[int]

banner

The guild’s banner.

Type:

Optional[str]

description

The guild’s description.

Type:

Optional[str]

mfa_level

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

Type:

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.

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

Added in version 1.7.

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

Type:

List[StageChannel]

property me

Similar to Client.user except an instance 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.

Added in version 1.3.

Type:

Optional[TextChannel]

property public_updates_channel

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

If no channel is set, then this returns None.

Added in version 2.0.

Type:

Optional[TextChannel]

property safety_alerts_channel

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

If no channel is set, then this returns None.

Added in version 2.0.

Type:

Optional[TextChannel]

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

Added in version 1.6.

Type:

Optional[Role]

property self_role

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

Added in version 1.6.

Type:

Optional[Role]

property owner

The member that owns the guild.

Type:

Optional[Member]

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.

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

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

    Added in version 1.7.

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

  • HTTPException – Creating the channel failed.

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

Returns:

The channel that was just created.

Return type:

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.

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

Added in version 2.0.

Returns:

The active threads and forum posts in the guild.

Return type:

List[Union[ThreadChannel, ForumPost]]

await fetch_member(member_id)

This function is a coroutine.

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

Note

This method is an API call. If you have Intents.members and member cache enabled, 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.

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

    Added in version 1.7.

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

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

  • InvalidArgument – An integer was not passed for days.

Returns:

The number of members estimated to be pruned.

Return type:

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.

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

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

Added in version 1.3.

Raises:

HTTPException – Retrieving the roles failed.

Returns:

All roles in the guild.

Return type:

List[Role]

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

This function is a coroutine.

Creates a Role for the guild.

All fields are optional.

You must have the manage_roles permission to do this.

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

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

Added in version 1.4.

Example:

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

await guild.edit_role_positions(positions=positions)
Parameters:
  • 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).

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

Added in version 1.5.

Parameters:

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

Raises:

ClientException – The members intent is not enabled.

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

This function is a coroutine.

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

This is a websocket operation and can be slow.

Added in version 1.3.

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

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

  • presences (bool) –

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

    Added in version 1.6.

  • cache (bool) – Whether to cache the members internally. This makes operations such 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.

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

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

Added in version 2.0.

Returns:

The welcome screen of the guild if any.

Return type:

Optional[WelcomeScreen]

await onboarding()

This function is a coroutine.

Fetches the onboarding configuration for the guild.

Added in version 2.0.

Returns:

The onboarding configuration fetched.

Return type:

Onboarding

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

This function is a coroutine.

Edits the onboarding configuration for the guild.

Added in version 2.0.

Parameters:
  • prompts (List[PartialOnboardingPrompt]) – The prompts that will be shown to new members (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.

Added in version 2.0.

'FEATURE_NAME' in features

Checks if the guild has the feature.

features.FEATURE_NAME

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

features.FEATURE_NAME = True

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

features.FEATURE_NAME = False

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

del features.FEATURE_NAME

The same as features.FEATURE_NAME = False

features.parsed()

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

features.merge(other)

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

features == other

Checks if two feature objects are equal.

features != other

Checks if two feature objects are not equal.

iter(features)

Returns an iterator over the enabled features.

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

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

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

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

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

Added in version 2.0.

Type:

class.`bool`

await timeout(until, *, reason=None)

This function is a coroutine.

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

The moderate_members permission is needed to do this.

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

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

    Note

    This can be max 28 days from current time!

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

Raises:
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.

    Added in version 1.7.

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

  • voice_channel (Optional[VoiceChannel]) – The voice channel to move the member to. 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.

Added in version 1.7.

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

  • HTTPException – The operation failed.

property avatar_decoration

Equivalent to User.avatar_decoration

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

Returns an Asset for the avatar decoration the user has. Could 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.

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

    Added in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

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

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

Added in version 1.3.

Type:

Optional[datetime.datetime]

property colour

Returns the Spotify integration colour, as a Colour.

There is an alias for this named color

Type:

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.

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

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

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

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

Added in version 1.3.

await delete(*, reason=None)

This function is a coroutine.

Deletes the custom emoji.

You must have manage_emojis permission to do this.

Parameters:

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

Raises:
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.

Added in version 1.6.

Type:

Optional[datetime.datetime]

property url

Returns the asset of the emoji, if it is custom.

This is equivalent to calling url_as() with the default parameters (i.e. png/gif detection).

Type:

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.

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

Added in version 1.6.

is_premium_subscriber()

bool: Whether the role is the premium subscriber, AKA “boost”, role for the guild.

Added in version 1.6.

is_integration()

bool: Whether the role is managed by an integration.

Added in version 1.6.

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

Added 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]

icon_emoji

The channel’s icon-emoji, if set.

Type:

Optional[PartialEmoji]

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

Type:

int

last_message_id

The last message ID of the message sent to this channel. It may not point to an existing or valid message.

Type:

Optional[int]

slowmode_delay

The number of seconds a member must wait between sending messages in this channel. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode.

Type:

int

async for ... in await archived_threads(*, private=False, joined_private=True, before=None, limit=100)

This function is a coroutine.

Returns an abc.AsyncIterator to retrieve archived threads from this channel.

Parameters:
  • private (bool) – Whether to fetch all private threads instead of public ones. Defaults to False.

  • joined_private (bool) –

    Whether to only fetch private threads the bot has joined. Defaults to True.

    Note

    The manage_threads() permission is required in order to fetch not-joined private threads.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Only fetch threads created before this date or ID.

  • limit (int) – The maximum number of threads to fetch. Defaults to 100.

Raises:
  • Forbidden – The bot lacks permissions to fetch not-joined private threads.

  • HTTPException – Fetching the threads failed.

Returns:

An iterator to retrieve the archived threads.

Return type:

ArchivedThreadIterator

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

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

You must have read_message_history permissions to use this.

Examples

Usage

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

Flattening into a list:

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

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of messages to retrieve. 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 type

The channel’s Discord type.

Type:

ChannelType

get_thread(id)

Optional[ThreadChannel]: Returns the cached thread in this channel with the given ID if any, else None

property threads

Returns a list of cached threads for this channel

Type:

List[ThreadChannel]

permissions_for(member, /)

Handles permission resolution for the current Member.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

Parameters:

member (Member) – The member to resolve permissions for.

Returns:

The resolved permissions for the member.

Return type:

Permissions

property members

Returns all members that can see this channel.

Type:

List[Member]

is_nsfw()

bool: Checks if the channel is NSFW.

is_news()

bool: Checks if the channel is a news channel.

property last_message

Fetches the last message from this channel in cache.

The message might not be valid or point to an existing message.

Reliable Fetching

For a slightly more reliable method of fetching the last message, consider using either history() or fetch_message() with the last_message_id attribute.

Returns:

The last message in this channel or None if not found.

Return type:

Optional[Message]

await edit(*, reason=None, **options)

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

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

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

Parameters:
  • name (str) – The new channel name.

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

  • position (int) – The new channel’s position.

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

  • sync_permissions (bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults to False.

  • category (Optional[CategoryChannel]) – The new category for this channel. Can be None to remove the category.

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

  • type (ChannelType) – Change the type of this text channel. Currently, only conversion between ChannelType.text and ChannelType.news is supported. This is only available to guilds that contain NEWS in Guild.features.

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

  • overwrites (dict) – A dict of target (either a role or a member) to PermissionOverwrite to apply to the channel.

Raises:
  • InvalidArgument – If position is less than 0 or greater than the number of channels, or if the permission overwrite information is not in proper form.

  • Forbidden – You do not have permissions to edit the channel.

  • HTTPException – Editing the channel failed.

await clone(*, name=None, reason=None)

This function is a coroutine.

Clones this channel. This creates a channel with the same properties as this channel.

You must have the manage_channels permission to do this.

Added in version 1.1.

Parameters:
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this channel name.

  • reason (Optional[str]) – The reason for cloning 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.

Returns:

The channel that was created.

Return type:

abc.GuildChannel

await delete_messages(messages, reason=None)

This function is a coroutine.

Deletes a list of messages. This is similar to Message.delete() except it bulk deletes multiple messages.

As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.

You cannot bulk delete more than 100 messages or messages that are older than 14 days old.

You must have the manage_messages permission to use this.

Usable only by bot accounts.

Parameters:
  • messages (Iterable[abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.

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

Raises:
  • ClientException – The number of messages to delete was more than 100.

  • Forbidden – You do not have proper permissions to delete the messages or you’re not using a bot account.

  • NotFound – If single delete, then the message was already deleted.

  • HTTPException – Deleting the messages failed.

await purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)

This function is a coroutine.

Purges a list of messages that meet the criteria given by the predicate check. If a check is not provided then all messages are deleted without discrimination.

You must have the manage_messages permission to delete messages even if they are your own (unless you are a user account). The read_message_history permission is also needed to retrieve message history.

Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.

Examples

Deleting bot’s messages

def is_me(m):
    return m.author == client.user

deleted = await channel.purge(limit=100, check=is_me)
await channel.send('Deleted {} message(s)'.format(len(deleted)))
Parameters:
  • limit (Optional[int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.

  • check (Callable[[Message], bool]) – The function used to check if a message should be deleted. It must take a Message as its sole parameter.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Same as before in history().

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Same as after in history().

  • around (Optional[Union[abc.Snowflake, datetime.datetime]]) – Same as around in history().

  • oldest_first (Optional[bool]) – Same as oldest_first in history().

  • bulk (bool) – If True, use bulk delete. Setting this to False is useful for mass-deleting a bot’s own messages without Permissions.manage_messages. When True, will fall back to single delete if current account is a user bot (now deprecated), or if messages are older than two weeks.

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

Raises:
  • Forbidden – You do not have proper permissions to do the actions required.

  • HTTPException – Purging the messages failed.

Returns:

The list of messages that were deleted.

Return type:

List[Message]

await webhooks()

This function is a coroutine.

Gets the list of webhooks from this channel.

Requires manage_webhooks permissions.

Raises:

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

Returns:

The webhooks for this channel.

Return type:

List[Webhook]

await create_webhook(*, name, avatar=None, reason=None)

This function is a coroutine.

Creates a webhook for this channel.

Requires manage_webhooks permissions.

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

Parameters:
  • name (str) – The webhook’s name.

  • avatar (Optional[bytes]) – A bytes-like object representing the webhook’s default avatar. This operates similarly to edit().

  • reason (Optional[str]) – The reason for creating this webhook. Shows up in the audit logs.

Raises:
  • HTTPException – Creating the webhook failed.

  • Forbidden – You do not have permissions to create a webhook.

Returns:

The created webhook.

Return type:

Webhook

await follow(*, destination, reason=None)

Follows a channel using a webhook.

Only news channels can be followed.

Note

The webhook returned will not provide a token to do webhook actions, as Discord does not provide it.

Added in version 1.3.

Parameters:
  • destination (TextChannel) – The channel you would like to follow from.

  • reason (Optional[str]) –

    The reason for following the channel. Shows up on the destination guild’s audit log.

    Added in version 1.4.

Raises:
  • HTTPException – Following the channel failed.

  • Forbidden – You do not have the permissions to create a webhook.

Returns:

The created webhook.

Return type:

Webhook

get_partial_message(message_id)

Creates a PartialMessage from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

Added in version 1.6.

Parameters:

message_id (int) – The message ID to create a partial message for.

Returns:

The partial message.

Return type:

PartialMessage

await create_thread(name, auto_archive_duration=None, slowmode_delay=0, private=False, invitable=True, *, reason=None)

This function is a coroutine.

Creates a new thread in this channel.

You must have the create_public_threads, or for private create_private_threads permission to use this.

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

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

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

  • private (bool) – Whether to create a private thread

  • invitable (bool) – For private-threads Whether non-moderators can add new members to the thread, default :obj`True`

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

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

  • ValueError – The name is of invalid 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

property category

The category this channel belongs to.

If there is no category then this is None.

Type:

Optional[CategoryChannel]

property changed_roles

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type:

List[Role]

await create_invite(*, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, reason=None)

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have the create_instant_invite permission to do this.

Parameters:
  • max_age (Optional[int]) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to 0.

  • max_uses (Optional[int]) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to 0.

  • temporary (Optional[bool]) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.

  • unique (Optional[bool]) – Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.

  • target_type (Optional[InviteTargetType]) –

    The type of target for this voice channel invite, if any.

    Added in version 2.0.

  • target_user (Optional[int]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    Added in version 2.0.

  • target_application_id (Optional[int]) –

    The id of the embedded application to open for this invite, required if target_type is InviteTargetType.embeded_application, the application must have the EMBEDDED flag.

    Added in version 2.0.

  • target_event (Optional[GuildScheduledEvent]) –

    The scheduled event object to link to the event. Shortcut to Invite.set_scheduled_event()

    See Invite.set_scheduled_event() for more info on event invite linking.

    Added in version 2.0.

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

Raises:
  • HTTPException – Invite creation failed.

  • NotFound – The channel that was passed is a category or an invalid channel.

Returns:

The invite that was created.

Return type:

Invite

property created_at

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

Parameters:

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

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

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

  • HTTPException – Deleting the channel failed.

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

This can only be used by bot accounts.

Parameters:

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

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

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

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

await invites()

This function is a coroutine.

Returns a list of all active instant invites from this channel.

You must have manage_channels to get this information.

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

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

property jump_url

Returns a URL that allows the client to jump to the referenced channel.

Added in version 2.0.

Type:

str

property mention

The string that allows you to mention the channel.

Type:

str

await move(*, beginning=False, end=False, before=MISSING, after=MISSING, offset=0, category=MISSING, sync_permissions=False, reason=None)

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit() should be used instead.

You must have the manage_channels permission to do this.

Note

Voice channels will always be sorted below text channels. This is a Discord limitation.

Added in version 1.7.

Parameters:
  • beginning (bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (Snowflake) – The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (Snowflake) – The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) – The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[Snowflake]) – The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

  • reason (str) – The reason for the move.

Raises:
  • InvalidArgument – An invalid position was given or a bad mix of arguments were passed.

  • Forbidden – You do not have permissions to move the channel.

  • HTTPException – Moving the channel failed.

property overwrites

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Returns:

The channel’s permission overwrites.

Return type:

Mapping[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

Parameters:

obj (Union[Role, User]) – The role or user denoting whose overwrite to get.

Returns:

The permission overwrites for this object.

Return type:

PermissionOverwrite

property permissions_synced

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

Added in version 1.3.

Type:

bool

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.

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

    Added in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

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

    Added in version 2.0.

Raises:
Returns:

The message that was sent.

Return type:

Message

await set_permissions(target, *, overwrite=MISSING, reason=None, **permissions)

This function is a coroutine.

Sets the channel specific permission overwrites for a target in the channel.

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have the manage_roles permission to use this.

Examples

Setting allow and deny:

await message.channel.set_permissions(message.author, read_messages=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)
Parameters:
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

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

Raises:
  • Forbidden – You do not have permissions to edit channel specific permissions.

  • HTTPException – Editing channel specific permissions failed.

  • NotFound – The role or member being edited is not part of the guild.

  • InvalidArgument – The overwrite parameter invalid or the target type was not Role or Member.

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

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

ThreadChannel

class discord.ThreadChannel

Bases: Messageable, Hashable

Represents a thread in a guild

id

The ID of the thread

Type:

int

type

The type of the thread

Type:

ChannelType

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!')
async for ... in fetch_members(limit=100, after=None)

Returns a ThreadMemberIterator that allows to retrieve the currently joined members of this thread.

Note

This requires the members() intent to be enabled and will also add the members retrieved to members

Examples

Usage

print(f"The thread {channel.name} has the following members:\n")
async for member in thread.fetch_members(limit=200):
    print(member)

Flattening into a list

messages = await thread.fetch_members(limit=123).flatten()
# messages is now a list of ThreadMember...

All parameters are optional.

Parameters:
  • limit (int) – The limit of thread members to retrieve - defaults to 100

  • after (Union[int, datetime.datetime]) – Get thread members after this user ID

Raises:

ClientException – The members intent is not enabled.

Yields:

ThreadMember – A member of this thread

property starter_message

The starter message of this thread if it was started from a message and the message is cached

Type:

Optional[Message]

property owner

Returns the owner(creator) of the thread. Depending on whether the associated guild member is cached, this returns the Member instead of the ThreadMember

Note

If the thread members are not fetched (can be done manually using fetch_members()) and the guild member is not cached, this returns None.

Returns:

The thread owners’ Member if cached, else the respective ThreadMember.

Return type:

Optional[Union[Member, ThreadMember]]

property members

Returns a list with cached members of this thread

Type:

List[Member]

property locked

Whether the threads conversation is locked by a moderator. If so, the thread can only be unarchived by a moderator

Type:

bool

property auto_archive_duration

The duration after which the thread will auto hide from the channel list

Type:

AutoArchiveDuration

property archived

Whether the thread is archived (e.g. not showing in the channel list)

Type:

bool

property invitable

Private threads only: When True only the owner of the thread and members with manage_threads permissions can add new members

Return type:

bool

property archive_time

When the thread’s archive status was last changed, used for calculating recent activity

Type:

Optional[datetime]

property me

The thread member of the bot, or None if he is not a member of the thread.

Type:

Optional[ThreadMember]

property parent_channel

The parent channel of this thread

Type:

Union[TextChannel, ForumChannel]

property category_id

The ID of the threads parent channel category, if any

Type:

Optional[int]

property created_at

An aware timestamp of when the thread was created in UTC.

Note

This timestamp only exists for threads created after 9 January 2022, otherwise returns None.

Type:

Optional[datetime.datetime]

property mention

The string that allows you to mention the thread.

Type:

str

property jump_url

Returns a URL that allows the client to jump to the referenced thread.

Type:

str

get_member(id)

ThreadMember: Returns the thread member with the given ID, or None if he is not a member of the thread.

permissions_for(member)

Handles permission resolution for the current Member.

Note

threads inherit their permissions from their parent channel.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

Parameters:

member (Member) – The member to resolve permissions for.

Returns:

The resolved permissions for the member.

Return type:

Permissions

is_nsfw()

bool: Whether the parent channel of this thread has NSFW enabled.

await join()

This function is a coroutine.

Adds the current user to the thread.

Note

Also requires the thread is not archived.

This will fire a discord.thread_members_update() event.

await leave()

This function is a coroutine.

Removes the current user from the thread.

Note

Also requires the thread is not archived.

This will fire a discord.thread_members_update() event.

await add_member(member)

This function is a coroutine.

Adds another member to the thread.

Note

Requires the ability to send messages in the thread.

Also requires the thread is not archived.

This will fire a thread_members_update event.

Parameters:

member (Union[discord.Member, int]) – The member that should be added to the thread; could be a discord.Member or his id (e.g. an int)

await remove_member(member)

This function is a coroutine.

Removes a member from the thread.

Note

This requires the MANAGE_THREADS permission, or to be the creator of the thread if it is a PRIVATE_THREAD.

Also requires the thread is not archived.

This will fire a thread_members_update event.

Parameters:

member (Union[discord.Member, int]) – The member that should be removed from the thread; could be a discord.Member or his id (e.g. an int)

await delete(*, reason=None)

This function is a coroutine.

Deletes the thread channel.

The bot must have manage_channels permission to use this.

Parameters:

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

Raises:
  • Forbidden – The bot is missing permissions to delete the thread.

  • NotFound – The thread was not found or was already deleted.

  • HTTPException – Deleting the thread failed.

await create_invite(*, reason=None, **fields)

This function is a coroutine.

Creates an instant invite from this thread.

You must have the create_instant_invite permission to do this.

Parameters:
  • max_age (int) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to 0.

  • max_uses (int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to 0.

  • temporary (bool) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.

  • unique (bool) – Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.

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

Raises:

HTTPException – Invite creation failed.

Returns:

The invite that was created.

Return type:

Invite

await invites()

This function is a coroutine.

Returns a list of all active instant invites from this thread.

You must have manage_channels to get this information.

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

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

await edit(*, name=MISSING, archived=MISSING, auto_archive_duration=MISSING, locked=MISSING, invitable=MISSING, slowmode_delay=MISSING, reason=None)

This function is a coroutine.

Edits the thread. In order to unarchive it, you must already be a member of it.

Parameters:
  • name (Optional[str]) – The channel name. Must be 1-100 characters long

  • auto_archive_duration (Optional[AutoArchiveDuration]) – Duration in minutes to automatically archive the thread after recent activity

  • archived (Optional[bool]) – Whether the thread is archived

  • locked (Optional[bool]) – Whether the thread is locked; when a thread is locked, only users with Permissions.manage_threads can unlock it

  • invitable (Optional[bool]) – Whether non-moderators can add other non-moderators to a thread; only available on private threads

  • slowmode_delay (:Optional[int]) – Amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission Permissions.manage_messages, Permissions.manage_thread, or Permissions.manage_channel, are unaffected

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

Raises:
  • InvalidArgument: – The auto_archive_duration is not a valid member of AutoArchiveDuration

  • Forbidden: – The bot missing permissions to edit the thread or the specific field

  • HTTPException: – Editing the thread failed

Returns:

The updated thread on success

Return type:

ThreadChannel

await delete_messages(messages, *, reason=None)

This function is a coroutine.

Deletes a list of messages. This is similar to Message.delete() except it bulk deletes multiple messages.

As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.

You cannot bulk delete more than 100 messages or messages that are older than 14 days old.

You must have the manage_messages permission to use this.

Usable only by bot accounts.

Parameters:
  • messages (Iterable[abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.

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

Raises:
  • ClientException – The number of messages to delete was more than 100.

  • Forbidden – You do not have proper permissions to delete the messages or you’re not using a bot account.

  • NotFound – If single delete, then the message was already deleted.

  • HTTPException – Deleting the messages failed.

await purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)

This function is a coroutine.

Purges a list of messages that meet the criteria given by the predicate check. If a check is not provided then all messages are deleted without discrimination.

You must have the manage_messages permission to delete messages even if they are your own (unless you are a user account). The read_message_history permission is also needed to retrieve message history.

Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.

Examples

Deleting bot’s messages

def is_me(m):
    return m.author == client.user

deleted = await channel.purge(limit=100, check=is_me)
await channel.send('Deleted {} message(s)'.format(len(deleted)))
Parameters:
  • limit (Optional[int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.

  • check (Callable[[Message], bool]) – The function used to check if a message should be deleted. It must take a Message as its sole parameter.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Same as before in history().

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Same as after in history().

  • around (Optional[Union[abc.Snowflake, datetime.datetime]]) – Same as around in history().

  • oldest_first (Optional[bool]) – Same as oldest_first in history().

  • bulk (bool) – If True, use bulk delete. Setting this to False is useful for mass-deleting a bot’s own messages without Permissions.manage_messages. When True, will fall back to single delete if current account is a user bot (now deprecated), or if messages are older than two weeks.

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

Raises:
  • Forbidden – You do not have proper permissions to do the actions required.

  • HTTPException – Purging the messages failed.

Returns:

The list of messages that were deleted.

Return type:

List[Message]

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

This can only be used by bot accounts.

Parameters:

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

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

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

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

await pins()

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the Message objects returned by this method do not contain 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.

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

    Added in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

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

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

ThreadMember

class discord.ThreadMember

Bases: object

Represents a minimal Member that has joined a ThreadChannel or ForumPost

id

The ID of the member

Type:

int

guild

The guild the thread member belongs to

Type:

Guild

joined_at

When the member joined the thread

Type:

datetime.datetime

thread_id

The id of the thread the member belongs to

Type:

int

guild_id

The ID of the guild the thread member belongs to

Type:

int

property as_guild_member

Returns the full guild member for the thread member if cached else None

Type:

Optional[Member]

await send(*args, **kwargs)

A shortcut to Member.send()

permissions_in(channel)

A shorthand method to Member.permissions_in()

Raises:

TypeError – The associated guild member is not cached

property mention

Returns a string the client renders as a mention of the user

VoiceChannel

class discord.VoiceChannel

Bases: VocalGuildChannel, Messageable

Represents a Discord guild voice channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns the channel’s name.

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]

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

Type:

int

icon_emoji

The channel’s icon-emoji, if set.

Type:

Optional[PartialEmoji]

bitrate

The channel’s preferred audio bitrate in bits per second.

Type:

int

user_limit

The channel’s limit for number of members that can be in a voice channel.

Type:

int

rtc_region

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

Added in version 1.7.

Type:

Optional[VoiceRegion]

slowmode_delay

The channel’s slowmode delay in seconds. A value of 0 indicates that slowmode is disabled.

Added in version 2.0.

Type:

int

nsfw

Whether the channel is marked as NSFW.

Added in version 2.0.

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 type

The channel’s Discord type.

Type:

ChannelType

property status

The current channel “status” (0-500 characters) if any.

Type:

Optional[str]

await clone(*, name=None, reason=None)

This function is a coroutine.

Clones this channel. This creates a channel with the same properties as this channel.

You must have the manage_channels permission to do this.

Added in version 1.1.

Parameters:
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this channel name.

  • reason (Optional[str]) – The reason for cloning 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.

Returns:

The channel that was created.

Return type:

abc.GuildChannel

await edit(*, reason=None, **options)

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

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

Parameters:
  • name (str) – The new channel’s name.

  • bitrate (int) – The new channel’s bitrate.

  • user_limit (int) – The new channel’s user limit.

  • position (int) – The new channel’s position.

  • sync_permissions (bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults to False.

  • category (Optional[CategoryChannel]) – The new category for this channel. Can be None to remove the category.

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

  • overwrites (dict) – A dict of target (either a role or a member) to PermissionOverwrite to apply to the channel.

  • rtc_region (Optional[VoiceRegion]) –

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

    Added in version 1.7.

  • slowmode_delay (int) –

    The new slowmode delay for this channel in seconds. A value of 0 disables slowmode.

    Added in version 2.0.

  • nsfw (bool) – Whether the channel is NSFW. This can only be set by guild administrators.

  • icon_emoji (Optional[PartialEmoji]) – The channels new icon-emoji. Note that custom emojis are only allowed when the guild has boost level 2 or higher.

Raises:
  • InvalidArgument – If the permission overwrite information is not in proper form.

  • Forbidden – You do not have permissions to edit the channel.

  • HTTPException – Editing the channel failed.

property category

The category this channel belongs to.

If there is no category then this is None.

Type:

Optional[CategoryChannel]

property changed_roles

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type:

List[Role]

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)

This function is a coroutine.

Connects to voice and creates a VoiceClient to establish your connection to the voice server.

Parameters:
  • timeout (float) – The timeout in seconds to wait for the voice endpoint.

  • reconnect (bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.

  • cls (Type[VoiceProtocol]) – A type that subclasses VoiceProtocol to connect with. Defaults to VoiceClient.

Raises:
Returns:

A voice client that is fully connected to the voice server.

Return type:

VoiceProtocol

await create_invite(*, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, reason=None)

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have the create_instant_invite permission to do this.

Parameters:
  • max_age (Optional[int]) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to 0.

  • max_uses (Optional[int]) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to 0.

  • temporary (Optional[bool]) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.

  • unique (Optional[bool]) – Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.

  • target_type (Optional[InviteTargetType]) –

    The type of target for this voice channel invite, if any.

    Added in version 2.0.

  • target_user (Optional[int]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    Added in version 2.0.

  • target_application_id (Optional[int]) –

    The id of the embedded application to open for this invite, required if target_type is InviteTargetType.embeded_application, the application must have the EMBEDDED flag.

    Added in version 2.0.

  • target_event (Optional[GuildScheduledEvent]) –

    The scheduled event object to link to the event. Shortcut to Invite.set_scheduled_event()

    See Invite.set_scheduled_event() for more info on event invite linking.

    Added in version 2.0.

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

Raises:
  • HTTPException – Invite creation failed.

  • NotFound – The channel that was passed is a category or an invalid channel.

Returns:

The invite that was created.

Return type:

Invite

await create_webhook(*, name, avatar=None, reason=None)

This function is a coroutine.

Creates a webhook for this channel.

Requires manage_webhooks permissions.

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

Parameters:
  • name (str) – The webhook’s name.

  • avatar (Optional[bytes]) – A bytes-like object representing the webhook’s default avatar. This operates similarly to edit().

  • reason (Optional[str]) – The reason for creating this webhook. Shows up in the audit logs.

Raises:
  • HTTPException – Creating the webhook failed.

  • Forbidden – You do not have permissions to create a webhook.

Returns:

The created webhook.

Return type:

Webhook

property created_at

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

Parameters:

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

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

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

  • HTTPException – Deleting the channel failed.

await delete_messages(messages, *, reason=None)

This function is a coroutine.

Deletes a list of messages. This is similar to Message.delete() except it bulk deletes multiple messages.

As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.

You cannot bulk delete more than 100 messages or messages that are older than 14 days old.

You must have the manage_messages permission to use this.

Usable only by bot accounts.

Parameters:
  • messages (Iterable[abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.

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

Raises:
  • ClientException – The number of messages to delete was more than 100.

  • Forbidden – You do not have proper permissions to delete the messages or you’re not using a bot account.

  • NotFound – If single delete, then the message was already deleted.

  • HTTPException – Deleting the messages failed.

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

This can only be used by bot accounts.

Parameters:

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

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

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

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

await invites()

This function is a coroutine.

Returns a list of all active instant invites from this channel.

You must have manage_channels to get this information.

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

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

is_nsfw()

bool: Checks if the channel is NSFW.

property jump_url

Returns a URL that allows the client to jump to the referenced channel.

Added in version 2.0.

Type:

str

property members

Returns all members that are currently inside this voice channel.

Type:

List[Member]

property mention

The string that allows you to mention the channel.

Type:

str

await move(*, beginning=False, end=False, before=MISSING, after=MISSING, offset=0, category=MISSING, sync_permissions=False, reason=None)

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit() should be used instead.

You must have the manage_channels permission to do this.

Note

Voice channels will always be sorted below text channels. This is a Discord limitation.

Added in version 1.7.

Parameters:
  • beginning (bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (Snowflake) – The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (Snowflake) – The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) – The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[Snowflake]) – The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

  • reason (str) – The reason for the move.

Raises:
  • InvalidArgument – An invalid position was given or a bad mix of arguments were passed.

  • Forbidden – You do not have permissions to move the channel.

  • HTTPException – Moving the channel failed.

property overwrites

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Returns:

The channel’s permission overwrites.

Return type:

Mapping[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

Parameters:

obj (Union[Role, User]) – The role or user denoting whose overwrite to get.

Returns:

The permission overwrites for this object.

Return type:

PermissionOverwrite

permissions_for(member, /)

Handles permission resolution for the current Member.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

Parameters:

member (Member) – The member to resolve permissions for.

Returns:

The resolved permissions for the member.

Return type:

Permissions

property permissions_synced

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

Added in version 1.3.

Type:

bool

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 purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)

This function is a coroutine.

Purges a list of messages that meet the criteria given by the predicate check. If a check is not provided then all messages are deleted without discrimination.

You must have the manage_messages permission to delete messages even if they are your own (unless you are a user account). The read_message_history permission is also needed to retrieve message history.

Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.

Examples

Deleting bot’s messages

def is_me(m):
    return m.author == client.user

deleted = await channel.purge(limit=100, check=is_me)
await channel.send('Deleted {} message(s)'.format(len(deleted)))
Parameters:
  • limit (Optional[int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.

  • check (Callable[[Message], bool]) – The function used to check if a message should be deleted. It must take a Message as its sole parameter.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Same as before in history().

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Same as after in history().

  • around (Optional[Union[abc.Snowflake, datetime.datetime]]) – Same as around in history().

  • oldest_first (Optional[bool]) – Same as oldest_first in history().

  • bulk (bool) – If True, use bulk delete. Setting this to False is useful for mass-deleting a bot’s own messages without Permissions.manage_messages. When True, will fall back to single delete if current account is a user bot (now deprecated), or if messages are older than two weeks.

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

Raises:
  • Forbidden – You do not have proper permissions to do the actions required.

  • HTTPException – Purging the messages failed.

Returns:

The list of messages that were deleted.

Return type:

List[Message]

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

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content). If the content is set 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.

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

    Added in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

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

    Added in version 2.0.

Raises:
Returns:

The message that was sent.

Return type:

Message

await set_permissions(target, *, overwrite=MISSING, reason=None, **permissions)

This function is a coroutine.

Sets the channel specific permission overwrites for a target in the channel.

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have the manage_roles permission to use this.

Examples

Setting allow and deny:

await message.channel.set_permissions(message.author, read_messages=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)
Parameters:
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

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

Raises:
  • Forbidden – You do not have permissions to edit channel specific permissions.

  • HTTPException – Editing channel specific permissions failed.

  • NotFound – The role or member being edited is not part of the guild.

  • InvalidArgument – The overwrite parameter invalid or the target type was not Role or Member.

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

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

property voice_states

Returns a mapping of member IDs who have voice states in this channel.

Added in version 1.3.

Note

This function is intentionally low level to replace members when the member cache is unavailable.

Returns:

The mapping of member ID to a voice state.

Return type:

Mapping[int, VoiceState]

await webhooks()

This function is a coroutine.

Gets the list of webhooks from this channel.

Requires manage_webhooks permissions.

Raises:

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

Returns:

The webhooks for this channel.

Return type:

List[Webhook]

StageChannel

class discord.StageChannel

Bases: VocalGuildChannel, Messageable

Represents a Discord guild stage channel.

Added in version 1.7.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns the channel’s name.

name

The channel name.

Type:

str

guild

The guild the channel belongs to.

Type:

Guild

id

The channel ID.

Type:

int

topic

The channel’s topic. None if it isn’t set.

Type:

Optional[str]

icon_emoji

The channel’s icon-emoji, if set.

Type:

Optional[PartialEmoji]

category_id

The category channel ID this channel belongs to, if applicable.

Type:

Optional[int]

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

Type:

int

bitrate

The channel’s preferred audio bitrate in bits per second.

Type:

int

user_limit

The channel’s limit for number of members that can be in a stage channel.

Type:

int

rtc_region

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

Type:

Optional[VoiceRegion]

slowmode_delay

The channel’s slowmode delay in seconds. A value of 0 indicates that slowmode is disabled.

Added in version 2.0.

Type:

int

nsfw

Whether the channel is marked as NSFW.

Added in version 2.0.

Type:

bool

property requesting_to_speak

A list of members who are requesting to speak in the stage channel.

Type:

List[Member]

property type

The channel’s Discord type.

Type:

ChannelType

property has_instance

Whether the channel has an associated stage instance.

Type:

bool

get_instance()

Optional[StageInstance]: Returns the associated stage instance, if any.

await clone(*, name=None, reason=None)

This function is a coroutine.

Clones this channel. This creates a channel with the same properties as this channel.

You must have the manage_channels permission to do this.

Added in version 1.1.

Parameters:
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this channel name.

  • reason (Optional[str]) – The reason for cloning 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.

Returns:

The channel that was created.

Return type:

abc.GuildChannel

await edit(*, reason=None, **options)

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

Parameters:
  • name (str) – The new channel’s name.

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

  • icon_emoji (Optional[PartialEmoji]) – The new channel’s icon-emoji. Note that custom emojis are only allowed when the guild has boost level 2 or higher.

  • position (int) – The new channel’s position.

  • sync_permissions (bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults to False.

  • category (Optional[CategoryChannel]) – The new category for this channel. Can be None to remove the category.

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

  • overwrites (dict) – A dict of target (either a role or a member) to PermissionOverwrite to apply to the channel.

  • rtc_region (Optional[VoiceRegion]) – The new region for the stage channel’s voice communication. A value of None indicates automatic voice region detection.

Raises:
  • InvalidArgument – If the permission overwrite information is not in proper form.

  • Forbidden – You do not have permissions to edit the channel.

  • HTTPException – Editing the channel failed.

await start_instance(topic, send_start_notification=False, *, reason=None)

This function is a coroutine. Starts a new stage instance for this stage channel (e.g. make it go live).

You must have the manage_channels permission to use this.

Parameters:
  • topic (str) – The topic of the stage instance.

  • send_start_notification (bool) –

    Whether to send a notification to everyone in the guild that the stage is live.

    This requires the mention_everyone permission.

  • reason (Optional[str]) – The reason for starting the stage instance. Shows up on the audit log.

Raises:
  • Forbidden – You do not have permissions to start the stage instance.

  • HTTPException – Starting the stage instance failed.

Returns:

The created stage instance.

Return type:

StageInstance

property category

The category this channel belongs to.

If there is no category then this is None.

Type:

Optional[CategoryChannel]

property changed_roles

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type:

List[Role]

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)

This function is a coroutine.

Connects to voice and creates a VoiceClient to establish your connection to the voice server.

Parameters:
  • timeout (float) – The timeout in seconds to wait for the voice endpoint.

  • reconnect (bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.

  • cls (Type[VoiceProtocol]) – A type that subclasses VoiceProtocol to connect with. Defaults to VoiceClient.

Raises:
Returns:

A voice client that is fully connected to the voice server.

Return type:

VoiceProtocol

await create_invite(*, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, reason=None)

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have the create_instant_invite permission to do this.

Parameters:
  • max_age (Optional[int]) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to 0.

  • max_uses (Optional[int]) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to 0.

  • temporary (Optional[bool]) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.

  • unique (Optional[bool]) – Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.

  • target_type (Optional[InviteTargetType]) –

    The type of target for this voice channel invite, if any.

    Added in version 2.0.

  • target_user (Optional[int]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    Added in version 2.0.

  • target_application_id (Optional[int]) –

    The id of the embedded application to open for this invite, required if target_type is InviteTargetType.embeded_application, the application must have the EMBEDDED flag.

    Added in version 2.0.

  • target_event (Optional[GuildScheduledEvent]) –

    The scheduled event object to link to the event. Shortcut to Invite.set_scheduled_event()

    See Invite.set_scheduled_event() for more info on event invite linking.

    Added in version 2.0.

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

Raises:
  • HTTPException – Invite creation failed.

  • NotFound – The channel that was passed is a category or an invalid channel.

Returns:

The invite that was created.

Return type:

Invite

await create_webhook(*, name, avatar=None, reason=None)

This function is a coroutine.

Creates a webhook for this channel.

Requires manage_webhooks permissions.

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

Parameters:
  • name (str) – The webhook’s name.

  • avatar (Optional[bytes]) – A bytes-like object representing the webhook’s default avatar. This operates similarly to edit().

  • reason (Optional[str]) – The reason for creating this webhook. Shows up in the audit logs.

Raises:
  • HTTPException – Creating the webhook failed.

  • Forbidden – You do not have permissions to create a webhook.

Returns:

The created webhook.

Return type:

Webhook

property created_at

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

Parameters:

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

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

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

  • HTTPException – Deleting the channel failed.

await delete_messages(messages, *, reason=None)

This function is a coroutine.

Deletes a list of messages. This is similar to Message.delete() except it bulk deletes multiple messages.

As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.

You cannot bulk delete more than 100 messages or messages that are older than 14 days old.

You must have the manage_messages permission to use this.

Usable only by bot accounts.

Parameters:
  • messages (Iterable[abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.

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

Raises:
  • ClientException – The number of messages to delete was more than 100.

  • Forbidden – You do not have proper permissions to delete the messages or you’re not using a bot account.

  • NotFound – If single delete, then the message was already deleted.

  • HTTPException – Deleting the messages failed.

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

This can only be used by bot accounts.

Parameters:

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

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

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

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

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.

await invites()

This function is a coroutine.

Returns a list of all active instant invites from this channel.

You must have manage_channels to get this information.

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

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

is_nsfw()

bool: Checks if the channel is NSFW.

property jump_url

Returns a URL that allows the client to jump to the referenced channel.

Added in version 2.0.

Type:

str

property members

Returns all members that are currently inside this voice channel.

Type:

List[Member]

property mention

The string that allows you to mention the channel.

Type:

str

await move(*, beginning=False, end=False, before=MISSING, after=MISSING, offset=0, category=MISSING, sync_permissions=False, reason=None)

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit() should be used instead.

You must have the manage_channels permission to do this.

Note

Voice channels will always be sorted below text channels. This is a Discord limitation.

Added in version 1.7.

Parameters:
  • beginning (bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (Snowflake) – The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (Snowflake) – The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) – The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[Snowflake]) – The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

  • reason (str) – The reason for the move.

Raises:
  • InvalidArgument – An invalid position was given or a bad mix of arguments were passed.

  • Forbidden – You do not have permissions to move the channel.

  • HTTPException – Moving the channel failed.

property overwrites

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Returns:

The channel’s permission overwrites.

Return type:

Mapping[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

Parameters:

obj (Union[Role, User]) – The role or user denoting whose overwrite to get.

Returns:

The permission overwrites for this object.

Return type:

PermissionOverwrite

permissions_for(member, /)

Handles permission resolution for the current Member.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

Parameters:

member (Member) – The member to resolve permissions for.

Returns:

The resolved permissions for the member.

Return type:

Permissions

property permissions_synced

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

Added in version 1.3.

Type:

bool

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 purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)

This function is a coroutine.

Purges a list of messages that meet the criteria given by the predicate check. If a check is not provided then all messages are deleted without discrimination.

You must have the manage_messages permission to delete messages even if they are your own (unless you are a user account). The read_message_history permission is also needed to retrieve message history.

Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.

Examples

Deleting bot’s messages

def is_me(m):
    return m.author == client.user

deleted = await channel.purge(limit=100, check=is_me)
await channel.send('Deleted {} message(s)'.format(len(deleted)))
Parameters:
  • limit (Optional[int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.

  • check (Callable[[Message], bool]) – The function used to check if a message should be deleted. It must take a Message as its sole parameter.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Same as before in history().

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Same as after in history().

  • around (Optional[Union[abc.Snowflake, datetime.datetime]]) – Same as around in history().

  • oldest_first (Optional[bool]) – Same as oldest_first in history().

  • bulk (bool) – If True, use bulk delete. Setting this to False is useful for mass-deleting a bot’s own messages without Permissions.manage_messages. When True, will fall back to single delete if current account is a user bot (now deprecated), or if messages are older than two weeks.

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

Raises:
  • Forbidden – You do not have proper permissions to do the actions required.

  • HTTPException – Purging the messages failed.

Returns:

The list of messages that were deleted.

Return type:

List[Message]

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

This function is a coroutine.

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through str(content). If the content is set 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.

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

    Added in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

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

    Added in version 2.0.

Raises:
Returns:

The message that was sent.

Return type:

Message

await set_permissions(target, *, overwrite=MISSING, reason=None, **permissions)

This function is a coroutine.

Sets the channel specific permission overwrites for a target in the channel.

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have the manage_roles permission to use this.

Examples

Setting allow and deny:

await message.channel.set_permissions(message.author, read_messages=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)
Parameters:
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

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

Raises:
  • Forbidden – You do not have permissions to edit channel specific permissions.

  • HTTPException – Editing channel specific permissions failed.

  • NotFound – The role or member being edited is not part of the guild.

  • InvalidArgument – The overwrite parameter invalid or the target type was not Role or Member.

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

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

typing()

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

This is useful for denoting long computations in your bot.

Note

This is both a regular context manager and an async context manager. This means that both with 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 voice_states

Returns a mapping of member IDs who have voice states in this channel.

Added in version 1.3.

Note

This function is intentionally low level to replace members when the member cache is unavailable.

Returns:

The mapping of member ID to a voice state.

Return type:

Mapping[int, VoiceState]

await webhooks()

This function is a coroutine.

Gets the list of webhooks from this channel.

Requires manage_webhooks permissions.

Raises:

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

Returns:

The webhooks for this channel.

Return type:

List[Webhook]

ForumChannel

class discord.ForumChannel

Bases: GuildChannel, Hashable

Represents a forum channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns the channel’s name.

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]

template

The channel’s template. None if it doesn’t exist.

Currently, this field is only available on some selected guilds.

Type:

Optional[str]

icon_emoji

The channel’s icon-emoji, if set.

Type:

Optional[PartialEmoji]

flags

The channel’s flags.

Type:

ChannelFlags

default_reaction_emoji

The default emoji for reacting to a post in this forum

Type:

Optional[PartialEmoji]

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.

Type:

int

nsfw

Whether the channel is marked as NSFW.

Type:

bool

last_post_id

The ID of the last post that was created in this forum, this may not point to an existing or valid post.

Type:

Optional[int]

slowmode_delay

The number of seconds a member must wait between sending messages in posts inside this channel. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode.

Type:

int

post_slowmode_delay

The number of seconds a member must wait between creating new posts.

Type:

int

default_auto_archive_duration

The default duration for which threads in this channel are automatically archived.

Type:

AutoArchiveDuration

default_sort_order

The default sort order for posts in this channel.

Type:

PostSortOrder

default_forum_layout

The default layout for posts in this channel.

Type:

ForumLayout

async for ... in await archived_posts(*, before=None, limit=100)

This function is a coroutine.

Returns an abc.AsyncIterator to retrieve archived posts from this channel.

Parameters:
  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Only fetch posts created before this date or ID.

  • limit (int) – The maximum number of posts to fetch. Defaults to 100.

Raises:
  • Forbidden – The bot lacks permissions to fetch not-joined private posts.

  • HTTPException – Fetching the posts failed.

Returns:

An iterator to retrieve the archived threads.

Return type:

ArchivedThreadIterator

property type

The channel’s type.

Type:

ChannelType

get_post(id)

Optional[ForumPost]: Returns a post in the forum with the given ID. or None when not found.

property posts

A list of all cached posts in the forum.

Type:

List[ForumPost]

get_tag(tag_id)

Optional[ForumTag]: Returns a tag with the given ID in the forum, or None when not found.

property available_tags

A list of all tags available in the forum.

Type:

List[ForumTag]

permissions_for(member, /)

Handles permission resolution for the current Member.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

Parameters:

member (Member) – The member to resolve permissions for.

Returns:

The resolved permissions for the member.

Return type:

Permissions

property members

Returns all members that can see this channel.

Type:

List[Member]

is_nsfw()

bool: Checks if the channel is NSFW.

property last_post

Fetches the last post from this channel in cache.

The post might not be valid or point to an existing post.

Returns:

The last post in this channel or None if not found.

Return type:

Optional[ForumPost]

await edit(*, name=MISSING, topic=MISSING, available_tags=MISSING, tags_required=MISSING, default_post_sort_order=MISSING, default_forum_layout=MISSING, default_reaction_emoji=MISSING, position=MISSING, nsfw=MISSING, sync_permissions=False, category=MISSING, slowmode_delay=MISSING, post_slowmode_delay=MISSING, overwrites=MISSING, icon_emoji=MISSING, reason=None)

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

Parameters:
  • name (str) – The new channel name.

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

  • available_tags (Sequence[ForumTag]) – An iterable of tags to keep as well of new tags. You can use this to reorder the tags.

  • tags_required (bool) – Whether new created post require at least one tag provided on creation

  • default_post_sort_order (Optional[PostSortOrder]) – How the posts in the forum will be sorted for users by default.

  • default_forum_layout (Optional[ForumLayout]) – The default forum layout view used to display posts to users.

  • default_reaction_emoji (Optional[PartialEmoji]) – The default emoji used to react to posts in the forum.

  • position (int) – The new channel’s position.

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

  • sync_permissions (bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults to False.

  • category (Optional[CategoryChannel]) – The new category for this channel. Can be None to remove the category.

  • slowmode_delay (int) – The number of seconds (max. 21600) a member must wait between sending messages in posts inside this channel. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode.

  • post_slowmode_delay (int) – The number of seconds (max. 21600) a member must wait between creating new posts.

  • overwrites (dict) – A dict of target (either a role or a member) to PermissionOverwrite to apply to the channel.

  • icon_emoji (Optional[PartialEmoji]) – The new icon-emoji for the channel. Note that setting custom emojis require the guild to have boost level 2 or higher.

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

Raises:
  • InvalidArgument – If position is less than 0 or greater than the number of channels, or if the permission overwrite information is not in proper form.

  • Forbidden – You do not have permissions to edit the channel.

  • HTTPException – Editing the channel failed.

await clone(*, name=None, reason=None)

This function is a coroutine.

Clones this channel. This creates a channel with the same properties as this channel.

You must have the manage_channels permission to do this.

Added in version 1.1.

Parameters:
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this channel name.

  • reason (Optional[str]) – The reason for cloning 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.

Returns:

The channel that was created.

Return type:

abc.GuildChannel

await webhooks()

This function is a coroutine.

Gets the list of webhooks from this channel.

Requires manage_webhooks permissions.

Raises:

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

Returns:

The webhooks for this channel.

Return type:

List[Webhook]

await create_webhook(*, name, avatar=None, reason=None)

This function is a coroutine.

Creates a webhook for this channel.

Requires manage_webhooks permissions.

Parameters:
  • name (str) – The webhook’s name.

  • avatar (Optional[bytes]) – A bytes-like object representing the webhook’s default avatar. This operates similarly to edit().

  • reason (Optional[str]) – The reason for creating this webhook. Shows up in the audit logs.

Raises:
  • HTTPException – Creating the webhook failed.

  • Forbidden – You do not have permissions to create a webhook.

Returns:

The created webhook.

Return type:

Webhook

await create_post(*, name, tags=None, content=None, embed=None, embeds=None, components=None, file=None, files=None, allowed_mentions=None, suppress_embeds=False, supress_notifications=False, auto_archive_duration=None, slowmode_delay=0, reason=None)

This function is a coroutine.

Creates a new post in this forum. Requires the create_posts permission.

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

  • tags (Optional[List[ForumTag]]) – The list of up to 5 tags that should be added to the post. These tags must be from the parent channel (forum).

  • content (str) – The content of the post starter-message.

  • embed (Optional[Embed]) – A embed of the post starter-message.

  • embeds (List[Embed]) – A list of up to 10 embeds to include in the post starter-message.

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

  • file (Optional[class:File]) – A file to include in the post starter-message.

  • files (List[File]) – A list of files to include in the post starter-message.

  • allowed_mentions (Optional[AllowedMentions]) – The allowed mentions for the post.

  • suppress_embeds (Optional[bool]) – Whether to suppress embeds in the post starter-message.

  • supress_notifications (Optional[bool]) –

    Whether to suppress desktop- & push-notifications for the post starter-message.

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

  • auto_archive_duration (Optional[AutoArchiveDuration]) – The duration after the post will be archived automatically when inactive.

  • slowmode_delay (Optional[int]) – The amount of seconds a user has to wait before sending another message (0-21600)

  • reason (Optional[str]) – The reason for creating this post. Shows up in the audit logs.

Raises:
  • InvalidArgument – The forum requires tags on post creation but no tags where provided, or name is of invalid length, or auto_archive_duration is not of valid type.

  • Forbidden – The bot does not have permissions to create posts in this channel

  • HTTPException – Creating the post failed

property category

The category this channel belongs to.

If there is no category then this is None.

Type:

Optional[CategoryChannel]

property changed_roles

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type:

List[Role]

await create_invite(*, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, reason=None)

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have the create_instant_invite permission to do this.

Parameters:
  • max_age (Optional[int]) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to 0.

  • max_uses (Optional[int]) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to 0.

  • temporary (Optional[bool]) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.

  • unique (Optional[bool]) – Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.

  • target_type (Optional[InviteTargetType]) –

    The type of target for this voice channel invite, if any.

    Added in version 2.0.

  • target_user (Optional[int]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    Added in version 2.0.

  • target_application_id (Optional[int]) –

    The id of the embedded application to open for this invite, required if target_type is InviteTargetType.embeded_application, the application must have the EMBEDDED flag.

    Added in version 2.0.

  • target_event (Optional[GuildScheduledEvent]) –

    The scheduled event object to link to the event. Shortcut to Invite.set_scheduled_event()

    See Invite.set_scheduled_event() for more info on event invite linking.

    Added in version 2.0.

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

Raises:
  • HTTPException – Invite creation failed.

  • NotFound – The channel that was passed is a category or an invalid channel.

Returns:

The invite that was created.

Return type:

Invite

property created_at

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

Parameters:

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

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

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

  • HTTPException – Deleting the channel failed.

await invites()

This function is a coroutine.

Returns a list of all active instant invites from this channel.

You must have manage_channels to get this information.

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

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

property jump_url

Returns a URL that allows the client to jump to the referenced channel.

Added in version 2.0.

Type:

str

property mention

The string that allows you to mention the channel.

Type:

str

await move(*, beginning=False, end=False, before=MISSING, after=MISSING, offset=0, category=MISSING, sync_permissions=False, reason=None)

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit() should be used instead.

You must have the manage_channels permission to do this.

Note

Voice channels will always be sorted below text channels. This is a Discord limitation.

Added in version 1.7.

Parameters:
  • beginning (bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (Snowflake) – The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (Snowflake) – The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) – The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[Snowflake]) – The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

  • reason (str) – The reason for the move.

Raises:
  • InvalidArgument – An invalid position was given or a bad mix of arguments were passed.

  • Forbidden – You do not have permissions to move the channel.

  • HTTPException – Moving the channel failed.

property overwrites

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Returns:

The channel’s permission overwrites.

Return type:

Mapping[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

Parameters:

obj (Union[Role, User]) – The role or user denoting whose overwrite to get.

Returns:

The permission overwrites for this object.

Return type:

PermissionOverwrite

property permissions_synced

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

Added in version 1.3.

Type:

bool

await set_permissions(target, *, overwrite=MISSING, reason=None, **permissions)

This function is a coroutine.

Sets the channel specific permission overwrites for a target in the channel.

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have the manage_roles permission to use this.

Examples

Setting allow and deny:

await message.channel.set_permissions(message.author, read_messages=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)
Parameters:
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

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

Raises:
  • Forbidden – You do not have permissions to edit channel specific permissions.

  • HTTPException – Editing channel specific permissions failed.

  • NotFound – The role or member being edited is not part of the guild.

  • InvalidArgument – The overwrite parameter invalid or the target type was not Role or Member.

ForumPost

class discord.ForumPost

Bases: ThreadChannel

Represents a post in a ForumChannel, this is very similar to a ThreadChannel

Added in version 2.0.

guild

The guild this post belongs to

Type:

Guild

id

The ID of the post

Type:

int

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!')
async for ... in fetch_members(limit=100, after=None)

Returns a ThreadMemberIterator that allows to retrieve the currently joined members of this thread.

Note

This requires the members() intent to be enabled and will also add the members retrieved to members

Examples

Usage

print(f"The thread {channel.name} has the following members:\n")
async for member in thread.fetch_members(limit=200):
    print(member)

Flattening into a list

messages = await thread.fetch_members(limit=123).flatten()
# messages is now a list of ThreadMember...

All parameters are optional.

Parameters:
  • limit (int) – The limit of thread members to retrieve - defaults to 100

  • after (Union[int, datetime.datetime]) – Get thread members after this user ID

Raises:

ClientException – The members intent is not enabled.

Yields:

ThreadMember – A member of this thread

property applied_tags

Returns a list of tags applied to this post.

Type:

List[ForumTag]

await edit_tags(*tags)

This function is a coroutine.

Edits the tags of the post

Parameters:

tags (Tuple[ForumTag]) – Tags to keep as well as new tags to add

Returns:

The updated post

Return type:

ForumPost

await edit(*, name=MISSING, tags=MISSING, pinned=MISSING, auto_archive_duration=MISSING, archived=MISSING, locked=MISSING, slowmode_delay=MISSING, reason=None)

This function is a coroutine.

Edits the post, all parameters are optional

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

  • tags (Sequence[ForumPost]) – Tags to keep as well as new tags to add

  • pinned (bool) –

    Whether the post is pinned to the top of the parent forum.

    Note

    Per forum, only one post can be pinned.

  • auto_archive_duration (AutoArchiveDuration) – The new amount of minutes after that the post will stop showing in the channel list after auto_archive_duration minutes of inactivity.

  • locked (bool) – Whether the post is locked; when a post is locked, only users with :func:~Permissions.manage_threads` permissions can unlock it

  • archived (bool) – Whether the post is archived.

  • slowmode_delay (Optional[str]) – Amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected

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

await add_member(member)

This function is a coroutine.

Adds another member to the thread.

Note

Requires the ability to send messages in the thread.

Also requires the thread is not archived.

This will fire a thread_members_update event.

Parameters:

member (Union[discord.Member, int]) – The member that should be added to the thread; could be a discord.Member or his id (e.g. an int)

property archive_time

When the thread’s archive status was last changed, used for calculating recent activity

Type:

Optional[datetime]

property archived

Whether the thread is archived (e.g. not showing in the channel list)

Type:

bool

property auto_archive_duration

The duration after which the thread will auto hide from the channel list

Type:

AutoArchiveDuration

property category_id

The ID of the threads parent channel category, if any

Type:

Optional[int]

await create_invite(*, reason=None, **fields)

This function is a coroutine.

Creates an instant invite from this thread.

You must have the create_instant_invite permission to do this.

Parameters:
  • max_age (int) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to 0.

  • max_uses (int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to 0.

  • temporary (bool) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.

  • unique (bool) – Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.

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

Raises:

HTTPException – Invite creation failed.

Returns:

The invite that was created.

Return type:

Invite

property created_at

An aware timestamp of when the thread was created in UTC.

Note

This timestamp only exists for threads created after 9 January 2022, otherwise returns None.

Type:

Optional[datetime.datetime]

await delete(*, reason=None)

This function is a coroutine.

Deletes the thread channel.

The bot must have manage_channels permission to use this.

Parameters:

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

Raises:
  • Forbidden – The bot is missing permissions to delete the thread.

  • NotFound – The thread was not found or was already deleted.

  • HTTPException – Deleting the thread failed.

await delete_messages(messages, *, reason=None)

This function is a coroutine.

Deletes a list of messages. This is similar to Message.delete() except it bulk deletes multiple messages.

As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.

You cannot bulk delete more than 100 messages or messages that are older than 14 days old.

You must have the manage_messages permission to use this.

Usable only by bot accounts.

Parameters:
  • messages (Iterable[abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.

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

Raises:
  • ClientException – The number of messages to delete was more than 100.

  • Forbidden – You do not have proper permissions to delete the messages or you’re not using a bot account.

  • NotFound – If single delete, then the message was already deleted.

  • HTTPException – Deleting the messages failed.

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

This can only be used by bot accounts.

Parameters:

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

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

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

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

get_member(id)

ThreadMember: Returns the thread member with the given ID, or None if he is not a member of the thread.

property invitable

Private threads only: When True only the owner of the thread and members with manage_threads permissions can add new members

Return type:

bool

await invites()

This function is a coroutine.

Returns a list of all active instant invites from this thread.

You must have manage_channels to get this information.

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

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

is_nsfw()

bool: Whether the parent channel of this thread has NSFW enabled.

await join()

This function is a coroutine.

Adds the current user to the thread.

Note

Also requires the thread is not archived.

This will fire a discord.thread_members_update() event.

property jump_url

Returns a URL that allows the client to jump to the referenced thread.

Type:

str

await leave()

This function is a coroutine.

Removes the current user from the thread.

Note

Also requires the thread is not archived.

This will fire a discord.thread_members_update() event.

property locked

Whether the threads conversation is locked by a moderator. If so, the thread can only be unarchived by a moderator

Type:

bool

property me

The thread member of the bot, or None if he is not a member of the thread.

Type:

Optional[ThreadMember]

property members

Returns a list with cached members of this thread

Type:

List[Member]

property mention

The string that allows you to mention the thread.

Type:

str

property owner

Returns the owner(creator) of the thread. Depending on whether the associated guild member is cached, this returns the Member instead of the ThreadMember

Note

If the thread members are not fetched (can be done manually using fetch_members()) and the guild member is not cached, this returns None.

Returns:

The thread owners’ Member if cached, else the respective ThreadMember.

Return type:

Optional[Union[Member, ThreadMember]]

property parent_channel

The parent channel of this thread

Type:

Union[TextChannel, ForumChannel]

permissions_for(member)

Handles permission resolution for the current Member.

Note

threads inherit their permissions from their parent channel.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

Parameters:

member (Member) – The member to resolve permissions for.

Returns:

The resolved permissions for the member.

Return type:

Permissions

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 purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)

This function is a coroutine.

Purges a list of messages that meet the criteria given by the predicate check. If a check is not provided then all messages are deleted without discrimination.

You must have the manage_messages permission to delete messages even if they are your own (unless you are a user account). The read_message_history permission is also needed to retrieve message history.

Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.

Examples

Deleting bot’s messages

def is_me(m):
    return m.author == client.user

deleted = await channel.purge(limit=100, check=is_me)
await channel.send('Deleted {} message(s)'.format(len(deleted)))
Parameters:
  • limit (Optional[int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.

  • check (Callable[[Message], bool]) – The function used to check if a message should be deleted. It must take a Message as its sole parameter.

  • before (Optional[Union[abc.Snowflake, datetime.datetime]]) – Same as before in history().

  • after (Optional[Union[abc.Snowflake, datetime.datetime]]) – Same as after in history().

  • around (Optional[Union[abc.Snowflake, datetime.datetime]]) – Same as around in history().

  • oldest_first (Optional[bool]) – Same as oldest_first in history().

  • bulk (bool) – If True, use bulk delete. Setting this to False is useful for mass-deleting a bot’s own messages without Permissions.manage_messages. When True, will fall back to single delete if current account is a user bot (now deprecated), or if messages are older than two weeks.

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

Raises:
  • Forbidden – You do not have proper permissions to do the actions required.

  • HTTPException – Purging the messages failed.

Returns:

The list of messages that were deleted.

Return type:

List[Message]

await remove_member(member)

This function is a coroutine.

Removes a member from the thread.

Note

This requires the MANAGE_THREADS permission, or to be the creator of the thread if it is a PRIVATE_THREAD.

Also requires the thread is not archived.

This will fire a thread_members_update event.

Parameters:

member (Union[discord.Member, int]) – The member that should be removed from the thread; could be a discord.Member or his id (e.g. an int)

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.

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

    Added in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

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

    Added in version 2.0.

Raises:
Returns:

The message that was sent.

Return type:

Message

property starter_message

The starter message of this thread if it was started from a message and the message is cached

Type:

Optional[Message]

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

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

CategoryChannel

class discord.CategoryChannel

Bases: GuildChannel, Hashable

Represents a Discord channel category.

These are useful to group channels to logical compartments.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the category’s hash.

str(x)

Returns the category’s name.

name

The category name.

Type:

str

guild

The guild the category belongs to.

Type:

Guild

id

The category channel ID.

Type:

int

position

The position in the category list. This is a number that starts at 0. e.g. the top category is position 0.

Type:

int

property type

The channel’s Discord type.

Type:

ChannelType

property jump_url

Returns an empty string as you can’t jump to a category.

Type:

str

is_nsfw()

bool: Checks if the category is NSFW.

await clone(*, name=None, reason=None)

This function is a coroutine.

Clones this channel. This creates a channel with the same properties as this channel.

You must have the manage_channels permission to do this.

Added in version 1.1.

Parameters:
  • name (Optional[str]) – The name of the new channel. If not provided, defaults to this channel name.

  • reason (Optional[str]) – The reason for cloning 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.

Returns:

The channel that was created.

Return type:

abc.GuildChannel

await edit(*, reason=None, **options)

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

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

Parameters:
  • name (str) – The new category’s name.

  • position (int) – The new category’s position.

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

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

  • overwrites (dict) – A dict of target (either a role or a member) to PermissionOverwrite to apply to the channel.

Raises:
  • InvalidArgument – If position is less than 0 or greater than the number of categories.

  • Forbidden – You do not have permissions to edit the category.

  • HTTPException – Editing the category failed.

await move(*, beginning=False, end=False, before=MISSING, after=MISSING, offset=0, category=MISSING, sync_permissions=False, reason=None)

This function is a coroutine.

A rich interface to help move a channel relative to other channels.

If exact position movement is required, edit() should be used instead.

You must have the manage_channels permission to do this.

Note

Voice channels will always be sorted below text channels. This is a Discord limitation.

Added in version 1.7.

Parameters:
  • beginning (bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with end, before, and after.

  • end (bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with beginning, before, and after.

  • before (Snowflake) – The channel that should be before our current channel. This is mutually exclusive with beginning, end, and after.

  • after (Snowflake) – The channel that should be after our current channel. This is mutually exclusive with beginning, end, and before.

  • offset (int) – The number of channels to offset the move by. For example, an offset of 2 with beginning=True would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the beginning, end, before, and after parameters.

  • category (Optional[Snowflake]) – The category to move this channel under. If None is given then it moves it out of the category. This parameter is ignored if moving a category channel.

  • sync_permissions (bool) – Whether to sync the permissions with the category (if given).

  • reason (str) – The reason for the move.

Raises:
  • InvalidArgument – An invalid position was given or a bad mix of arguments were passed.

  • Forbidden – You do not have permissions to move the channel.

  • HTTPException – Moving the channel failed.

property channels

Returns the channels that are under this category.

These are sorted by the official Discord UI, which places voice channels below the text channels.

Type:

List[abc.GuildChannel]

property text_channels

Returns the text channels that are under this category.

Type:

List[TextChannel]

property thread_channels

Returns the thread channels that are under this category. Only includes public threads and threads that the authorized bot has joined.

Note

This also includes forum-posts as they are threads too.

Type:

List[ThreadChannel]

property voice_channels

Returns the voice channels that are under this category.

Type:

List[VoiceChannel]

property stage_channels

Returns the voice channels that are under this category.

Added in version 1.7.

Type:

List[StageChannel]

property forum_channels

Returns the forum channels that are under this category.

Type:

List[ForumChannel]

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

This function is a coroutine.

A shortcut method to Guild.create_text_channel() to create a TextChannel in the category.

Returns:

The channel that was just created.

Return type:

TextChannel

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

This function is a coroutine.

A shortcut method to Guild.create_voice_channel() to create a VoiceChannel in the category.

Returns:

The channel that was just created.

Return type:

VoiceChannel

await create_stage_channel(name, *, overwrites=None, reason=None, **options)

This function is a coroutine.

A shortcut method to Guild.create_stage_channel() to create a StageChannel in the category.

Added in version 1.7.

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, position=None, reason=None)

This function is a coroutine.

A shortcut method to Guild.create_forum_channel() to create a ForumChannel in the category.

Returns:

The channel that was just created

Return type:

ForumChannel

property category

The category this channel belongs to.

If there is no category then this is None.

Type:

Optional[CategoryChannel]

property changed_roles

Returns a list of roles that have been overridden from their default values in the roles attribute.

Type:

List[Role]

await create_invite(*, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, reason=None)

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have the create_instant_invite permission to do this.

Parameters:
  • max_age (Optional[int]) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to 0.

  • max_uses (Optional[int]) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to 0.

  • temporary (Optional[bool]) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to False.

  • unique (Optional[bool]) – Indicates if a unique invite URL should be created. Defaults to True. If this is set to False then it will return a previously created invite.

  • target_type (Optional[InviteTargetType]) –

    The type of target for this voice channel invite, if any.

    Added in version 2.0.

  • target_user (Optional[int]) –

    The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.

    Added in version 2.0.

  • target_application_id (Optional[int]) –

    The id of the embedded application to open for this invite, required if target_type is InviteTargetType.embeded_application, the application must have the EMBEDDED flag.

    Added in version 2.0.

  • target_event (Optional[GuildScheduledEvent]) –

    The scheduled event object to link to the event. Shortcut to Invite.set_scheduled_event()

    See Invite.set_scheduled_event() for more info on event invite linking.

    Added in version 2.0.

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

Raises:
  • HTTPException – Invite creation failed.

  • NotFound – The channel that was passed is a category or an invalid channel.

Returns:

The invite that was created.

Return type:

Invite

property created_at

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

Parameters:

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

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

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

  • HTTPException – Deleting the channel failed.

await invites()

This function is a coroutine.

Returns a list of all active instant invites from this channel.

You must have manage_channels to get this information.

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

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

property mention

The string that allows you to mention the channel.

Type:

str

property overwrites

Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a Role or a Member and the value is the overwrite as a PermissionOverwrite.

Returns:

The channel’s permission overwrites.

Return type:

Mapping[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

Returns the channel-specific overwrites for a member or a role.

Parameters:

obj (Union[Role, User]) – The role or user denoting whose overwrite to get.

Returns:

The permission overwrites for this object.

Return type:

PermissionOverwrite

permissions_for(member, /)

Handles permission resolution for the current Member.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

Parameters:

member (Member) – The member to resolve permissions for.

Returns:

The resolved permissions for the member.

Return type:

Permissions

property permissions_synced

Whether or not the permissions for this channel are synced with the category it belongs to.

If there is no category then this is False.

Added in version 1.3.

Type:

bool

await set_permissions(target, *, overwrite=MISSING, reason=None, **permissions)

This function is a coroutine.

Sets the channel specific permission overwrites for a target in the channel.

The target parameter should either be a Member or a Role that belongs to guild.

The overwrite parameter, if given, must either be None or PermissionOverwrite. For convenience, you can pass in keyword arguments denoting Permissions attributes. If this is done, then you cannot mix the keyword arguments with the overwrite parameter.

If the overwrite parameter is None, then the permission overwrites are deleted.

You must have the manage_roles permission to use this.

Examples

Setting allow and deny:

await message.channel.set_permissions(message.author, read_messages=True,
                                                      send_messages=False)

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)
Parameters:
  • target (Union[Member, Role]) – The member or role to overwrite permissions for.

  • overwrite (Optional[PermissionOverwrite]) – The permissions to allow and deny to the target, or None to delete the overwrite.

  • **permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with overwrite.

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

Raises:
  • Forbidden – You do not have permissions to edit channel specific permissions.

  • HTTPException – Editing channel specific permissions failed.

  • NotFound – The role or member being edited is not part of the guild.

  • InvalidArgument – The overwrite parameter invalid or the target type was not Role or Member.

DMChannel

class discord.DMChannel

Bases: Messageable, Hashable

Represents a Discord direct message channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns a string representation of the channel

recipient

The user you are participating with in the direct message channel.

Type:

User

me

The user presenting yourself.

Type:

ClientUser

id

The direct message channel ID.

Type:

int

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 type

The channel’s Discord type.

Type:

ChannelType

property created_at

Returns the direct message channel’s creation time in UTC.

Type:

datetime.datetime

permissions_for(user=None)

Handles permission resolution for a User.

This function is there for compatibility with other channel types.

Actual direct messages do not really have the concept of permissions.

This returns all the Text related permissions set to True except:

Parameters:

user (User) – The user to check permissions for. This parameter is ignored but kept for compatibility.

Returns:

The resolved permissions.

Return type:

Permissions

get_partial_message(message_id)

Creates a PartialMessage from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

Added in version 1.6.

Parameters:

message_id (int) – The message ID to create a partial message for.

Returns:

The partial message.

Return type:

PartialMessage

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

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.

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

    Added in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

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

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

GroupChannel

class discord.GroupChannel

Bases: Messageable, Hashable

Represents a Discord group channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns a string representation of the channel

recipients

The users you are participating with in the group channel.

Type:

List[User]

me

The user presenting yourself.

Type:

ClientUser

id

The group channel ID.

Type:

int

owner

The user that owns the group channel.

Type:

User

icon

The group channel’s icon hash if provided.

Type:

Optional[str]

name

The group channel’s name if provided.

Type:

Optional[str]

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

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

You must have read_message_history permissions to use this.

Examples

Usage

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

Flattening into a list:

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

All parameters are optional.

Parameters:
  • limit (Optional[int]) – The number of messages to retrieve. 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 type

The channel’s Discord type.

Type:

ChannelType

property icon_url

Returns the channel’s icon asset if available.

This is equivalent to calling icon_url_as() with the default parameters (‘webp’ format and a size of 1024).

Type:

Asset

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

Returns an Asset for the icon the channel has.

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

Added in version 2.0.

Parameters:
  • format (str) – The format to attempt to convert the icon to. Defaults to ‘webp’.

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

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

permissions_for(user)

Handles permission resolution for a User.

This function is there for compatibility with other channel types.

Actual direct messages do not really have the concept of permissions.

This returns all the Text related permissions set to True except:

This also checks the kick_members permission if the user is the owner.

Parameters:

user (User) – The user to check permissions for.

Returns:

The resolved permissions for the user.

Return type:

Permissions

await add_recipients(*recipients)

This function is a coroutine.

Adds recipients to this group.

A group can only have a maximum of 10 members. Attempting to add more ends up in an exception. To add a recipient to the group, you must have a relationship with the user of type RelationshipType.friend.

Deprecated since version 1.7.

Parameters:

*recipients (User) – An argument list of users to add to this group.

Raises:

HTTPException – Adding a recipient to this group failed.

await remove_recipients(*recipients)

This function is a coroutine.

Removes recipients from this group.

Deprecated since version 1.7.

Parameters:

*recipients (User) – An argument list of users to remove from this group.

Raises:

HTTPException – Removing a recipient from this group failed.

await edit(**fields)

This function is a coroutine.

Edits the group.

Deprecated since version 1.7.

Parameters:
  • name (Optional[str]) – The new name to change the group to. Could be None to remove the name.

  • icon (Optional[bytes]) – A bytes-like object representing the new icon. Could be None to remove the icon.

Raises:

HTTPException – Editing the group failed.

await leave()

This function is a coroutine.

Leave the group.

If you are the only one in the group, this deletes it as well.

Raises:

HTTPException – Leaving the group failed.

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

This can only be used by bot accounts.

Parameters:

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

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

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

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

await pins()

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the Message objects returned by this method do not contain 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.

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

    Added in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

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

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

PartialInviteGuild

class discord.PartialInviteGuild

Bases: object

Represents a “partial” invite guild.

This model will be given when the user is not part of the guild the Invite resolves to.

x == y

Checks if two partial guilds are the same.

x != y

Checks if two partial guilds are not the same.

hash(x)

Return the partial guild’s hash.

str(x)

Returns the partial guild’s name.

name

The partial guild’s name.

Type:

str

id

The partial guild’s ID.

Type:

int

verification_level

The partial guild’s verification level.

Type:

VerificationLevel

features

A list of features the guild has. See Guild.features for more information.

Type:

List[str]

icon

The partial guild’s icon.

Type:

Optional[str]

banner

The partial guild’s banner.

Type:

Optional[str]

splash

The partial guild’s invite splash.

Type:

Optional[str]

description

The partial guild’s description.

Type:

Optional[str]

premium_subscription_count

The partial guild’s “boost” count.

Type:

int

property created_at

Returns the guild’s creation time in UTC.

Type:

datetime.datetime

property icon_url

Returns the guild’s icon asset.

Type:

Asset

is_icon_animated()

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

Added in version 1.4.

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

The same operation as Guild.icon_url_as().

Returns:

The resulting CDN asset.

Return type:

Asset

property banner_url

Returns the guild’s banner asset.

Type:

Asset

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

The same operation as Guild.banner_url_as().

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)

The same operation as Guild.splash_url_as().

Returns:

The resulting CDN asset.

Return type:

Asset

PartialInviteChannel

class discord.PartialInviteChannel

Bases: object

Represents a “partial” invite channel.

This model will be given when the user is not part of the guild the Invite resolves to.

x == y

Checks if two partial channels are the same.

x != y

Checks if two partial channels are not the same.

hash(x)

Return the partial channel’s hash.

str(x)

Returns the partial channel’s name.

name

The partial channel’s name.

Type:

str

id

The partial channel’s ID.

Type:

int

type

The partial channel’s type.

Type:

ChannelType

property mention

The string that allows you to mention the channel.

Type:

str

property created_at

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

Invite

class discord.Invite

Bases: Hashable

Represents a Discord Guild or abc.GuildChannel invite.

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

x == y

Checks if two invites are equal.

x != y

Checks if two invites are not equal.

hash(x)

Returns the invite hash.

str(x)

Returns the invite URL.

The following table illustrates what methods will obtain the attributes:

If it’s not in the table above then it is available by all methods.

max_age

How long the before the invite expires in seconds. A value of 0 indicates that it doesn’t expire.

Type:

int

code

The URL fragment used for the invite.

Type:

str

guild

The guild the invite is for. Can be None if it’s from a group direct message.

Type:

Optional[Union[Guild, Object, PartialInviteGuild]]

revoked

Indicates if the invite has been revoked.

Type:

bool

created_at

A datetime object denoting the time the invite was created.

Type:

datetime.datetime

temporary

Indicates that the invite grants temporary membership. If True, members who joined via this invite will be kicked upon disconnect.

Type:

bool

uses

How many times the invite has been used.

Type:

int

max_uses

How many times the invite can be used. A value of 0 indicates that it has unlimited uses.

Type:

int

inviter

The user who created the invite.

Type:

User

approximate_member_count

The approximate number of members in the guild.

Type:

Optional[int]

approximate_presence_count

The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded.

Type:

Optional[int]

scheduled_event

The scheduled event attached to this invite link, if any.

Type:

Optional[GuildScheduledEvent]

channel

The channel the invite is for.

Type:

Union[abc.GuildChannel, Object, PartialInviteChannel]

property id

Returns the proper code portion of the invite.

Type:

str

property url

A property that retrieves the invite URL.

Type:

str

await delete(*, reason=None)

This function is a coroutine.

Revokes the instant invite.

You must have the manage_channels permission to do this.

Parameters:

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

Raises:
  • Forbidden – You do not have permissions to revoke invites.

  • NotFound – The invite is invalid or expired.

  • HTTPException – Revoking the invite failed.

set_scheduled_event(event)

Links the given scheduled event to this invite.

Note

Scheduled events aren’t actually associated with invites on the API. Any guild channel invite can have an event attached to it. Using abc.GuildChannel.create_invite(), Client.fetch_invite(), or this method, you can link scheduled events.

Added in version 2.0.

Parameters:

event (ScheduledEvent) – The scheduled event object to link.

Template

class discord.Template

Bases: object

Represents a Discord template.

Added in version 1.4.

code

The template code.

Type:

str

uses

How many times the template has been used.

Type:

int

name

The name of the template.

Type:

str

description

The description of the template.

Type:

str

creator

The creator of the template.

Type:

User

created_at

When the template was created.

Type:

datetime.datetime

updated_at

When the template was last updated (referred to as “last synced” in the client).

Type:

datetime.datetime

source_guild

The source guild.

Type:

Guild

await create_guild(name, region=None, icon=None)

This function is a coroutine.

Creates a Guild using the template.

Bot accounts in more than 10 guilds are not allowed to create guilds.

Parameters:
Raises:
Returns:

The guild created. This is not the same guild that is added to cache.

Return type:

Guild

await sync()

This function is a coroutine.

Sync the template to the guild’s current state.

You must have the manage_guild permission in the source guild to do this.

Added in version 1.7.

Raises:
  • HTTPException – Editing the template failed.

  • Forbidden – You don’t have permissions to edit the template.

  • NotFound – This template does not exist.

await edit(**kwargs)

This function is a coroutine.

Edit the template metadata.

You must have the manage_guild permission in the source guild to do this.

Added in version 1.7.

Parameters:
  • name (Optional[str]) – The template’s new name.

  • description (Optional[str]) – The template’s description.

Raises:
  • HTTPException – Editing the template failed.

  • Forbidden – You don’t have permissions to edit the template.

  • NotFound – This template does not exist.

await delete()

This function is a coroutine.

Delete the template.

You must have the manage_guild permission in the source guild to do this.

Added in version 1.7.

Raises:
  • HTTPException – Editing the template failed.

  • Forbidden – You don’t have permissions to edit the template.

  • NotFound – This template does not exist.

WidgetChannel

class discord.WidgetChannel

Bases: object

Represents a “partial” widget channel.

x == y

Checks if two partial channels are the same.

x != y

Checks if two partial channels are not the same.

hash(x)

Return the partial channel’s hash.

str(x)

Returns the partial channel’s name.

id

The channel’s ID.

Type:

int

name

The channel’s name.

Type:

str

position

The channel’s position

Type:

int

property mention

The string that allows you to mention the channel.

Type:

str

property created_at

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

WidgetMember

class discord.WidgetMember

Bases: BaseUser

Represents a “partial” member of the widget’s guild.

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

x == y

Checks if two widget members are the same.

x != y

Checks if two widget members are not the same.

hash(x)

Return the widget member’s hash.

str(x)

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

Note

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

id

The member’s ID.

Type:

int

username

The member’s username.

Type:

str

global_name

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

Added in version 2.0.

Type:

Optional[str]

discriminator

The member’s discriminator.

Important

This will be removed in a future API version. Read more about it here.

Type:

str

bot

Whether the member is a bot.

Type:

bool

status

The member’s status.

Type:

Status

nick

The member’s nickname.

Type:

Optional[str]

avatar

The member’s avatar hash.

Type:

Optional[str]

activity

The member’s activity.

Type:

Optional[Union[BaseActivity, Spotify]]

deafened

Whether the member is currently deafened.

Type:

Optional[bool]

muted

Whether the member is currently muted.

Type:

Optional[bool]

suppress

Whether the member is currently being suppressed.

Type:

Optional[bool]

connected_channel

Which channel the member is connected to.

Type:

Optional[VoiceChannel]

property display_name

Returns the member’s display name.

Type:

str

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

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

Widget

class discord.Widget

Bases: object

Represents a Guild widget.

x == y

Checks if two widgets are the same.

x != y

Checks if two widgets are not the same.

str(x)

Returns the widget’s JSON URL.

id

The guild’s ID.

Type:

int

name

The guild’s name.

Type:

str

channels

The accessible voice channels in the guild.

Type:

Optional[List[WidgetChannel]]

members

The online members in the server. Offline members do not appear in the widget.

Note

Due to a Discord limitation, if this data is available the users will be “anonymized” with linear IDs and discriminator information being incorrect. Likewise, the number of members retrieved is capped.

Type:

Optional[List[Member]]

property created_at

Returns the member’s creation time in UTC.

Type:

datetime.datetime

property json_url

The JSON URL of the widget.

Type:

str

property invite_url

The invite URL for the guild, if available.

Type:

Optional[str]

await fetch_invite(*, with_counts=True)

This function is a coroutine.

Retrieves an Invite from a invite URL or ID. This is the same as Client.fetch_invite(); the invite code is abstracted away.

Parameters:

with_counts (bool) – Whether to include count information in the invite. This fills the Invite.approximate_member_count and Invite.approximate_presence_count fields.

Returns:

The invite from the URL/ID.

Return type:

Invite

StickerPack

class discord.StickerPack

Bases: Hashable

Represents a pack of build-in stickers

name

The name of the sticker pack.

Type:

str

id

The id of the sticker pack.

Type:

int

description

The description of the sticker pack.

Type:

str

sku_id

The id of the pack’s SKU.

Type:

int

banner_asset_id

The id of the sticker pack’s banner image.

Type:

int

cover_sticker_id

The id of a sticker in the pack which is shown in the client as the pack’s icon.

Type:

Optional[int]

property stickers

The stickers of the pack

Type:

Tuple[Sticker]

property banner_url

Returns an Asset for the sticker pack’s banner.

Returns:

The resulting CDN asset.

Return type:

Asset

banner_url_as(format='png', size=1024)

Returns an Asset for the sticker pack’s banner.

The size must be a power of 2 between 16 and 4096.

Returns:

The resulting CDN asset.

Return type:

Asset

property cover_sticker

Returns the sticker in the pack which is shown in the client as the pack’s icon.

Type:

Sticker

get_sticker(id)

Returns a sticker of the pack with the given id or None if not found.

Parameters:

id (int) – The id of the sticker to get

Returns:

The sticker or None if not found.

Return type:

Optional[Sticker]

Sticker

class discord.Sticker

Bases: Hashable

Represents a sticker.

Added in version 1.6.

str(x)

Returns the name of the sticker.

x == y

Checks if the sticker is equal to another sticker.

x != y

Checks if the sticker is not equal to another sticker.

name

The sticker’s name.

Type:

str

id

The id of the sticker.

Type:

int

description

The description of the sticker.

Type:

str

pack_id

The id of the sticker’s pack.

Type:

int

format

The format for the sticker’s image.

Type:

StickerType

tags

A list of tags for the sticker.

Type:

List[str]

pack

The pack the sticker belongs to. Could be None even if Sticker.pack_id is present.

Type:

Optional[StickerPack]

sort_value

The sticker’s sort order within its Sticker.pack.

Type:

int

property created_at

Returns the sticker’s creation time in UTC as a naive datetime.

Type:

datetime.datetime

property image_url

Returns an Asset for the sticker’s image.

Note

This will return None if the format is StickerType.lottie.

Returns:

The resulting CDN asset.

Return type:

Optional[Asset]

image_url_as()

Optionally returns an Asset for the sticker’s image.

The size must be a power of 2 between 16 and 4096.

Note

This will return None if the format is StickerType.lottie.

Returns:

The resulting CDN asset or None.

Return type:

Optional[Asset]

class discord.GuildSticker

Bases: Sticker

Represents a “custom” sticker in a guild

name

The sticker’s name.

Type:

str

id

The id of the sticker.

Type:

int

description

The description of the sticker.

Type:

str

format

The format for the sticker’s image.

Type:

StickerType

tags

A list of tags for the sticker.

Type:

List[str]

guild_id

The id of the guild wich this sticker belongs to.

Type:

int

available

Whether this guild sticker can be used, may be False due to loss of Server Boosts

Type:

bool

user

The user that uploaded the guild sticker

Type:

User

property guild

The guild the sticker belongs to

Type:

Guild

await edit(*, reason=None, **fields)

This function is a coroutine.

Modify the sticker.

Requires the MANAGE_EMOJIS_AND_STICKERS permission.

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

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

  • tags (Union[str, List[str]]) – The autocomplete/suggestion tags for the sticker. A string in which the individual tags are separated by , or a list of tags; (max 200 characters).

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

Raises:
  • discord.Forbidden: – You don’t have the required permission to edit the sticker.

  • discord.HTTPException: – Editing the sticker failed.

  • ValueError: – Any of name, description or tags is invalid.

Returns:

The updated sticker on success.

Return type:

discord.GuildSticker

property created_at

Returns the sticker’s creation time in UTC as a naive datetime.

Type:

datetime.datetime

await delete(*, reason)

This function is a coroutine.

Delete the sticker.

Requires the MANAGE_EMOJIS_AND_STICKERS permission.

Parameters:

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

Raises:
  • discord.Forbidden: – You don’t have the required permissions to delete the sticker.

  • discord.HTTPException: – Deleting the sticker failed.

Returns:

The sticker that was deleted.

Return type:

discord.GuildSticker

property image_url

Returns an Asset for the sticker’s image.

Note

This will return None if the format is StickerType.lottie.

Returns:

The resulting CDN asset.

Return type:

Optional[Asset]

image_url_as()

Optionally returns an Asset for the sticker’s image.

The size must be a power of 2 between 16 and 4096.

Note

This will return None if the format is StickerType.lottie.

Returns:

The resulting CDN asset or None.

Return type:

Optional[Asset]

VoiceRegionInfo

class discord.VoiceRegionInfo

Bases: object

A class containing info about a specific voice region.

These can be retrieved via fetch_voice_regions().

Added in version 2.0.

id

The unique ID of the region.

Type:

str

name

The name of the region.

Type:

str

vip

Indicates if this is a VIP-only server.

Type:

bool

optimal

True for a single server that is closest to the current user’s client

Type:

bool

deprecated

Indicates if this is a deprecated voice region (avoid switching to these).

Type:

bool

custom

Indicates if this is a custom voice region (used for events/etc).

Type:

bool

.. container:: operations
x == y
Whether two voice regions are equal.
x != y
Whether two voice regions are not equal.
x > y
Whether a voice region is optimal over another.
x < y
Whether a voice region is not optimal over another.
str(x)
Returns the id of the region.
repr(x)
Returns a representation of the region.

RawMessageDeleteEvent

class discord.RawMessageDeleteEvent

Bases: _RawReprMixin

Represents the event payload for a on_raw_message_delete() event.

channel_id

The channel ID where the deletion took place.

Type:

int

guild_id

The guild ID where the deletion took place, if applicable.

Type:

Optional[int]

message_id

The message ID that got deleted.

Type:

int

cached_message

The cached message, if found in the internal message cache.

Type:

Optional[Message]

RawBulkMessageDeleteEvent

class discord.RawBulkMessageDeleteEvent

Bases: _RawReprMixin

Represents the event payload for a on_raw_bulk_message_delete() event.

message_ids

A set of the message IDs that were deleted.

Type:

Set[int]

channel_id

The channel ID where the message got deleted.

Type:

int

guild_id

The guild ID where the message got deleted, if applicable.

Type:

Optional[int]

cached_messages

The cached messages, if found in the internal message cache.

Type:

List[Message]

RawMessageUpdateEvent

class discord.RawMessageUpdateEvent

Bases: _RawReprMixin

Represents the payload for a on_raw_message_edit() event.

message_id

The message ID that got updated.

Type:

int

channel_id

The channel ID where the update took place.

Added in version 1.3.

Type:

int

guild_id

The guild ID where the message got updated, if applicable.

Added in version 1.7.

Type:

Optional[int]

data

The raw data given by the gateway

Type:

dict

cached_message

The cached message, if found in the internal message cache. Represents the message before it is modified by the data in RawMessageUpdateEvent.data.

Type:

Optional[Message]

RawReactionActionEvent

class discord.RawReactionActionEvent

Bases: _RawReprMixin

Represents the payload for a on_raw_reaction_add() or on_raw_reaction_remove() event.

message_id

The message ID that got or lost a reaction.

Type:

int

user_id

The user ID who added the reaction or whose reaction was removed.

Type:

int

channel_id

The channel ID where the reaction got added or removed.

Type:

int

guild_id

The guild ID where the reaction got added or removed, if applicable.

Type:

Optional[int]

emoji

The custom or unicode emoji being used.

Type:

PartialEmoji

member

The member who added the reaction. Only available if event_type is REACTION_ADD and the reaction is inside a guild.

Added in version 1.3.

Type:

Optional[Member]

event_type

The event type that triggered this action. Can be REACTION_ADD for reaction addition or REACTION_REMOVE for reaction removal.

Added in version 1.3.

Type:

str

property type

The type of reaction; e.g. normal or burst.

Added in version 2.0.

Type:

ReactionType

RawReactionClearEvent

class discord.RawReactionClearEvent

Bases: _RawReprMixin

Represents the payload for a on_raw_reaction_clear() event.

message_id

The message ID that got its reactions cleared.

Type:

int

channel_id

The channel ID where the reactions got cleared.

Type:

int

guild_id

The guild ID where the reactions got cleared.

Type:

Optional[int]

RawReactionClearEmojiEvent

class discord.RawReactionClearEmojiEvent

Bases: _RawReprMixin

Represents the payload for a on_raw_reaction_clear_emoji() event.

Added in version 1.3.

message_id

The message ID that got its reactions cleared.

Type:

int

channel_id

The channel ID where the reactions got cleared.

Type:

int

guild_id

The guild ID where the reactions got cleared.

Type:

Optional[int]

emoji

The custom or unicode emoji being removed.

Type:

PartialEmoji

VoiceChannelEffectSendEvent

class discord.VoiceChannelEffectSendEvent

Bases: _RawReprMixin

Represents the payload for an on_voice_channel_effect_send() event.

Added in version 2.0.

guild_id

The guild ID where the effect is being sent.

Type:

int

channel_id

The channel ID where the effect is being sent.

Type:

int

user_id

The user ID who sent the effect.

Type:

int

emoji

The emoji used when this is an emoji effect or the emoji associated to the sound.

Type:

Optional[PartialEmoji]

sound_id

The sound ID of the soundboard sound used, if any.

Type:

Optional[int]

sound_volume

The volume of the soundboard sound used, if any.

Type:

Optional[float]

property type

The type of effect being sent. Can be emoji or sound.

Type:

str