Discord Models

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

Опасно

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.

Примечание

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

Attributes
class discord.Asset(state, *, url, key, animated=False)[исходный код]

Represents a CDN asset on Discord.

str(x)

Returns the URL of the CDN asset.

len(x)

Returns the length of the CDN asset’s URL.

x == y

Checks if the asset is equal to another asset.

x != y

Checks if the asset is not equal to another asset.

hash(x)

Returns the asset’s url’s hash.

This is equivalent to hash(url).

Параметры:
property url: str

Returns the underlying URL of the asset.

property key: str

Returns the identifying key of the asset.

is_animated()[исходный код]

Returns whether the asset is animated.

Тип результата:

bool

replace(*, size=..., format=..., static_format=...)[исходный код]

Returns a new asset with the passed components replaced.

Параметры:
  • size (int) – The new size of the asset.

  • format (Literal['webp', 'jpeg', 'jpg', 'png', 'gif']) – The new format to change it to. Must be either „webp“, „jpeg“, „jpg“, „png“, or „gif“ if it’s animated.

  • static_format (Literal['webp', 'jpeg', 'jpg', 'png']) – The new format to change it to if the asset isn’t animated. Must be either „webp“, „jpeg“, „jpg“, or „png“.

Результат:

The newly updated asset.

Тип результата:

Asset

Исключение:

InvalidArgument – An invalid size or format was passed.

with_size(size, /)[исходный код]

Returns a new asset with the specified size.

Параметры:

size (int) – The new size of the asset.

Результат:

The new updated asset.

Тип результата:

Asset

Исключение:

InvalidArgument – The asset had an invalid size.

with_format(format, /)[исходный код]

Returns a new asset with the specified format.

Параметры:

format (Literal['webp', 'jpeg', 'jpg', 'png', 'gif']) – The new format of the asset.

Результат:

The new updated asset.

Тип результата:

Asset

Исключение:

InvalidArgument – The asset has an invalid format.

with_static_format(format, /)[исходный код]

Returns a new asset with the specified static format.

This only changes the format if the underlying asset is not animated. Otherwise, the asset is not changed.

Параметры:

format (Literal['webp', 'jpeg', 'jpg', 'png']) – The new static format of the asset.

Результат:

The new updated asset.

Тип результата:

Asset

Исключение:

InvalidArgument – The asset had an invalid format.

await read()

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

Результат:

The content of the asset.

Тип результата:

bytes

Исключение:
await save(fp, *, seek_begin=True)

This function is a coroutine.

Saves this asset into a file-like object.

Параметры:
  • fp (str | bytes | PathLike | BufferedIOBase) – 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.

Результат:

The number of bytes written.

Тип результата:

int

Исключение:
class discord.Spotify[исходный код]

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: ActivityType

Returns the activity’s type. This is for compatibility with Activity.

It always returns ActivityType.listening.

property created_at: datetime | None

When the user started listening in UTC.

Добавлено в версии 1.3.

property colour: Colour

Returns the Spotify integration colour, as a Colour.

There is an alias for this named color

property color: Colour

Returns the Spotify integration colour, as a Colour.

There is an alias for this named colour

property name: str

The activity’s name. This will always return «Spotify».

property title: str

The title of the song being played.

property artists: list[str]

The artists of the song being played.

property artist: str

The artist of the song being played.

This does not attempt to split the artist information into multiple artists. Useful if there’s only a single artist.

property album: str

The album that the song being played belongs to.

property album_cover_url: str

The album cover image URL from Spotify’s CDN.

property track_id: str

The track ID used by Spotify to identify this song.

property track_url: str

The track URL to listen on Spotify.

Добавлено в версии 2.0.

property start: datetime

When the user started playing this song in UTC.

property end: datetime

When the user will stop playing this song in UTC.

property duration: timedelta

The duration of the song being played.

property party_id: str

The party ID of the listening party.

class discord.VoiceState(*, data, channel=None)[исходный код]

Represents a Discord user’s voice state.

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.

Добавлено в версии 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.

Добавлено в версии 1.7.

Type:

bool

requested_to_speak_at

An aware datetime object that specifies the date and time in UTC that the member requested to speak. It will be None if they are not requesting to speak anymore or have been accepted to speak.

Only applicable to stage channels.

Добавлено в версии 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]]

Параметры:
  • data (VoiceState)

  • channel (VocalGuildChannel | None)

Attributes
class discord.PartialMessageable(state, id, type=None)[исходный код]

Represents a partial messageable to aid with working messageable channels when only a channel ID are present.

The only way to construct this class is through Client.get_partial_messageable().

Note that this class is trimmed down and has no rich attributes.

Добавлено в версии 2.0.

x == y

Checks if two partial messageables are equal.

x != y

Checks if two partial messageables are not equal.

hash(x)

Returns the partial messageable’s hash.

id

The channel ID associated with this partial messageable.

Type:

int

type

The channel type associated with this partial messageable, if given.

Type:

Optional[ChannelType]

Параметры:
  • state (ConnectionState)

  • id (int)

  • type (ChannelType | None)

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.

Параметры:

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

Результат:

The partial message.

Тип результата:

PartialMessage

can_send(*objects)

Returns a bool indicating whether you have the permissions to send the object(s).

Результат:

Indicates whether you have the permissions to send the object(s).

Тип результата:

bool

Исключение:

TypeError – An invalid type has been passed.

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

Параметры:

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

Результат:

The message asked for.

Тип результата:

Message

Исключение:
  • NotFound – The specified message was not found.

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

  • HTTPException – Retrieving the message failed.

history(*, limit=100, before=None, after=None, around=None, oldest_first=None)

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

You must have read_message_history permissions to use this.

Параметры:
  • limit (int | None) – 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 (Snowflake | datetime | None) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Snowflake | datetime | None) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.

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

Yields:

Message – The message with the message data parsed.

Исключение:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Тип результата:

HistoryIterator

Примеры

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.

pins(*, limit=50, before=None)

Returns a MessagePinIterator that enables receiving the destination’s pinned messages.

You must have read_message_history permissions to use this.

Предупреждение

Starting from version 3.0, await channel.pins() will no longer return a list of Message. See examples below for new usage instead.

Параметры:
  • limit (int | None) – The number of pinned messages to retrieve. If None, retrieves every pinned message in the channel.

  • before (Snowflake | datetime | None) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

Yields:

MessagePin – The pinned message.

Исключение:
  • Forbidden – You do not have permissions to get pinned messages.

  • HTTPException – The request to get pinned messages failed.

Тип результата:

MessagePinIterator

Примеры

Usage

counter = 0
async for pin in channel.pins(limit=250):
    if pin.message.author == client.user:
        counter += 1

Flattening into a list:

pins = await channel.pins(limit=None).flatten()
# pins is now a list of MessagePin...

All parameters are optional.

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, suppress_embeds=None, silent=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Параметры:
  • content (Optional[str]) – The content of the message to send.

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

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

  • file (File) – The file to upload.

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

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

  • enforce_nonce (Optional[bool]) –

    Whether nonce is enforced to be validated.

    Добавлено в версии 2.5.

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

  • allowed_mentions (AllowedMentions) –

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

    Добавлено в версии 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message being replied to or forwarded. This can be created using to_reference(). When replying, 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.

    Добавлено в версии 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    Добавлено в версии 1.6.

  • view (discord.ui.BaseView) – A Discord UI View to add to the message.

  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    Добавлено в версии 2.0.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    Добавлено в версии 2.0.

  • suppress (bool) –

    Whether to suppress embeds for the message.

    Устарело, начиная с версии 2.8.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message.

    Добавлено в версии 2.8.

  • silent (bool) –

    Whether to suppress push and desktop notifications for the message.

    Добавлено в версии 2.4.

  • poll (Poll) –

    The poll to send.

    Добавлено в версии 2.6.

Результат:

The message that was sent.

Тип результата:

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.

Тип результата:

None

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.

Примечание

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():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
Тип результата:

Typing

Users

class discord.ClientUser(*, state, data)[исходный код]

Represents your Discord user.

x == y

Checks if two users are equal.

x != y

Checks if two users are not equal.

hash(x)

Return the user’s hash.

str(x)

Returns the user’s name with discriminator or global_name.

name

The user’s username.

Type:

str

id

The user’s unique ID.

Type:

int

discriminator

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

Примечание

If the user has migrated to the new username system, this will always be 0.

Type:

str

global_name

The user’s global name.

Добавлено в версии 2.5.

Type:

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

Добавлено в версии 1.3.

Type:

bool

verified

Specifies if the user’s email is verified.

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

Параметры:
  • state (ConnectionState)

  • data (User)

await edit(*, username=..., avatar=..., banner=...)[исходный код]

This function is a coroutine.

Edits the current profile of the client.

Примечание

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

The only image formats supported for uploading are JPEG, PNG, and GIF.

Изменено в версии 2.0: The edit is no longer in-place, instead the newly edited client user is returned.

Изменено в версии 2.6: The banner keyword-only parameter was added.

Параметры:
  • username (str) – The new username you wish to change to.

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

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

Результат:

The newly edited client user.

Тип результата:

ClientUser

Исключение:
property accent_color: Colour | None

Returns the user’s accent color, if applicable.

There is an alias for this named accent_colour.

Добавлено в версии 2.0.

Примечание

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

property accent_colour: Colour | None

Returns the user’s accent colour, if applicable.

There is an alias for this named accent_color.

Добавлено в версии 2.0.

Примечание

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

property avatar: Asset | None

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, None is returned. If you want the avatar that a user has displayed, consider display_avatar.

property avatar_decoration: Asset | None

Returns the user’s avatar decoration, if available.

Добавлено в версии 2.5.

property banner: Asset | None

Returns the user’s banner asset, if available.

Добавлено в версии 2.0.

Примечание

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

property collectibles: Collectibles | None

Returns the user’s equipped collectibles.

Добавлено в версии 2.8.

property color: Colour

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

There is an alias for this named colour.

property colour: Colour

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

There is an alias for this named color.

property created_at: datetime

Returns the user’s creation time in UTC.

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

property default_avatar: Asset

Returns the default avatar for a given user. This is calculated by the user’s ID if they’re on the new username system, otherwise their discriminator.

property display_avatar: Asset

Returns the user’s display avatar.

Returns the user’s uploaded avatar. If the user has not uploaded any avatar, their default avatar is returned instead.

Добавлено в версии 2.0.

property display_name: str

Returns the user’s display name. This will be their global name if set, otherwise their username.

property is_migrated: bool

Checks whether the user is already migrated to global name.

property jump_url: str

Returns a URL that allows the client to jump to the user.

Добавлено в версии 2.0.

property mention: str

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

mentioned_in(message)

Checks if the user is mentioned in the specified message.

Параметры:

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

Результат:

Indicates if the user is mentioned in the message.

Тип результата:

bool

property nameplate: Nameplate | None

The user’s nameplate, if the user has one equipped. Alias for User.collectibles.nameplate.

Добавлено в версии 2.7.

Изменено в версии 2.8: Now an alias for User.collectibles.nameplate.

property public_flags: PublicUserFlags

The publicly available flags the user has.

class discord.User(*, state, data)[исходный код]

Represents a Discord user.

x == y

Checks if two users are equal.

x != y

Checks if two users are not equal.

hash(x)

Return the user’s hash.

str(x)

Returns the user’s name with discriminator or global_name.

name

The user’s username.

Type:

str

id

The user’s unique ID.

Type:

int

discriminator

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

Примечание

If the user has migrated to the new username system, this will always be «0».

Type:

str

global_name

The user’s global name.

Добавлено в версии 2.5.

Type:

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

primary_guild

The user’s primary guild, if the user has one. Represent what guild the user’s tag is from.

Добавлено в версии 2.7.

Type:

Optional[PrimaryGuild]

Параметры:
  • state (ConnectionState)

  • data (User)

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

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

You must have read_message_history permissions to use this.

Параметры:
  • limit (int | None) – 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 (Snowflake | datetime | None) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Snowflake | datetime | None) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.

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

Yields:

Message – The message with the message data parsed.

Исключение:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Тип результата:

HistoryIterator

Примеры

Usage

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

Flattening into a list:

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

All parameters are optional.

async with typing()

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

This is useful for denoting long computations in your bot.

Примечание

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():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
Тип результата:

Typing

property dm_channel: DMChannel | None

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.

property mutual_guilds: list[Guild]

The guilds that the user shares with the client.

Примечание

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

Добавлено в версии 1.7.

property accent_color: Colour | None

Returns the user’s accent color, if applicable.

There is an alias for this named accent_colour.

Добавлено в версии 2.0.

Примечание

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

property accent_colour: Colour | None

Returns the user’s accent colour, if applicable.

There is an alias for this named accent_color.

Добавлено в версии 2.0.

Примечание

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

property avatar: Asset | None

Returns an Asset for the avatar the user has.

If the user does not have a traditional avatar, None is returned. If you want the avatar that a user has displayed, consider display_avatar.

property avatar_decoration: Asset | None

Returns the user’s avatar decoration, if available.

Добавлено в версии 2.5.

property banner: Asset | None

Returns the user’s banner asset, if available.

Добавлено в версии 2.0.

Примечание

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

can_send(*objects)

Returns a bool indicating whether you have the permissions to send the object(s).

Результат:

Indicates whether you have the permissions to send the object(s).

Тип результата:

bool

Исключение:

TypeError – An invalid type has been passed.

property collectibles: Collectibles | None

Returns the user’s equipped collectibles.

Добавлено в версии 2.8.

property color: Colour

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

There is an alias for this named colour.

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

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.

Результат:

The channel that was created.

Тип результата:

DMChannel

property created_at: datetime

Returns the user’s creation time in UTC.

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

property default_avatar: Asset

Returns the default avatar for a given user. This is calculated by the user’s ID if they’re on the new username system, otherwise their discriminator.

property display_avatar: Asset

Returns the user’s display avatar.

Returns the user’s uploaded avatar. If the user has not uploaded any avatar, their default avatar is returned instead.

Добавлено в версии 2.0.

property display_name: str

Returns the user’s display name. This will be their global name if set, otherwise their username.

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

Параметры:

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

Результат:

The message asked for.

Тип результата:

Message

Исключение:
  • NotFound – The specified message was not found.

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

  • HTTPException – Retrieving the message failed.

property is_migrated: bool

Checks whether the user is already migrated to global name.

property jump_url: str

Returns a URL that allows the client to jump to the user.

Добавлено в версии 2.0.

property mention: str

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

mentioned_in(message)

Checks if the user is mentioned in the specified message.

Параметры:

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

Результат:

Indicates if the user is mentioned in the message.

Тип результата:

bool

property nameplate: Nameplate | None

The user’s nameplate, if the user has one equipped. Alias for User.collectibles.nameplate.

Добавлено в версии 2.7.

Изменено в версии 2.8: Now an alias for User.collectibles.nameplate.

pins(*, limit=50, before=None)

Returns a MessagePinIterator that enables receiving the destination’s pinned messages.

You must have read_message_history permissions to use this.

Предупреждение

Starting from version 3.0, await channel.pins() will no longer return a list of Message. See examples below for new usage instead.

Параметры:
  • limit (int | None) – The number of pinned messages to retrieve. If None, retrieves every pinned message in the channel.

  • before (Snowflake | datetime | None) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

Yields:

MessagePin – The pinned message.

Исключение:
  • Forbidden – You do not have permissions to get pinned messages.

  • HTTPException – The request to get pinned messages failed.

Тип результата:

MessagePinIterator

Примеры

Usage

counter = 0
async for pin in channel.pins(limit=250):
    if pin.message.author == client.user:
        counter += 1

Flattening into a list:

pins = await channel.pins(limit=None).flatten()
# pins is now a list of MessagePin...

All parameters are optional.

property public_flags: PublicUserFlags

The publicly available flags the user has.

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, suppress_embeds=None, silent=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Параметры:
  • content (Optional[str]) – The content of the message to send.

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

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

  • file (File) – The file to upload.

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

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

  • enforce_nonce (Optional[bool]) –

    Whether nonce is enforced to be validated.

    Добавлено в версии 2.5.

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

  • allowed_mentions (AllowedMentions) –

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

    Добавлено в версии 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message being replied to or forwarded. This can be created using to_reference(). When replying, 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.

    Добавлено в версии 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    Добавлено в версии 1.6.

  • view (discord.ui.BaseView) – A Discord UI View to add to the message.

  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    Добавлено в версии 2.0.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    Добавлено в версии 2.0.

  • suppress (bool) –

    Whether to suppress embeds for the message.

    Устарело, начиная с версии 2.8.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message.

    Добавлено в версии 2.8.

  • silent (bool) –

    Whether to suppress push and desktop notifications for the message.

    Добавлено в версии 2.4.

  • poll (Poll) –

    The poll to send.

    Добавлено в версии 2.6.

Результат:

The message that was sent.

Тип результата:

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.

Тип результата:

None

await create_test_entitlement(sku)[исходный код]

This function is a coroutine.

Creates a test entitlement for the user.

Параметры:

sku (Snowflake) – The SKU to create a test entitlement for.

Результат:

The created entitlement.

Тип результата:

Entitlement

entitlements(skus=None, before=None, after=None, limit=100, exclude_ended=False)[исходный код]

Returns an AsyncIterator that enables fetching the user’s entitlements.

This is identical to Client.entitlements() with the user parameter.

Добавлено в версии 2.6.

Параметры:
  • skus (list[Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.

  • before (Snowflake | datetime | None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.

  • limit (int | None) – The number of entitlements to retrieve. If None, retrieves every entitlement, which may be slow. Defaults to 100.

  • exclude_ended (bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults to False.

Yields:

Entitlement – The application’s entitlements.

Исключение:

HTTPException – Retrieving the entitlements failed.

Тип результата:

EntitlementIterator

class discord.PrimaryGuild(data, state)[исходный код]

Represents a Discord Primary Guild.

Добавлено в версии 2.7.

x == y

Checks if two Primary Guilds are equal.

x != y

Checks if two Primary Guilds are not equal.

Изменено в версии 2.7.1: Primary Guilds are now comparable.

identity_guild_id

The ID of the guild.

Type:

int

identity_enabled

Whether the primary guild is enabled.

Type:

bool

tag

The tag of the primary guild.

Type:

str

Параметры:
  • data (PrimaryGuild)

  • state (ConnectionState)

property badge: Asset | None[исходный код]

Returns the badge asset, if available.

Добавлено в версии 2.7.

Messages

class discord.Attachment(*, data, state)[исходный код]

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 attachment’s unique identifier.

This is equivalent to id.

Изменено в версии 1.7: Attachment can now be cast to str and is hashable.

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

title

The attachment’s title. This is equal to the original filename (without an extension) if special characters were filtered from it.

Добавлено в версии 2.6.

Type:

Optional[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 or not.

Добавлено в версии 1.7.

Type:

bool

description

The attachment’s description.

Добавлено в версии 2.0.

Type:

Optional[str]

duration_secs

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

Добавлено в версии 2.5.

Type:

Optional[float]

waveform

The base64 encoded bytearray representing a sampled waveform (currently for voice messages).

Добавлено в версии 2.5.

Type:

Optional[str]

flags

Extra attributes of the attachment.

Добавлено в версии 2.5.

Type:

AttachmentFlags

hm

The unique signature of this attachment’s instance.

Добавлено в версии 2.5.

Type:

str

Параметры:
  • data (Attachment)

  • state (ConnectionState)

property expires_at: datetime | None

This attachment URL’s expiry time in UTC.

property issued_at: datetime | None

The attachment URL’s issue time in UTC.

is_spoiler()[исходный код]

Whether this attachment contains a spoiler.

Тип результата:

bool

await save(fp, *, seek_begin=True, use_cached=False, chunksize=None)[исходный код]

This function is a coroutine.

Saves this attachment into a file-like object.

Параметры:
  • fp (BufferedIOBase | 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.

  • chunksize (int | None) – The maximum size of each chunk to process. Must be a positive integer.

Результат:

The number of bytes written.

Тип результата:

int

Исключение:
await read(*, use_cached=False)[исходный код]

This function is a coroutine.

Retrieves the content of this attachment as a bytes object.

Добавлено в версии 1.1.

Параметры:

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.

Результат:

The contents of the attachment.

Тип результата:

bytes

Исключение:
  • HTTPException – Downloading the attachment failed.

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

  • NotFound – The attachment was deleted.

await read_chunked(chunksize, *, use_cached=False)[исходный код]

This function is a coroutine.

Retrieves the content of this attachment in chunks as a AsyncGenerator object of bytes.

Параметры:
  • chunksize (int) – The maximum size of each chunk to process. Must be a positive integer.

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

Yields:

bytes – A chunk of the file.

Исключение:
await to_file(*, use_cached=False, spoiler=False)[исходный код]

This function is a coroutine.

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

Добавлено в версии 1.3.

Параметры:
  • 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.

    Добавлено в версии 1.4.

  • spoiler (bool) –

    Whether the file is a spoiler.

    Добавлено в версии 1.4.

Результат:

The attachment as a file suitable for sending.

Тип результата:

File

Исключение:
  • HTTPException – Downloading the attachment failed.

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

  • NotFound – The attachment was deleted.

class discord.Message(*, state, channel, data)[исходный код]

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 the left the guild, then it is a User instead.

Type:

Union[Member, 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.

Type:

Optional[Union[str, int]]

embeds

A list of embeds the message has.

Type:

List[Embed]

channel

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

Type:

Union[TextChannel, Thread, DMChannel, GroupChannel, PartialMessageable]

reference

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

Добавлено в версии 1.5.

Type:

Optional[MessageReference]

mention_everyone

Specifies if the message mentions everyone.

Примечание

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.

Предупреждение

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.

Добавлено в версии 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 sticker items given to the message.

Добавлено в версии 1.6.

Type:

List[StickerItem]

components

A list of components in the message.

Добавлено в версии 2.0.

Type:

List[Component]

guild

The guild that the message belongs to, if applicable.

Type:

Optional[Guild]

interaction

The interaction associated with the message, if applicable.

Устарело, начиная с версии 2.6: Use interaction_metadata instead.

Type:

Optional[MessageInteraction]

interaction_metadata

The interaction metadata associated with the message, if applicable.

Добавлено в версии 2.6.

Type:

Optional[InteractionMetadata]

thread

The thread created from this message, if applicable.

Добавлено в версии 2.0.

Type:

Optional[Thread]

poll

The poll associated with this message, if applicable.

Добавлено в версии 2.6.

Type:

Optional[Poll]

call

The call information associated with this message, if applicable.

Добавлено в версии 2.6.

Type:

Optional[MessageCall]

snapshots

The snapshots attached to this message, if applicable.

Добавлено в версии 2.7.

Type:

Optional[List[MessageSnapshot]]

Параметры:
raw_mentions

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

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

raw_channel_mentions

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

raw_role_mentions

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

clean_content

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

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

Примечание

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.

property created_at: datetime

The message’s creation time in UTC.

property edited_at: datetime | None

An aware UTC datetime object containing the edited time of the message.

property jump_url: str

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

is_system()[исходный код]

Whether the message is a system message.

A system message is a message that is constructed entirely by the Discord API in response to something.

Добавлено в версии 1.3.

Тип результата:

bool

system_content

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

In the case of MessageType.default and MessageType.reply, this just returns the regular Message.content, and forwarded messages will display the original message’s content from Message.snapshots. Otherwise, this returns an English message denoting the contents of the system message.

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.

Изменено в версии 1.1: Added the new delay keyword-only parameter.

Параметры:
  • delay (float | None) – 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 (str | None) – The reason for deleting the message. Shows up on the audit log.

Исключение:
  • Forbidden – You do not have proper permissions to delete the message.

  • NotFound – The message was deleted already

  • HTTPException – Deleting the message failed.

Тип результата:

None

await edit(content=..., embed=..., embeds=..., file=..., files=..., attachments=..., suppress=..., suppress_embeds=..., delete_after=None, allowed_mentions=..., view=...)[исходный код]

This function is a coroutine.

Edits the message.

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

Изменено в версии 1.3: The suppress keyword-only parameter was added.

Параметры:
  • content (str | None) – The new content to replace the message with. Could be None to remove the content.

  • embed (Embed | None) – The new embed to replace the original with. Could be None to remove the embed.

  • embeds (list[Embed]) –

    The new embeds to replace the original with. Must be a maximum of 10. To remove all embeds [] should be passed.

    Добавлено в версии 2.0.

  • file (Sequence[File]) – A new file to add to the message.

  • files (list[Sequence[File]]) – New files to add to the message.

  • attachments (list[Attachment]) – A list of attachments to keep in the message. If [] is passed then all attachments are removed.

  • suppress (bool) –

    Whether to suppress embeds for the message. This removes all the embeds if set to True. If set to False this brings the embeds back if they were suppressed. Using this parameter requires manage_messages.

    Устарело, начиная с версии 2.8.

  • 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. Using this parameter requires manage_messages.

    Добавлено в версии 2.8.

  • delete_after (float | None) – 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 (AllowedMentions | None) –

    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.

    Добавлено в версии 1.4.

  • view (BaseView | None) – The updated view to update this message with. If None is passed then the view is removed.

Исключение:
  • NotFound – The message was not found.

  • HTTPException – Editing the message failed.

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

  • InvalidArgument – You specified both embed and embeds, specified both file and files, or either``file`` or files were of the wrong type.

Тип результата:

Message

await publish()[исходный код]

This function is a coroutine.

Publishes this message to your announcement channel.

You must have the send_messages permission to do this.

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

Исключение:
  • Forbidden – You do not have the proper permissions to publish this message.

  • HTTPException – Publishing the message failed.

Тип результата:

None

await pin(*, reason=None)[исходный код]

This function is a coroutine.

Pins the message.

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

Параметры:

reason (str | None) –

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

Добавлено в версии 1.4.

Исключение:
  • 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.

Тип результата:

None

await unpin(*, reason=None)[исходный код]

This function is a coroutine.

Unpins the message.

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

Параметры:

reason (str | None) –

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

Добавлено в версии 1.4.

Исключение:
  • 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.

Тип результата:

None

await add_reaction(emoji)[исходный код]

This function is a coroutine.

Add a reaction to the message.

The emoji may be a unicode emoji, a custom GuildEmoji, or an AppEmoji.

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.

Параметры:

emoji (GuildEmoji | AppEmoji | PartialEmoji | str) – The emoji to react with.

Исключение:
  • 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.

Тип результата:

None

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, a custom GuildEmoji, or an AppEmoji.

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.

Параметры:
Исключение:
  • 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.

Тип результата:

None

await clear_reaction(emoji)[исходный код]

This function is a coroutine.

Clears a specific reaction from the message.

The emoji may be a unicode emoji, a custom GuildEmoji, or an AppEmoji.

You need the manage_messages permission to use this.

Добавлено в версии 1.3.

Параметры:

emoji (GuildEmoji | AppEmoji | PartialEmoji | str | Reaction) – The emoji to clear.

Исключение:
  • 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.

Тип результата:

None

await clear_reactions()[исходный код]

This function is a coroutine.

Removes all the reactions from the message.

You need the manage_messages permission to use this.

Исключение:
  • HTTPException – Removing the reactions failed.

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

Тип результата:

None

await create_thread(*, name, auto_archive_duration=..., slowmode_delay=...)[исходный код]

This function is a coroutine.

Creates a public thread from this message.

You must have create_public_threads in order to create a public thread from a message.

The channel this message belongs in must be a TextChannel.

Добавлено в версии 2.0.

Параметры:
  • name (str) – The name of the thread.

  • auto_archive_duration (Literal[60, 1440, 4320, 10080]) – The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used.

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

Результат:

The created thread.

Тип результата:

Thread

Исключение:
await reply(content=None, **kwargs)[исходный код]

This function is a coroutine.

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

Добавлено в версии 1.6.

Результат:

The message that was sent.

Тип результата:

Message

Исключение:
  • 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.

Параметры:

content (str | None)

await forward_to(channel, **kwargs)[исходный код]

This function is a coroutine.

A shortcut method to abc.Messageable.send() to forward the Message to a channel.

Добавлено в версии 2.7.

Параметры:

channel (TextChannel | VoiceChannel | StageChannel | Thread | DMChannel | PartialMessageable | GroupChannel) – The channel to forward this to.

Результат:

The message that was sent.

Тип результата:

Message

Исключение:
  • 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.

await end_poll()[исходный код]

This function is a coroutine.

Immediately ends the poll associated with this message. Only doable by the poll’s owner.

Добавлено в версии 2.6.

Результат:

The updated message.

Тип результата:

Message

Исключение:
to_reference(*, fail_if_not_exists=True, type=None)[исходный код]

Creates a MessageReference from the current message.

Добавлено в версии 1.6.

Параметры:
  • 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.

    Добавлено в версии 1.7.

  • type (MessageReferenceType) –

    The type of message reference. Defaults to a reply.

    Добавлено в версии 2.7.

Результат:

The reference to this message.

Тип результата:

MessageReference

get_component(id)[исходный код]

Gets a component from this message. Roughly equal to utils.get(message.components, …). If an int is provided, the component will be retrieved by id, otherwise by custom_id. This method will also search nested components.

Параметры:

id (str | int) – The id or custom_id the item to get

Результат:

The component with the matching custom_id or id if it exists.

Тип результата:

Component | None

Attributes
class discord.MessagePin(state, channel, data)[исходный код]

Represents information about a pinned message.

Добавлено в версии 2.7.

Параметры:
property message: Message

The pinned message.

property pinned_at: datetime

An aware timestamp of when the message was pinned.

Attributes
class discord.MessageSnapshot(*, state, reference, data)[исходный код]

Represents a message snapshot.

Добавлено в версии 2.7.

message

The forwarded message, which includes a minimal subset of fields from the original message.

Type:

ForwardedMessage

Параметры:
class discord.ForwardedMessage(*, state, reference, data)[исходный код]

Represents the snapshotted contents from a forwarded message. Forwarded messages are immutable; any updates to the original message will not be reflected.

Добавлено в версии 2.7.

type

The type of the original 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

original_message

The original message that was forwarded, if available.

Type:

Optional[Union[Message, PartialMessage]]

channel

The TextChannel or Thread that the original message was sent from.

Type:

Union[TextChannel, Thread, DMChannel, GroupChannel, PartialMessageable]

guild

The guild that the original message belonged to, if applicable.

Type:

Optional[Union[Guild, Object]]

content

The contents of the original message.

Type:

str

embeds

A list of embeds the original message had.

Type:

List[Embed]

attachments

A list of attachments given to the original message.

Type:

List[Attachment]

flags

Extra features of the original message.

Type:

MessageFlags

mentions

A list of User that were originally mentioned.

Примечание

This list will be empty if the message was forwarded to a different place, e.g., from a DM to a guild, or from one guild to another.

Type:

List[User]

role_mentions

A list of Role that were originally mentioned.

Предупреждение

This is only available using abc.Messageable.fetch_message().

Type:

List[Role]

stickers

A list of sticker items given to the original message.

Type:

List[StickerItem]

components

A list of components in the original message.

Type:

List[Component]

Параметры:
property created_at: datetime

The original message’s creation time in UTC.

property edited_at: datetime | None

An aware UTC datetime object containing the edited time of the original message.

Attributes
class discord.DeletedReferencedMessage(parent)[исходный код]

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.

Добавлено в версии 1.6.

Параметры:

parent (MessageReference)

property id: int

The message ID of the deleted referenced message.

property channel_id: int

The channel ID of the deleted referenced message.

property guild_id: int | None

The guild ID of the deleted referenced message.

class discord.Reaction(*, message, data, emoji=None)[исходный код]

Represents a reaction to a message.

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

x == y

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

x != y

Checks if two reactions are not equal.

hash(x)

Returns the reaction’s hash.

str(x)

Returns the string form of the reaction’s emoji.

emoji

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

Type:

Union[GuildEmoji, AppEmoji, PartialEmoji, str]

count

The combined total of normal and super reactions for this emoji.

Type:

int

me

If the user sent this as a normal reaction.

Type:

bool

me_burst

If the user sent this as a super reaction.

Type:

bool

message

Message this reaction is for.

Type:

Message

burst

Whether this reaction is a burst (super) reaction.

Type:

bool

Параметры:
async for ... in users(*, limit=None, after=None, type=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.

Параметры:
  • limit (int | None) – The maximum number of results to return. If not provided, returns all the users who reacted to the message.

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

  • type (ReactionType | None) – The type of reaction to get users for. Defaults to normal.

Yields:

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

Исключение:

HTTPException – Getting the users for the reaction failed.

Тип результата:

ReactionIterator

Примеры

Usage

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

Flattening into a list:

users = await reaction.users().flatten()
# users is now a list of User...
winner = random.choice(users)
await channel.send(f'{winner} has won the raffle.')

Getting super reactors:

users = await reaction.users(type=ReactionType.burst).flatten()
property burst_colours: list[Colour]

Returns a list possible Colour this super reaction can be.

There is an alias for this named burst_colors.

property burst_colors: list[Colour]

Returns a list possible Colour this super reaction can be.

There is an alias for this named burst_colours.

property count_details

Returns ReactionCountDetails for the individual counts of normal and super reactions made.

is_custom_emoji()[исходный код]

If this is a custom emoji.

Тип результата:

bool

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.

Параметры:

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

Исключение:
  • 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.

Тип результата:

None

await clear()[исходный код]

This function is a coroutine.

Clears this reaction from the message.

You need the manage_messages permission to use this.

Добавлено в версии 1.3.

Исключение:
  • 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.

Тип результата:

None

class discord.ReactionCountDetails(data)[исходный код]

Represents a breakdown of the normal and burst reaction counts for the emoji.

normal

The number of normal reactions for this emoji.

Type:

int

burst

The number of super reactions for this emoji.

Type:

bool

Параметры:

data (ReactionCountDetails)

Monetization

class discord.SKU(*, state, data)[исходный код]

Represents a Discord SKU (stock-keeping unit).

Добавлено в версии 2.5.

id

The SKU’s ID.

Type:

int

type

The type of SKU.

Type:

SKUType

application_id

The ID of the application this SKU belongs to.

Type:

int

name

The name of the SKU.

Type:

str

slug

The SKU’s slug.

Type:

str

flags

The SKU’s flags.

Type:

SKUFlags

Параметры:
  • state (ConnectionState)

  • data (SKU)

property url: str

Returns the URL for the SKU.

Type:

str

fetch_subscriptions(user, *, before=None, after=None, limit=100)[исходный код]

Returns an AsyncIterator that enables fetching the SKU’s subscriptions.

Добавлено в версии 2.7.

Параметры:
  • user (Snowflake) – The user for which to retrieve subscriptions.

  • before (Snowflake | datetime | None) – Retrieves subscriptions before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieve subscriptions after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.

  • limit (int | None) – The number of subscriptions to retrieve. If None, retrieves all subscriptions.

Yields:

Subscription – A subscription that the user has for this SKU.

Исключение:

HTTPException – Getting the subscriptions failed.

Тип результата:

SubscriptionIterator

Примеры

Usage

async for subscription in sku.fetch_subscriptions(discord.Object(id=123456789)):
    print(subscription.status)

Flattening into a list

subscriptions = await sku.fetch_subscriptions(discord.Object(id=123456789)).flatten()
# subscriptions is now a list of Subscription...

All parameters except for user are optional.

class discord.Entitlement(*, data, state)[исходный код]

Represents a Discord entitlement.

Добавлено в версии 2.5.

Примечание

As of October 1, 2024, entitlements that have been purchased will have ends_at set to None unless the parent Subscription has been cancelled.

See the Discord changelog.

id

The entitlement’s ID.

Type:

int

sku_id

The ID of the SKU this entitlement is for.

Type:

int

application_id

The ID of the application this entitlement belongs to.

Type:

int

user_id

The ID of the user that owns this entitlement.

Type:

Union[int, MISSING]

type

The type of entitlement.

Type:

EntitlementType

deleted

Whether the entitlement has been deleted.

Type:

bool

starts_at

When the entitlement starts.

Type:

Union[datetime.datetime, MISSING]

ends_at

When the entitlement expires.

Type:

Union[datetime.datetime, MISSING]

guild_id

The ID of the guild that owns this entitlement.

Type:

Union[int, MISSING]

consumed

Whether or not this entitlement has been consumed. This will always be False for entitlements that are not from an SKU of type SKUType.consumable.

Type:

bool

Параметры:
  • data (Entitlement)

  • state (ConnectionState)

await consume()[исходный код]

This function is a coroutine.

Consumes this entitlement.

This can only be done on entitlements from an SKU of type SKUType.consumable.

Исключение:

HTTPException – Consuming the entitlement failed.

Тип результата:

None

await delete()[исходный код]

This function is a coroutine.

Deletes a test entitlement.

A test entitlement is an entitlement that was created using Guild.create_test_entitlement() or User.create_test_entitlement().

Исключение:

HTTPException – Deleting the entitlement failed.

Тип результата:

None

class discord.Subscription(*, state, data)[исходный код]

Represents a user making recurring payments for one or more SKUs.

Successful payments grant the user access to entitlements associated with the SKU.

Добавлено в версии 2.7.

id

The subscription’s ID.

Type:

int

user_id

The ID of the user that owns this subscription.

Type:

int

sku_ids

The IDs of the SKUs this subscription is for.

Type:

List[int]

entitlement_ids

The IDs of the entitlements this subscription is for.

Type:

List[int]

renewal_sku_ids

The IDs of the SKUs that the buyer will be subscribed to at renewal.

Type:

List[int]

current_period_start

The start of the current subscription period.

Type:

datetime.datetime

current_period_end

The end of the current subscription period.

Type:

datetime.datetime

status

The status of the subscription.

Type:

SubscriptionStatus

canceled_at

When the subscription was canceled.

Type:

datetime.datetime | None

Параметры:
  • state (ConnectionState)

  • data (Subscription)

property user

The user that owns this subscription.

Type:

Optional[User]

Guild

Methods
class discord.Guild(*, data, state)[исходный код]

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[GuildEmoji, …]

stickers

All stickers that the guild owns.

Добавлено в версии 2.0.

Type:

Tuple[GuildSticker, …]

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]

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.

Примечание

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.

Добавлено в версии 1.4.

Type:

Optional[int]

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. The features that a guild can have are subject to arbitrary change by Discord. You can find a catalog of guild features here.

Type:

List[str]

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

premium_progress_bar_enabled

Indicates if the guild has premium progress bar enabled.

Добавлено в версии 2.0.

Type:

bool

preferred_locale

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

Type:

Optional[str]

nsfw_level

The guild’s NSFW level.

Добавлено в версии 2.0.

Type:

NSFWLevel

approximate_member_count

The approximate number of members in the guild. This is None unless the guild is obtained using Client.fetch_guild() with with_counts=True.

Добавлено в версии 2.0.

Type:

Optional[int]

approximate_presence_count

The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded. This is None unless the guild is obtained using Client.fetch_guild() with with_counts=True.

Добавлено в версии 2.0.

Type:

Optional[int]

incidents_data

The incidents data for the guild.

Добавлено в версии 2.7.

Type:

Optional[IncidentsData]

Параметры:
  • data (Guild)

  • state (ConnectionState)

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.

Примечание

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

Добавлено в версии 1.3.

All parameters are optional.

Параметры:
  • limit (int | None) – The number of members to retrieve. Defaults to 1000. Pass None to fetch all members. Note that this is potentially slow.

  • after (Snowflake | datetime | None) – Retrieve members after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

Yields:

Member – The member with the member data parsed.

Исключение:
Тип результата:

MemberIterator

Примеры

Usage

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

Flattening into a list

members = await guild.fetch_members(limit=150).flatten()
# members is now a list of Member...
async for ... in audit_logs(*, limit=100, before=None, after=None, user=None, action=None)[исходный код]

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

You must have the view_audit_log permission to use this.

See API documentation for more information about the before and after parameters.

Параметры:
  • limit (int | None) – The number of entries to retrieve. If None retrieve all entries.

  • before (Snowflake | datetime | None) – Retrieve entries before this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieve entries after this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

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

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

Yields:

AuditLogEntry – The audit log entry.

Исключение:
  • Forbidden – You are not allowed to fetch audit logs

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

Тип результата:

AuditLogIterator

Примеры

Getting the first 100 entries:

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

Getting entries for a specific action:

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

Getting entries made by a specific user:

entries = await guild.audit_logs(limit=None, user=guild.me).flatten()
await channel.send(f'I made {len(entries)} moderation actions.')
await fetch_sounds()[исходный код]

This function is a coroutine. Fetches all the soundboard sounds in the guild.

Добавлено в версии 2.7.

Результат:

The sounds in the guild.

Тип результата:

list[SoundboardSound]

await fetch_sound(sound_id)[исходный код]

This function is a coroutine. Fetches a soundboard sound in the guild.

Добавлено в версии 2.7.

Параметры:

sound_id (int) – The ID of the sound.

Результат:

The sound.

Тип результата:

SoundboardSound

await create_sound(name, sound, volume=1.0, emoji=None, reason=None)[исходный код]

This function is a coroutine. Creates a SoundboardSound in the guild. You must have Permissions.manage_expressions permission to use this.

Добавлено в версии 2.7.

Параметры:
  • name (str) – The name of the sound.

  • sound (bytes) – The bytes-like object representing the sound data. Only MP3 sound files that are less than 5.2 seconds long are supported.

  • volume (float) – The volume of the sound. Defaults to 1.0.

  • emoji (PartialEmoji | GuildEmoji | str | None) – The emoji of the sound.

  • reason (str | None) – The reason for creating this sound. Shows up on the audit log.

Результат:

The created sound.

Тип результата:

SoundboardSound

Исключение:
property channels: list[VoiceChannel | StageChannel | TextChannel | ForumChannel | CategoryChannel]

A list of channels that belong to this guild.

property threads: list[Thread]

A list of threads that you have permission to view.

Добавлено в версии 2.0.

property jump_url: str

Returns a URL that allows the client to jump to the guild.

Добавлено в версии 2.0.

property large: bool

Indicates if the guild is a „large“ guild.

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

property voice_channels: list[VoiceChannel]

A list of voice channels that belong to this guild.

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

property stage_channels: list[StageChannel]

A list of stage channels that belong to this guild.

Добавлено в версии 1.7.

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

property forum_channels: list[ForumChannel]

A list of forum channels that belong to this guild.

Добавлено в версии 2.0.

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

property me: Member

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

property voice_client: VoiceClient | None

Returns the VoiceClient associated with this guild, if any.

property text_channels: list[TextChannel]

A list of text channels that belong to this guild.

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

property categories: list[CategoryChannel]

A list of categories that belong to this guild.

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

property sounds: list[SoundboardSound]

A list of soundboard sounds that belong to this guild.

Добавлено в версии 2.7.

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

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.

Результат:

The categories and their associated channels.

Тип результата:

list[Tuple[CategoryChannel | None, List[VoiceChannel | StageChannel | TextChannel | ForumChannel | CategoryChannel]]]

get_channel_or_thread(channel_id, /)[исходный код]

Returns a channel or thread with the given ID.

Добавлено в версии 2.0.

Параметры:

channel_id (int) – The ID to search for.

Результат:

The returned channel or thread or None if not found.

Тип результата:

Thread | VoiceChannel | StageChannel | TextChannel | ForumChannel | CategoryChannel | None

get_channel(channel_id, /)[исходный код]

Returns a channel with the given ID.

Примечание

This does not search for threads.

Параметры:

channel_id (int) – The ID to search for.

Результат:

The returned channel or None if not found.

Тип результата:

VoiceChannel | StageChannel | TextChannel | ForumChannel | CategoryChannel | None

get_thread(thread_id, /)[исходный код]

Returns a thread with the given ID.

Добавлено в версии 2.0.

Параметры:

thread_id (int) – The ID to search for.

Результат:

The returned thread or None if not found.

Тип результата:

Thread | None

property system_channel: TextChannel | None

Returns the guild’s channel used for system messages.

If no channel is set, then this returns None.

property system_channel_flags: SystemChannelFlags

Returns the guild’s system channel settings.

property rules_channel: TextChannel | None

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.

Добавлено в версии 1.3.

property public_updates_channel: TextChannel | None

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.

Добавлено в версии 1.4.

property emoji_limit: int

The maximum number of emoji slots this guild has.

property sticker_limit: int

The maximum number of sticker slots this guild has.

Добавлено в версии 2.0.

property soundboard_limit: int

The maximum number of soundboard slots this guild has.

Добавлено в версии 2.7.

property bitrate_limit: int

The maximum bitrate for voice channels this guild can have.

property filesize_limit: int

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

property members: list[Member]

A list of members that belong to this guild.

get_member(user_id, /)[исходный код]

Returns a member with the given ID.

Параметры:

user_id (int) – The ID to search for.

Результат:

The member or None if not found.

Тип результата:

Member | None

await get_or_fetch(object_type, object_id, default=None)[исходный код]

Shortcut method to get data from this guild either by returning the cached version, or if it does not exist, attempting to fetch it from the API.

Параметры:
  • object_type (type[TypeVar(_FETCHABLE, bound= VoiceChannel | TextChannel | ForumChannel | StageChannel | CategoryChannel | Thread | Member | User | Guild | Role | GuildEmoji | AppEmoji)]) – Type of object to fetch or get.

  • object_id (int | None) – ID of the object to get. If None, returns default if provided, otherwise None.

  • default (TypeVar(_D)) – The value to return instead of raising if fetching fails or if object_id is None.

  • self (Guild)

Результат:

The object if found, or default if provided when not found.

Тип результата:

TypeVar(_FETCHABLE, bound= VoiceChannel | TextChannel | ForumChannel | StageChannel | CategoryChannel | Thread | Member | User | Guild | Role | GuildEmoji | AppEmoji) | TypeVar(_D) | None

Исключение:
  • TypeError – Raised when required parameters are missing or invalid types are provided.

  • InvalidArgument – Raised when an unsupported or incompatible object type is used.

property premium_subscribers: list[Member]

A list of members who have «boosted» this guild.

property roles: list[Role]

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.

get_role(role_id, /)[исходный код]

Returns a role with the given ID.

Параметры:

role_id (int) – The ID to search for.

Результат:

The role or None if not found.

Тип результата:

Role | None

await fetch_roles_member_counts()[исходный код]

This function is a coroutine. Fetches a mapping of role IDs to their member counts for this guild.

Добавлено в версии 2.7.

Результат:

A mapping of role IDs to their member counts. Can be accessed with either role IDs (int) or Snowflake objects (e.g., Role).

Тип результата:

GuildRoleCounts

Исключение:

HTTPException – Fetching the role member counts failed.

Примеры

Getting member counts using role IDs:

counts = await guild.fetch_roles_member_counts()
member_count = counts[123456789]

Using a role object:

counts = await guild.fetch_roles_member_counts()
role = guild.get_role(123456789)
member_count = counts[role]
property default_role: Role

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

property premium_subscriber_role: Role | None

Gets the premium subscriber role, AKA «boost» role, in this guild.

Добавлено в версии 1.6.

property self_role: Role | None

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

Добавлено в версии 1.6.

property stage_instances: list[StageInstance]

Returns a list of the guild’s stage instances that are currently running.

Добавлено в версии 2.0.

get_stage_instance(stage_instance_id, /)[исходный код]

Returns a stage instance with the given ID.

Добавлено в версии 2.0.

Параметры:

stage_instance_id (int) – The ID to search for.

Результат:

The stage instance or None if not found.

Тип результата:

StageInstance | None

property owner: Member | None

The member that owns the guild.

property icon: Asset | None

Returns the guild’s icon asset, if available.

property banner: Asset | None

Returns the guild’s banner asset, if available.

property splash: Asset | None

Returns the guild’s invite splash asset, if available.

property discovery_splash: Asset | None

Returns the guild’s discovery splash asset, if available.

property member_count: int

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

Предупреждение

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

property chunked: bool

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.

property shard_id: int

Returns the shard ID for this guild if applicable.

property created_at: datetime

Returns the guild’s creation time in UTC.

property invites_disabled: bool

A boolean indicating whether the guild invites are disabled.

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 look up the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.

If no member is found, None is returned.

Параметры:

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

Результат:

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

Тип результата:

Member | None

await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_thread_slowmode_delay=..., default_auto_archive_duration=...)[исходный код]

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.

Примечание

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.

Параметры:
  • name (str) – The channel’s name.

  • overwrites (dict[Role | Member, PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.

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

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

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

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

  • nsfw (bool) – Whether the channel is marked as NSFW.

  • reason (str | None) – The reason for creating this channel. Shows up on the audit log.

  • default_thread_slowmode_delay (int | None) –

    The initial slowmode delay to set on newly created threads in this channel.

    Добавлено в версии 2.7.

  • default_auto_archive_duration (int) –

    The default auto archive duration in minutes for threads created in this channel.

    Добавлено в версии 2.7.

Результат:

The channel that was just created.

Тип результата:

TextChannel

Исключение:
  • 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.

Примеры

Creating a basic channel:

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

Creating a «secret» channel:

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

channel = await guild.create_text_channel('secret', overwrites=overwrites)
await create_voice_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=..., slowmode_delay=..., nsfw=...)[исходный код]

This function is a coroutine.

This is similar to create_text_channel() except makes a VoiceChannel instead.

Параметры:
  • name (str) – The channel’s name.

  • overwrites (dict[Role | Member, PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.

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

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

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

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

  • rtc_region (VoiceRegion | None) –

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

    Добавлено в версии 1.7.

  • video_quality_mode (VideoQualityMode) –

    The camera video quality for the voice channel’s participants.

    Добавлено в версии 2.0.

  • reason (str | None) – The reason for creating this channel. Shows up on the audit log.

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

    Добавлено в версии 2.7.

  • nsfw (bool) –

    Whether the channel is marked as NSFW.

    Добавлено в версии 2.7.

Результат:

The channel that was just created.

Тип результата:

VoiceChannel

Исключение:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

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

await create_stage_channel(name, *, topic, position=..., overwrites=..., category=None, reason=None, bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., slowmode_delay=..., nsfw=...)[исходный код]

This function is a coroutine.

This is similar to create_text_channel() except makes a StageChannel instead.

Добавлено в версии 1.7.

Параметры:
  • name (str) – The channel’s name.

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

  • overwrites (dict[Role | Member, PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.

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

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

  • reason (str | None) – The reason for creating this channel. Shows up on the audit log.

  • bitrate (int) –

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

    Добавлено в версии 2.7.

  • user_limit (int) –

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

    Добавлено в версии 2.7.

  • rtc_region (VoiceRegion | None) –

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

    Добавлено в версии 2.7.

  • video_quality_mode (VideoQualityMode) –

    The camera video quality for the voice channel’s participants.

    Добавлено в версии 2.7.

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

    Добавлено в версии 2.7.

  • nsfw (bool) –

    Whether the channel is marked as NSFW.

    Добавлено в версии 2.7.

Результат:

The channel that was just created.

Тип результата:

StageChannel

Исключение:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

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

await create_forum_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_reaction_emoji=..., available_tags=..., default_sort_order=..., default_thread_slowmode_delay=..., default_auto_archive_duration=...)[исходный код]

This function is a coroutine.

Creates a ForumChannel for the guild.

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

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

Примечание

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.

Параметры:
  • name (str) – The channel’s name.

  • overwrites (dict[Role | Member, PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.

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

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

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

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

  • nsfw (bool) – Whether the channel is marked as NSFW.

  • reason (str | None) – The reason for creating this channel. Shows up on the audit log.

  • default_reaction_emoji (GuildEmoji | int | str) –

    The default reaction emoji. Can be a unicode emoji or a custom emoji in the forms: GuildEmoji, snowflake ID, string representation (eg. „<a:emoji_name:emoji_id>“).

    Добавлено в версии v2.5.

  • available_tags (list[ForumTag]) –

    The set of tags that can be used in a forum channel.

    Добавлено в версии 2.7.

  • default_sort_order (SortOrder | None) –

    The default sort order type used to order posts in this channel.

    Добавлено в версии 2.7.

  • default_thread_slowmode_delay (int | None) –

    The initial slowmode delay to set on newly created threads in this channel.

    Добавлено в версии 2.7.

  • default_auto_archive_duration (int) –

    The default auto archive duration in minutes for threads created in this channel.

    Добавлено в версии 2.7.

Результат:

The channel that was just created.

Тип результата:

ForumChannel

Исключение:

Примеры

Creating a basic channel:

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

Creating a «secret» channel:

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

channel = await guild.create_forum_channel('secret', overwrites=overwrites)
await create_category(name, *, overwrites=..., reason=None, position=...)[исходный код]

This function is a coroutine.

Same as create_text_channel() except makes a CategoryChannel instead.

Примечание

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

Результат:

The channel that was just created.

Тип результата:

CategoryChannel

Исключение:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

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

Параметры:
await create_category_channel(name, *, overwrites=..., reason=None, position=...)

This function is a coroutine.

Same as create_text_channel() except makes a CategoryChannel instead.

Примечание

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

Результат:

The channel that was just created.

Тип результата:

CategoryChannel

Исключение:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

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

Параметры:
await leave()[исходный код]

This function is a coroutine.

Leaves the guild.

Примечание

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

Исключение:

HTTPException – Leaving the guild failed.

Тип результата:

None

await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., afk_channel=..., afk_timeout=..., default_notifications=..., verification_level=..., explicit_content_filter=..., system_channel=..., system_channel_flags=..., preferred_locale=..., rules_channel=..., public_updates_channel=..., premium_progress_bar_enabled=..., disable_invites=..., discoverable=..., disable_raid_alerts=..., enable_activity_feed=...)[исходный код]

This function is a coroutine.

Edits the guild.

You must have the manage_guild permission to edit the guild.

Изменено в версии 1.4: The rules_channel and public_updates_channel keyword-only parameters were added.

Изменено в версии 2.0: The discovery_splash and community keyword-only parameters were added.

Изменено в версии 2.0: The newly updated guild is returned.

Параметры:
  • name (str) – The new name of the guild.

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

  • icon (bytes | None) – 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 | None) – A bytes-like object representing the banner. Could be None to denote removal of the banner. This is only available to guilds that contain BANNER in Guild.features.

  • splash (bytes | None) – 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 | None) – 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.

  • community (bool) – Whether the guild should be a Community guild. If set to True, both rules_channel and public_updates_channel parameters are required.

  • afk_channel (VoiceChannel | None) – 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.

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

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

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

  • system_channel (TextChannel | None) – 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 (TextChannel | None) – 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 (TextChannel | None) – 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.

  • premium_progress_bar_enabled (bool) – Whether the guild should have premium progress bar enabled.

  • disable_invites (bool) – Whether the guild should have server invites enabled or disabled.

  • discoverable (bool) – Whether the guild should be discoverable in the discover tab.

  • disable_raid_alerts (bool) – Whether activity alerts for the guild should be disabled.

  • enable_activity_feed (bool) – Whether the guild’s user activity feed should be enabled.

  • reason (str | None) – The reason for editing this guild. Shows up on the audit log.

Исключение:
  • 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.

Результат:

The newly updated guild. Note that this has the same limitations as mentioned in Client.fetch_guild() and may not have full data.

Тип результата:

Guild

await fetch_channels()[исходный код]

This function is a coroutine.

Retrieves all abc.GuildChannel that the guild has.

Примечание

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

Добавлено в версии 1.2.

Результат:

All channels in the guild.

Тип результата:

Sequence[VoiceChannel | StageChannel | TextChannel | ForumChannel | CategoryChannel]

Исключение:
await active_threads()[исходный код]

This function is a coroutine.

Returns a list of active Thread that the client can access.

This includes both private and public threads.

Добавлено в версии 2.0.

Результат:

The active threads

Тип результата:

list[Thread]

Исключение:

HTTPException – The request to get the active threads failed.

await search_members(query, *, limit=1000)[исходный код]

Search for guild members whose usernames or nicknames start with the query string. Unlike fetch_members(), this does not require Intents.members().

Примечание

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

Добавлено в версии 2.6.

Параметры:
  • query (str) – Searches for usernames and nicknames that start with this string, case-insensitive.

  • limit (int) – The maximum number of members to retrieve, up to 1000.

Результат:

The list of members that have matched the query.

Тип результата:

list[Member]

Исключение:

HTTPException – Getting the members failed.

await fetch_member(member_id, /)[исходный код]

This function is a coroutine.

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

Примечание

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

Параметры:

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

Результат:

The member from the member ID.

Тип результата:

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.

Параметры:

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

Результат:

The BanEntry object for the specified user.

Тип результата:

BanEntry

Исключение:
  • Forbidden – You do not have proper permissions to get the information.

  • NotFound – This user is not banned.

  • HTTPException – An error occurred while fetching the information.

await fetch_channel(channel_id, /)[исходный код]

This function is a coroutine.

Retrieves a abc.GuildChannel or Thread with the specified ID.

Примечание

This method is an API call. For general usage, consider get_channel_or_thread() instead.

Добавлено в версии 2.0.

Результат:

The channel from the ID.

Тип результата:

VoiceChannel | StageChannel | TextChannel | ForumChannel | CategoryChannel | Thread

Исключение:
  • InvalidData – An unknown channel type was received from Discord or the guild the channel belongs to is not the same as the one in this object points to.

  • HTTPException – Retrieving the channel failed.

  • NotFound – Invalid Channel ID.

  • Forbidden – You do not have permission to fetch this channel.

Параметры:

channel_id (int)

bans(limit=None, before=None, after=None)[исходный код]

This function is a coroutine.

Retrieves an AsyncIterator that enables receiving the guild’s bans. In order to use this, you must have the ban_members permission. Users will always be returned in ascending order sorted by user ID. If both the before and after parameters are provided, only before is respected.

Изменено в версии 2.5: The before. and after parameters were changed. They are now of the type abc.Snowflake instead of SnowflakeTime to comply with the discord api.

Изменено в версии 2.0: The limit, before. and after parameters were added. Now returns a BanIterator instead of a list of BanEntry objects.

All parameters are optional.

Параметры:
  • limit (int | None) – The number of bans to retrieve. Defaults to 1000.

  • before (Snowflake | None) – Retrieve bans before the given user.

  • after (Snowflake | None) – Retrieve bans after the given user.

Yields:

BanEntry – The ban entry for the ban.

Исключение:
  • Forbidden – You do not have proper permissions to get the information.

  • HTTPException – An error occurred while fetching the information.

Тип результата:

BanIterator

Примеры

Usage

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

Flattening into a list

bans = await guild.bans(limit=150).flatten()
# bans is now a list of BanEntry...
await prune_members(*, days, compute_prune_count=True, roles=..., reason=None)[исходный код]

This function is a coroutine.

Prunes the guild from its inactive members.

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

You must have the kick_members permission to use this.

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

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

Изменено в версии 1.4: The roles keyword-only parameter was added.

Параметры:
  • days (int) – The number of days before counting as inactive.

  • reason (str | None) – 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 (list[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.

Исключение:
Результат:

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

Тип результата:

int | None

await templates()[исходный код]

This function is a coroutine.

Gets the list of templates from this guild.

Requires manage_guild permissions.

Добавлено в версии 1.7.

Результат:

The templates for this guild.

Тип результата:

list[Template]

Исключение:

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

await webhooks()[исходный код]

This function is a coroutine.

Gets the list of webhooks from this guild.

Requires manage_webhooks permissions.

Результат:

The webhooks for this guild.

Тип результата:

list[Webhook]

Исключение:

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

await estimate_pruned_members(*, days, roles=...)[исходный код]

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.

Параметры:
  • days (int) – The number of days before counting as inactive.

  • roles (list[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.

    Добавлено в версии 1.7.

Результат:

The number of members estimated to be pruned.

Тип результата:

int

Исключение:
  • Forbidden – You do not have permissions to prune members.

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

  • InvalidArgument – An integer was not passed for days.

await invites()[исходный код]

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.

Результат:

The list of invites that are currently active.

Тип результата:

list[Invite]

Исключение:
  • Forbidden – You do not have proper permissions to get the information.

  • HTTPException – An error occurred while fetching the information.

await create_template(*, name, description=...)[исходный код]

This function is a coroutine.

Creates a template for the guild.

You must have the manage_guild permission to do this.

Добавлено в версии 1.7.

Параметры:
  • name (str) – The name of the template.

  • description (str) – The description of the template.

Тип результата:

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.

Добавлено в версии 1.4.

Параметры:
  • type (str) – The integration type (e.g. Twitch).

  • id (int) – The integration ID.

Исключение:
  • Forbidden – You do not have permission to create the integration.

  • HTTPException – The account could not be found.

Тип результата:

None

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.

Добавлено в версии 1.4.

Результат:

The list of integrations that are attached to the guild.

Тип результата:

list[Integration]

Исключение:
  • Forbidden – You do not have permission to create the integration.

  • HTTPException – Fetching the integrations failed.

await fetch_stickers()[исходный код]

This function is a coroutine.

Retrieves a list of all Stickers for the guild.

Добавлено в версии 2.0.

Примечание

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

Исключение:

HTTPException – An error occurred fetching the stickers.

Результат:

The retrieved stickers.

Тип результата:

list[GuildSticker]

await fetch_sticker(sticker_id, /)[исходный код]

This function is a coroutine.

Retrieves a custom Sticker from the guild.

Добавлено в версии 2.0.

Примечание

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

Параметры:

sticker_id (int) – The sticker’s ID.

Результат:

The retrieved sticker.

Тип результата:

GuildSticker

Исключение:
  • NotFound – The sticker requested could not be found.

  • HTTPException – An error occurred fetching the sticker.

await create_sticker(*, name, description=None, emoji, file, reason=None)[исходный код]

This function is a coroutine.

Creates a Sticker for the guild.

You must have manage_emojis_and_stickers permission to do this.

Добавлено в версии 2.0.

Параметры:
  • name (str) – The sticker name. Must be 2 to 30 characters.

  • description (str | None) – The sticker’s description. If used, must be 2 to 100 characters.

  • emoji (str) – The name of a unicode emoji that represents the sticker’s expression.

  • file (File) – The file of the sticker to upload.

  • reason (str | None) – The reason for creating this sticker. Shows up on the audit log.

Результат:

The created sticker.

Тип результата:

GuildSticker

Исключение:
  • Forbidden – You are not allowed to create stickers.

  • HTTPException – An error occurred creating a sticker.

  • TypeError – The parameters for the sticker are not correctly formatted.

await delete_sticker(sticker, *, reason=None)[исходный код]

This function is a coroutine.

Deletes the custom Sticker from the guild.

You must have manage_emojis_and_stickers permission to do this.

Добавлено в версии 2.0.

Параметры:
  • sticker (Snowflake) – The sticker you are deleting.

  • reason (str | None) – The reason for deleting this sticker. Shows up on the audit log.

Исключение:
  • Forbidden – You are not allowed to delete stickers.

  • HTTPException – An error occurred deleting the sticker.

Тип результата:

None

get_emoji(emoji_id, /)[исходный код]

Returns an emoji with the given ID.

Добавлено в версии 2.7.

Параметры:

emoji_id (int) – The ID to get.

Результат:

The returned Emoji or None if not found.

Тип результата:

GuildEmoji | None

await fetch_emojis()[исходный код]

This function is a coroutine.

Retrieves all custom GuildEmojis from the guild.

Примечание

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

Исключение:

HTTPException – An error occurred fetching the emojis.

Результат:

The retrieved emojis.

Тип результата:

list[GuildEmoji]

await fetch_emoji(emoji_id, /)[исходный код]

This function is a coroutine.

Retrieves a custom GuildEmoji from the guild.

Примечание

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

Параметры:

emoji_id (int) – The emoji’s ID.

Результат:

The retrieved emoji.

Тип результата:

GuildEmoji

Исключение:
  • NotFound – The emoji requested could not be found.

  • HTTPException – An error occurred fetching the emoji.

await create_custom_emoji(*, name, image, roles=..., reason=None)[исходный код]

This function is a coroutine.

Creates a custom GuildEmoji 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.

Параметры:
  • name (str) – The emoji name. Must be at least 2 characters.

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

  • roles (list[Role]) – A list of Roles that can use this emoji. Leave empty to make it available to everyone.

  • reason (str | None) – The reason for creating this emoji. Shows up on the audit log.

Исключение:
Результат:

The created emoji.

Тип результата:

GuildEmoji

await delete_emoji(emoji, *, reason=None)[исходный код]

This function is a coroutine.

Deletes the custom GuildEmoji from the guild.

You must have manage_emojis permission to do this.

Параметры:
  • emoji (Snowflake) – The emoji you are deleting.

  • reason (str | None) – The reason for deleting this emoji. Shows up on the audit log.

Исключение:
Тип результата:

None

await fetch_roles()[исходный код]

This function is a coroutine.

Retrieves all Role that the guild has.

Примечание

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

Добавлено в версии 1.3.

Результат:

All roles in the guild.

Тип результата:

list[Role]

Исключение:

HTTPException – Retrieving the roles failed.

await fetch_role(role_id)[исходный код]

This function is a coroutine.

Retrieves a Role that the guild has.

Примечание

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

Добавлено в версии 2.7.

Результат:

The role in the guild with the specified ID.

Тип результата:

Role

Исключение:

HTTPException – Retrieving the role failed.

Параметры:

role_id (int)

await create_role(*, name=..., permissions=..., color=..., colour=..., colors=..., colours=..., holographic=..., hoist=..., mentionable=..., reason=None, icon=..., unicode_emoji=...)[исходный код]

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.

Изменено в версии 1.6: Can now pass int to colour keyword-only parameter.

Параметры:
  • name (str) – The role name. Defaults to „new role“.

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

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

  • reason (str | None) – The reason for creating this role. Shows up on the audit log.

  • icon (bytes | None) – A bytes-like object representing the icon. Only PNG/JPEG/WebP is supported. If this argument is passed, unicode_emoji is set to None. Only available to guilds that contain ROLE_ICONS in Guild.features.

  • unicode_emoji (str | None) – The role’s unicode emoji. If this argument is passed, icon is set to None. Only available to guilds that contain ROLE_ICONS in Guild.features.

  • color (Colour | int)

  • colors (RoleColours)

  • colours (RoleColours)

  • holographic (bool)

Результат:

The newly created role.

Тип результата:

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.

Добавлено в версии 1.4.

Example:

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

await guild.edit_role_positions(positions=positions)
Параметры:
  • positions (dict[Snowflake, int]) – A dict of Role to int to change the positions of each given role.

  • reason (str | None) – The reason for editing the role positions. Shows up on the audit log.

Результат:

A list of all the roles in the guild.

Тип результата:

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.

Параметры:
  • user (Snowflake) – The user to kick from their guild.

  • reason (str | None) – The reason the user got kicked.

Исключение:
Тип результата:

None

await ban(user, *, delete_message_seconds=None, 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.

Параметры:
  • user (Snowflake) – The user to ban from their guild.

  • delete_message_seconds (int | None) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.

  • reason (str | None) – The reason the user got banned.

Исключение:
Тип результата:

None

await bulk_ban(*users, delete_message_seconds=None, reason=None)[исходный код]

This function is a coroutine.

Bulk ban users from the guild.

The users must meet the abc.Snowflake abc.

You must have the ban_members permission to do this.

Example Usage:

# Ban multiple users
successes, failures = await guild.bulk_ban(user1, user2, user3, ..., reason="Raid")

# Ban a list of users
successes, failures = await guild.bulk_ban(*users)
Параметры:
  • *users (Snowflake) – An argument list of users to ban from the guild, up to 200.

  • delete_message_seconds (int | None) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.

  • reason (str | None) – The reason the users were banned.

Результат:

Returns two lists: the first contains members that were successfully banned, while the second is members that could not be banned.

Тип результата:

tuple[list[Snowflake], list[Snowflake]]

Исключение:
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.

Параметры:
  • user (Snowflake) – The user to unban.

  • reason (str | None) – The reason for doing this action. Shows up on the audit log.

Исключение:
Тип результата:

None

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.

Результат:

The special vanity invite. If None then the guild does not have a vanity invite set.

Тип результата:

Invite | None

Исключение:
  • Forbidden – You do not have the proper permissions to get this.

  • HTTPException – Retrieving the vanity invite failed.

await widget()[исходный код]

This function is a coroutine.

Returns the widget of the guild.

Примечание

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

Результат:

The guild’s widget.

Тип результата:

Widget

Исключение:
await edit_widget(*, enabled=..., channel=...)[исходный код]

This function is a coroutine.

Edits the widget of the guild.

You must have the manage_guild permission to use this

Добавлено в версии 2.0.

Параметры:
  • enabled (bool) – Whether to enable the widget for the guild.

  • channel (Snowflake | None) – The new widget channel. None removes the widget channel.

Исключение:
Тип результата:

None

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.

Добавлено в версии 1.5.

Параметры:

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

Исключение:

ClientException – The members intent is not enabled.

Тип результата:

None

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.

Добавлено в версии 1.3.

Параметры:
  • query (str | None) – The string that the username’s start with.

  • user_ids (list[int] | None) –

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

    Добавлено в версии 1.4.

  • limit (int | None) – The maximum number of members to send back. If no query is passed, passing None returns all members. If a query or user_ids is passed, must be between 1 and 100. Defaults to 5.

  • presences (bool) –

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

    Добавлено в версии 1.6.

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

Результат:

The list of members that have matched the query.

Тип результата:

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.

Добавлено в версии 1.4.

Параметры:
  • channel (VoiceChannel | StageChannel | None) – 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 welcome_screen()[исходный код]

This function is a coroutine.

Returns the WelcomeScreen of the guild.

The guild must have COMMUNITY in features.

You must have the manage_guild permission in order to get this.

Добавлено в версии 2.0.

Результат:

The welcome screen of guild.

Тип результата:

WelcomeScreen

Исключение:
  • Forbidden – You do not have the proper permissions to get this.

  • HTTPException – Retrieving the welcome screen failed somehow.

  • NotFound – The guild doesn’t have a welcome screen or community feature is disabled.

await edit_welcome_screen(**options)[исходный код]

This function is a coroutine.

A shorthand for WelcomeScreen.edit without fetching the welcome screen.

You must have the manage_guild permission in the guild to do this.

The guild must have COMMUNITY in Guild.features

Параметры:
  • description (Optional[str]) – The new description of welcome screen.

  • welcome_channels (Optional[List[WelcomeScreenChannel]]) – The welcome channels. The order of the channels would be same as the passed list order.

  • enabled (Optional[bool]) – Whether the welcome screen should be displayed.

  • reason (Optional[str]) – The reason that shows up on audit log.

Результат:

The edited welcome screen.

Тип результата:

WelcomeScreen

Исключение:
  • HTTPException – Editing the welcome screen failed somehow.

  • Forbidden – You don’t have permissions to edit the welcome screen.

  • NotFound – This welcome screen does not exist.

await fetch_scheduled_events(*, with_user_count=True)[исходный код]

This function is a coroutine.

Returns a list of ScheduledEvent in the guild.

Примечание

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

Параметры:

with_user_count (bool) – If the scheduled event should be fetched with the number of users that are interested in the events. Defaults to True.

Результат:

The fetched scheduled events.

Тип результата:

list[ScheduledEvent]

Исключение:
await fetch_scheduled_event(event_id, /, *, with_user_count=True)[исходный код]

This function is a coroutine.

Retrieves a ScheduledEvent from event ID.

Примечание

This method is an API call. If you have Intents.scheduled_events, consider get_scheduled_event() instead.

Параметры:
  • event_id (int) – The event’s ID to fetch with.

  • with_user_count (bool) – If the scheduled vent should be fetched with the number of users that are interested in the event. Defaults to True.

Результат:

The scheduled event from the event ID.

Тип результата:

ScheduledEvent | None

Исключение:
get_scheduled_event(event_id, /)[исходный код]

Returns a Scheduled Event with the given ID.

Параметры:

event_id (int) – The ID to search for.

Результат:

The scheduled event or None if not found.

Тип результата:

ScheduledEvent | None

await create_scheduled_event(*, name, description=..., start_time, end_time=..., location, privacy_level=('guild_only', 2), reason=None, image=...)[исходный код]

This function is a coroutine. Creates a scheduled event.

Параметры:
  • name (str) – The name of the scheduled event.

  • description (str) – The description of the scheduled event.

  • start_time (datetime) – A datetime object of when the scheduled event is supposed to start.

  • end_time (datetime) – A datetime object of when the scheduled event is supposed to end.

  • location (str | int | VoiceChannel | StageChannel | ScheduledEventLocation) – The location of where the event is happening.

  • privacy_level (ScheduledEventPrivacyLevel) – The privacy level of the event. Currently, the only possible value is ScheduledEventPrivacyLevel.guild_only, which is default, so there is no need to change this parameter.

  • reason (str | None) – The reason to show in the audit log.

  • image (bytes) – The cover image of the scheduled event

Результат:

The created scheduled event.

Тип результата:

ScheduledEvent | None

Исключение:
property scheduled_events: list[ScheduledEvent]

A list of scheduled events in this guild.

await fetch_auto_moderation_rules()[исходный код]

This function is a coroutine.

Retrieves a list of auto moderation rules for this guild.

Результат:

The auto moderation rules for this guild.

Тип результата:

list[AutoModRule]

Исключение:
  • HTTPException – Getting the auto moderation rules failed.

  • Forbidden – You do not have the Manage Guild permission.

await fetch_auto_moderation_rule(id)[исходный код]

This function is a coroutine.

Retrieves a AutoModRule from rule ID.

Результат:

The requested auto moderation rule.

Тип результата:

AutoModRule

Исключение:
  • HTTPException – Getting the auto moderation rule failed.

  • Forbidden – You do not have the Manage Guild permission.

Параметры:

id (int)

await create_auto_moderation_rule(*, name, event_type, trigger_type, trigger_metadata, actions, enabled=False, exempt_roles=None, exempt_channels=None, reason=None)[исходный код]

Creates an auto moderation rule.

Параметры:
  • name (str) – The name of the auto moderation rule.

  • event_type (AutoModEventType) – The type of event that triggers the rule.

  • trigger_type (AutoModTriggerType) – The rule’s trigger type.

  • trigger_metadata (AutoModTriggerMetadata) – The rule’s trigger metadata.

  • actions (list[AutoModAction]) – The actions to take when the rule is triggered.

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

  • exempt_roles (list[Snowflake]) – A list of roles that are exempt from the rule.

  • exempt_channels (list[Snowflake]) – A list of channels that are exempt from the rule.

  • reason (str | None) – The reason for creating the rule. Shows up in the audit log.

Результат:

The new auto moderation rule.

Тип результата:

AutoModRule

Исключение:
  • HTTPException – Creating the auto moderation rule failed.

  • Forbidden – You do not have the Manage Guild permission.

await onboarding()[исходный код]

This function is a coroutine.

Returns the Onboarding flow for the guild.

Добавлено в версии 2.5.

Результат:

The onboarding flow for the guild.

Тип результата:

Onboarding

Исключение:

HTTPException – Retrieving the onboarding flow failed somehow.

await edit_onboarding(*, prompts=..., default_channels=..., enabled=..., mode=..., reason=...)[исходный код]

This function is a coroutine.

A shorthand for Onboarding.edit without fetching the onboarding flow.

You must have the manage_guild and manage_roles permissions in the guild to do this.

Параметры:
  • prompts (list[OnboardingPrompt] | None) – The new list of prompts for this flow.

  • default_channels (list[Snowflake] | None) – The new default channels that users are opted into.

  • enabled (bool | None) – Whether onboarding should be enabled. Setting this to True requires the guild to have COMMUNITY in features and at least 7 default_channels.

  • mode (OnboardingMode | None) – The new onboarding mode.

  • reason (str | None) – The reason that shows up on Audit log.

Результат:

The updated onboarding flow.

Тип результата:

Onboarding

Исключение:
  • HTTPException – Editing the onboarding flow failed somehow.

  • Forbidden – You don’t have permissions to edit the onboarding flow.

await modify_incident_actions(*, invites_disabled_until=..., dms_disabled_until=..., reason=...)[исходный код]

This function is a coroutine.

Modify the guild’s incident actions, controlling when invites or DMs are re-enabled after being temporarily disabled. Requires the manage_guild permission.

Параметры:
  • invites_disabled_until (datetime | None) – The ISO8601 timestamp indicating when invites will be enabled again, or None to enable invites immediately.

  • dms_disabled_until (datetime | None) – The ISO8601 timestamp indicating when DMs will be enabled again, or None to enable DMs immediately.

  • reason (str | None) – The reason for this action, used for the audit log.

Результат:

The updated incidents data for the guild.

Тип результата:

IncidentsData

await delete_auto_moderation_rule(id, *, reason=None)[исходный код]

Deletes an auto moderation rule.

Параметры:
  • id (int) – The ID of the auto moderation rule.

  • reason (str | None) – The reason for deleting the rule. Shows up in the audit log.

Исключение:
  • HTTPException – Deleting the auto moderation rule failed.

  • Forbidden – You do not have the Manage Guild permission.

Тип результата:

None

await create_test_entitlement(sku)[исходный код]

This function is a coroutine.

Creates a test entitlement for the guild.

Параметры:

sku (Snowflake) – The SKU to create a test entitlement for.

Результат:

The created entitlement.

Тип результата:

Entitlement

entitlements(skus=None, before=None, after=None, limit=100, exclude_ended=False)[исходный код]

Returns an AsyncIterator that enables fetching the guild’s entitlements.

This is identical to Client.entitlements() with the guild parameter.

Добавлено в версии 2.6.

Параметры:
  • skus (list[Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.

  • before (Snowflake | datetime | None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.

  • limit (int | None) – The number of entitlements to retrieve. If None, retrieves every entitlement, which may be slow. Defaults to 100.

  • exclude_ended (bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults to False.

Yields:

Entitlement – The application’s entitlements.

Исключение:

HTTPException – Retrieving the entitlements failed.

Тип результата:

EntitlementIterator

get_sound(sound_id)[исходный код]

Returns a sound with the given ID.

Добавлено в версии 2.7.

Параметры:

sound_id (int) – The ID to search for.

Результат:

The sound or None if not found.

Тип результата:

SoundboardSound | None

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

class discord.Member(*, data, guild, state)[исходный код]

Represents a Discord member to a Guild.

This implements a lot of the functionality of User.

x == y

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

x != y

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

hash(x)

Returns the member’s hash.

str(x)

Returns the member’s name with the discriminator or global_name.

joined_at

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

Type:

Optional[datetime.datetime]

activities

The activities that the user is currently doing.

Примечание

Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters.

Type:

Tuple[Union[BaseActivity, Spotify]]

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.

Добавлено в версии 1.6.

Type:

bool

premium_since

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

Type:

Optional[datetime.datetime]

communication_disabled_until

An aware datetime object that specifies the date and time in UTC when the member will be removed from timeout.

Добавлено в версии 2.0.

Type:

Optional[datetime.datetime]

flags

Extra attributes of the member.

Добавлено в версии 2.6.

Type:

MemberFlags

Параметры:
  • data (MemberWithUser)

  • guild (Guild)

  • state (ConnectionState)

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

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

You must have read_message_history permissions to use this.

Параметры:
  • limit (int | None) – 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 (Snowflake | datetime | None) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Snowflake | datetime | None) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.

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

Yields:

Message – The message with the message data parsed.

Исключение:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Тип результата:

HistoryIterator

Примеры

Usage

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

Flattening into a list:

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

All parameters are optional.

async with typing()

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

This is useful for denoting long computations in your bot.

Примечание

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():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
Тип результата:

Typing

property name

Equivalent to User.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() DMChannel

This function is a coroutine.

Creates a DMChannel with this user.

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

Результат:

The channel that was created.

Тип результата:

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 primary_guild

Equivalent to User.primary_guild

property collectibles

Equivalent to User.collectibles

property avatar_decoration

Equivalent to User.avatar_decoration

property raw_status: str

The member’s overall status as a string value.

Добавлено в версии 1.5.

property status: Status

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

property mobile_status: Status

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

property desktop_status: Status

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

property web_status: Status

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

property global_name: str | None

The member’s global name, if applicable.

is_on_mobile()[исходный код]

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

Тип результата:

bool

property colour: Colour

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

This is an alias for Member.colours.primary.

property color: Colour

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

This is an alias for Member.colours.primary.

property colours: RoleColours

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

There is an alias for this named colors.

Добавлено в версии 2.8.

property colors: RoleColours

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

This is an alias for colours.

Добавлено в версии 2.8.

property roles: list[Role]

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.

property mention: str

Returns a string that allows you to mention the member.

property display_name: str

Returns the user’s display name. This will either be their guild specific nickname, global name or username.

property display_avatar: Asset

Returns the member’s display avatar.

Returns the user’s guild avatar. If the user does not have a guild avatar, their global avatar is returned instead.

Добавлено в версии 2.0.

property guild_avatar: Asset | None

Returns an Asset for the guild avatar the member has. If unavailable, None is returned.

Добавлено в версии 2.0.

property display_avatar_decoration: Asset | None

Returns the member’s displayed avatar decoration.

Returns the user’s guild avatar decoration. If the user does not have a guild avatar decoration, their global avatar decoration is returned instead.

Добавлено в версии 2.8.

property guild_avatar_decoration: Asset | None

Returns an Asset for the guild specific avatar decoration the member has. If unavailable, None is returned.

Добавлено в версии 2.8.

property display_banner: Asset | None

Returns the member’s display banner.

Returns the user’s guild banner. If the user does not have a guild banner, their global banner is returned instead.

Добавлено в версии 2.7.

property guild_banner: Asset | None

Returns an Asset for the guild banner the member has. If unavailable, None is returned.

Добавлено в версии 2.7.

property activity: Activity | Game | CustomActivity | Streaming | Spotify | None

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

Примечание

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.

Примечание

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

mentioned_in(message)[исходный код]

Checks if the member is mentioned in the specified message.

Параметры:

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

Результат:

Indicates if the member is mentioned in the message.

Тип результата:

bool

property top_role: Role

Returns the member’s highest role.

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

property guild_permissions: Permissions

Returns the member’s guild permissions.

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

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

property voice: VoiceState | None

Returns the member’s current voice state.

property timed_out: bool

Returns whether the member is timed out.

Добавлено в версии 2.0.

await ban(*, delete_message_seconds=None, reason=None)[исходный код]

This function is a coroutine.

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

Параметры:
Тип результата:

None

await unban(*, reason=None)[исходный код]

This function is a coroutine.

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

Параметры:

reason (str | None)

Тип результата:

None

await kick(*, reason=None)[исходный код]

This function is a coroutine.

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

Параметры:

reason (str | None)

Тип результата:

None

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., reason=None, communication_disabled_until=..., bypass_verification=..., banner=..., avatar=..., bio=...)[исходный код]

This function is a coroutine.

Edits the member’s data.

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

Parameter

Permission

nick

Permissions.manage_nicknames

mute

Permissions.mute_members

deafen

Permissions.deafen_members

roles

Permissions.manage_roles

voice_channel

Permissions.move_members

communication_disabled_until

Permissions.moderate_members

bypass_verification

See note below

Примечание

bypass_verification may be edited under three scenarios:

Примечание

The following parameters are only available when editing the bot’s own member:

  • avatar

  • banner

  • bio

All parameters are optional.

Изменено в версии 1.1: Can now pass None to voice_channel to kick a member from voice.

Изменено в версии 2.0: The newly member is now optionally returned, if applicable.

Параметры:
  • nick (str | None) – 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.

    Добавлено в версии 1.7.

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

  • voice_channel (VocalGuildChannel | None) – The voice channel to move the member to. Pass None to kick them from voice.

  • reason (str | None) – The reason for editing this member. Shows up on the audit log.

  • communication_disabled_until (datetime | None) –

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

    Добавлено в версии 2.0.

  • bypass_verification (bool | None) –

    Indicates if the member should bypass the guild’s verification requirements.

    Добавлено в версии 2.6.

  • banner (bytes | None) –

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

    This is only available when editing the bot’s own member (i.e. Guild.me).

    Добавлено в версии 2.7.

  • avatar (bytes | None) –

    A bytes-like object representing the avatar. Could be None to denote removal of the avatar.

    This is only available when editing the bot’s own member (i.e. Guild.me).

    Добавлено в версии 2.7.

  • bio (str | None) –

    The new bio for the member. Could be None to denote removal of the bio.

    This is only available when editing the bot’s own member (i.e. Guild.me).

    Добавлено в версии 2.7.

Результат:

The newly updated member, if applicable. This is only returned when certain fields are updated.

Тип результата:

Member | None

Исключение:
  • Forbidden – You do not have the proper permissions to the action requested.

  • HTTPException – The operation failed.

  • InvalidArgument – You tried to edit the avatar, banner, or bio of a member that is not the bot.

await timeout(until, *, reason=None)[исходный код]

This function is a coroutine.

Applies a timeout to a member in the guild until a set datetime.

You must have the moderate_members permission to timeout a member.

Параметры:
  • until (datetime | None) – The date and time to timeout the member for. If this is None then the member is removed from timeout.

  • reason (str | None) – The reason for doing this action. Shows up on the audit log.

Исключение:
  • Forbidden – You do not have permissions to timeout members.

  • HTTPException – An error occurred doing the request.

Тип результата:

None

await timeout_for(duration, *, reason=None)[исходный код]

This function is a coroutine.

Applies a timeout to a member in the guild for a set duration. A shortcut method for timeout(), and equivalent to timeout(until=datetime.utcnow() + duration, reason=reason).

You must have the moderate_members permission to timeout a member.

Параметры:
  • duration (timedelta) – The duration to timeout the member for.

  • reason (str | None) – The reason for doing this action. Shows up on the audit log.

Исключение:
  • Forbidden – You do not have permissions to timeout members.

  • HTTPException – An error occurred doing the request.

Тип результата:

None

await remove_timeout(*, reason=None)[исходный код]

This function is a coroutine.

Removes the timeout from a member.

You must have the moderate_members permission to remove the timeout.

This is equivalent to calling timeout() and passing None to the until parameter.

Параметры:

reason (str | None) – The reason for doing this action. Shows up on the audit log.

Исключение:
  • Forbidden – You do not have permissions to remove the timeout.

  • HTTPException – An error occurred doing the request.

Тип результата:

None

await request_to_speak()[исходный код]

This function is a coroutine.

Request to speak in the connected channel.

Only applies to stage channels.

Примечание

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

Добавлено в версии 1.7.

Исключение:
  • Forbidden – You do not have the proper permissions to the action requested.

  • HTTPException – The operation failed.

Тип результата:

None

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

Изменено в версии 1.1: Can now pass None to kick a member from voice.

Параметры:
  • channel (VocalGuildChannel | None) – The new voice channel to move the member to. Pass None to kick them from voice.

  • reason (str | None) – The reason for doing this action. Shows up on the audit log.

Тип результата:

None

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.

Параметры:
  • *roles (Snowflake) – An argument list of abc.Snowflake representing a Role to give to the member.

  • reason (str | None) – 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.

Исключение:
Тип результата:

None

can_send(*objects)

Returns a bool indicating whether you have the permissions to send the object(s).

Результат:

Indicates whether you have the permissions to send the object(s).

Тип результата:

bool

Исключение:

TypeError – An invalid type has been passed.

await create_test_entitlement(sku: discord.abc.Snowflake) Entitlement

This function is a coroutine.

Creates a test entitlement for the user.

Параметры:

sku (Snowflake) – The SKU to create a test entitlement for.

Результат:

The created entitlement.

Тип результата:

Entitlement

entitlements(skus: list[Snowflake] | None = None, before: SnowflakeTime | None = None, after: SnowflakeTime | None = None, limit: int | None = 100, exclude_ended: bool = False) EntitlementIterator

Returns an AsyncIterator that enables fetching the user’s entitlements.

This is identical to Client.entitlements() with the user parameter.

Добавлено в версии 2.6.

Параметры:
  • skus (list[abc.Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.

  • before (abc.Snowflake | datetime.datetime | None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (abc.Snowflake | datetime.datetime | None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.

  • limit (Optional[int]) – The number of entitlements to retrieve. If None, retrieves every entitlement, which may be slow. Defaults to 100.

  • exclude_ended (bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults to False.

Yields:

Entitlement – The application’s entitlements.

Исключение:

HTTPException – Retrieving the entitlements failed.

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

Параметры:

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

Результат:

The message asked for.

Тип результата:

Message

Исключение:
  • NotFound – The specified message was not found.

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

  • HTTPException – Retrieving the message failed.

property is_migrated

Equivalent to User.is_migrated

property jump_url

Equivalent to User.jump_url

property nameplate

Equivalent to User.nameplate

pins(*, limit=50, before=None)

Returns a MessagePinIterator that enables receiving the destination’s pinned messages.

You must have read_message_history permissions to use this.

Предупреждение

Starting from version 3.0, await channel.pins() will no longer return a list of Message. See examples below for new usage instead.

Параметры:
  • limit (int | None) – The number of pinned messages to retrieve. If None, retrieves every pinned message in the channel.

  • before (Snowflake | datetime | None) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

Yields:

MessagePin – The pinned message.

Исключение:
  • Forbidden – You do not have permissions to get pinned messages.

  • HTTPException – The request to get pinned messages failed.

Тип результата:

MessagePinIterator

Примеры

Usage

counter = 0
async for pin in channel.pins(limit=250):
    if pin.message.author == client.user:
        counter += 1

Flattening into a list:

pins = await channel.pins(limit=None).flatten()
# pins is now a list of MessagePin...

All parameters are optional.

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.

Параметры:
  • *roles (Snowflake) – An argument list of abc.Snowflake representing a Role to remove from the member.

  • reason (str | None) – 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.

Исключение:
  • Forbidden – You do not have permissions to remove these roles.

  • HTTPException – Removing the roles failed.

Тип результата:

None

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, suppress_embeds=None, silent=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Параметры:
  • content (Optional[str]) – The content of the message to send.

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

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

  • file (File) – The file to upload.

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

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

  • enforce_nonce (Optional[bool]) –

    Whether nonce is enforced to be validated.

    Добавлено в версии 2.5.

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

  • allowed_mentions (AllowedMentions) –

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

    Добавлено в версии 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message being replied to or forwarded. This can be created using to_reference(). When replying, 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.

    Добавлено в версии 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    Добавлено в версии 1.6.

  • view (discord.ui.BaseView) – A Discord UI View to add to the message.

  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    Добавлено в версии 2.0.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    Добавлено в версии 2.0.

  • suppress (bool) –

    Whether to suppress embeds for the message.

    Устарело, начиная с версии 2.8.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message.

    Добавлено в версии 2.8.

  • silent (bool) –

    Whether to suppress push and desktop notifications for the message.

    Добавлено в версии 2.4.

  • poll (Poll) –

    The poll to send.

    Добавлено в версии 2.6.

Результат:

The message that was sent.

Тип результата:

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.

Тип результата:

None

get_role(role_id, /)[исходный код]

Returns a role with the given ID from roles which the member has.

Добавлено в версии 2.0.

Параметры:

role_id (int) – The ID to search for.

Результат:

The role or None if not found in the member’s roles.

Тип результата:

Role | None

class discord.Template(*, state, data)[исходный код]

Represents a Discord template.

Добавлено в версии 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

An aware datetime in UTC representing when the template was created.

Type:

datetime.datetime

updated_at

An aware datetime in UTC representing when the template was last updated. This is referred to as «last synced» in the official Discord client.

Type:

datetime.datetime

source_guild

The source guild.

Type:

Guild

is_dirty

Whether the template has unsynced changes.

Добавлено в версии 2.0.

Type:

Optional[bool]

Параметры:
  • state (ConnectionState)

  • data (Template)

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.

Добавлено в версии 1.7.

Изменено в версии 2.0: The template is no longer synced in-place, instead it is returned.

Результат:

The newly synced template.

Тип результата:

Template

Исключение:
  • HTTPException – Syncing the template failed.

  • Forbidden – You don’t have permissions to sync the template.

  • NotFound – This template does not exist.

await edit(*, name=..., description=...)[исходный код]

This function is a coroutine.

Edit the template metadata.

You must have the manage_guild permission in the source guild to do this.

Добавлено в версии 1.7.

Изменено в версии 2.0: The template is no longer edited in-place, instead it is returned.

Параметры:
  • name (str) – The template’s new name.

  • description (str | None) – The template’s new description.

Результат:

The newly edited template.

Тип результата:

Template

Исключение:
  • 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.

Добавлено в версии 1.7.

Исключение:
  • HTTPException – Deleting the template failed.

  • Forbidden – You don’t have permissions to delete the template.

  • NotFound – This template does not exist.

Тип результата:

None

property url: str

The template url.

Добавлено в версии 2.0.

AutoMod

class discord.AutoModRule(*, state, data)[исходный код]

Represents a guild’s auto moderation rule.

Добавлено в версии 2.0.

x == y

Checks if two rules are equal.

x != y

Checks if two rules are not equal.

hash(x)

Returns the rule’s hash.

str(x)

Returns the rule’s name.

id

The rule’s ID.

Type:

int

name

The rule’s name.

Type:

str

creator_id

The ID of the user who created this rule.

Type:

int

event_type

Indicates in what context the rule is checked.

Type:

AutoModEventType

trigger_type

Indicates what type of information is checked to determine whether the rule is triggered.

Type:

AutoModTriggerType

trigger_metadata

The rule’s trigger metadata.

Type:

AutoModTriggerMetadata

actions

The actions to perform when the rule is triggered.

Type:

List[AutoModAction]

enabled

Whether this rule is enabled.

Type:

bool

exempt_role_ids

The IDs of the roles that are exempt from this rule.

Type:

List[int]

exempt_channel_ids

The IDs of the channels that are exempt from this rule.

Type:

List[int]

Параметры:
  • state (ConnectionState)

  • data (AutoModRule)

property guild: Guild | None

The guild this rule belongs to.

property creator: Member | None

The member who created this rule.

property exempt_roles: list[Role | Object][исходный код]

The roles that are exempt from this rule.

If a role is not found in the guild’s cache, then it will be returned as an Object.

property exempt_channels: list[TextChannel | ForumChannel | VoiceChannel | Object][исходный код]

The channels that are exempt from this rule.

If a channel is not found in the guild’s cache, then it will be returned as an Object.

await delete(reason=None)[исходный код]

This function is a coroutine.

Deletes this rule.

Параметры:

reason (str | None) – The reason for deleting this rule. Shows up in the audit log.

Исключение:
Тип результата:

None

await edit(*, name=..., event_type=..., trigger_metadata=..., actions=..., enabled=..., exempt_roles=..., exempt_channels=..., reason=None)[исходный код]

This function is a coroutine.

Edits this rule.

Параметры:
  • name (str) – The rule’s new name.

  • event_type (AutoModEventType) – The new context in which the rule is checked.

  • trigger_metadata (AutoModTriggerMetadata) – The new trigger metadata.

  • actions (list[AutoModAction]) – The new actions to perform when the rule is triggered.

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

  • exempt_roles (list[Snowflake]) – The roles that will be exempt from this rule.

  • exempt_channels (list[Snowflake]) – The channels that will be exempt from this rule.

  • reason (str | None) – The reason for editing this rule. Shows up in the audit log.

Результат:

The newly updated rule, if applicable. This is only returned when fields are updated.

Тип результата:

AutoModRule | None

Исключение:
Attributes
class discord.AutoModAction(action_type, metadata)[исходный код]

Represents an action for a guild’s auto moderation rule.

Добавлено в версии 2.0.

type

The action’s type.

Type:

AutoModActionType

metadata

The action’s metadata.

Type:

AutoModActionMetadata

Параметры:
class discord.AutoModActionMetadata(channel_id=..., timeout_duration=..., custom_message=...)[исходный код]

Represents an action’s metadata.

Depending on the action’s type, different attributes will be used.

Добавлено в версии 2.0.

channel_id

The ID of the channel to send the message to. Only for actions of type AutoModActionType.send_alert_message.

Type:

int

timeout_duration

How long the member that triggered the action should be timed out for. Only for actions of type AutoModActionType.timeout.

Type:

datetime.timedelta

custom_message

An additional message shown to members when their message is blocked. Maximum 150 characters. Only for actions of type AutoModActionType.block_message.

Type:

str

Параметры:
class discord.AutoModTriggerMetadata(keyword_filter=..., regex_patterns=..., presets=..., allow_list=..., mention_total_limit=...)[исходный код]

Represents a rule’s trigger metadata, defining additional data used to determine when a rule triggers.

Depending on the trigger type, different metadata attributes will be used:

Each attribute has limits that may change based on the trigger type. See here for information on attribute limits.

Добавлено в версии 2.0.

keyword_filter

A list of substrings to filter.

Type:

List[str]

regex_patterns

A list of regex patterns to filter using Rust-flavored regex, which is not fully compatible with regex syntax supported by the builtin re module.

Добавлено в версии 2.4.

Type:

List[str]

presets

A list of preset keyword sets to filter.

Type:

List[AutoModKeywordPresetType]

allow_list

A list of substrings to allow, overriding keyword and regex matches.

Добавлено в версии 2.4.

Type:

List[str]

mention_total_limit

The total number of unique role and user mentions allowed.

Добавлено в версии 2.4.

Type:

int

Параметры:
  • keyword_filter (list[str])

  • regex_patterns (list[str])

  • presets (list[AutoModKeywordPresetType])

  • allow_list (list[str])

  • mention_total_limit (int)

Invites

class discord.PartialInviteGuild(state, data, id)[исходный код]

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]

description

The partial guild’s description.

Type:

Optional[str]

Параметры:
  • state (ConnectionState)

  • data (InviteGuild)

  • id (int)

property created_at: datetime

Returns the guild’s creation time in UTC.

property icon: Asset | None

Returns the guild’s icon asset, if available.

property banner: Asset | None

Returns the guild’s banner asset, if available.

property splash: Asset | None

Returns the guild’s invite splash asset, if available.

class discord.PartialInviteChannel(data)[исходный код]

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

Параметры:

data (PartialChannel)

property mention: str

The string that allows you to mention the channel.

property created_at: datetime

Returns the channel’s creation time in UTC.

class discord.Invite(*, state, data, guild=None, channel=None)[исходный код]

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

An aware UTC 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:

Optional[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]

expires_at

The expiration date of the invite. If the value is None when received through Client.fetch_invite with with_expiration enabled, the invite will never expire.

Добавлено в версии 2.0.

Type:

Optional[datetime.datetime]

channel

The channel the invite is for.

Type:

Union[abc.GuildChannel, Object, PartialInviteChannel]

target_type

The type of target for the voice channel invite.

Добавлено в версии 2.0.

Type:

InviteTarget

target_user

The user whose stream to display for this invite, if any.

Добавлено в версии 2.0.

Type:

Optional[User]

target_application

The embedded application the invite targets, if any.

Добавлено в версии 2.0.

Type:

Optional[PartialAppInfo]

scheduled_event

The scheduled event linked with the invite.

Type:

Optional[ScheduledEvent]

roles

The roles that will be assigned to a user that joins via this invite.

When using Client.fetch_invite, these may be partial role objects and have nullish attributes.

Добавлено в версии 2.8.

Type:

List[Union[Role, Object]]

Параметры:
property id: str

Returns the proper code portion of the invite.

property url: str

A property that retrieves the invite URL.

property target_users: InviteTargetUsers

An InviteTargetUsers object for managing the target users list for this invite.

Добавлено в версии 2.8.

await edit_target_users(target_users_file)[исходный код]

This function is a coroutine.

Updates the target users list for this invite.

You must have created this invite or have the manage_guild permission to do this.

You can use utils.users_to_csv() to generate a virtual CSV file from a sequence of user IDs.

Параметры:

target_users_file (File) – A CSV file with a single column of user IDs for all the users able to accept this invite.

Исключение:
  • HTTPException – Updating the target users failed.

  • Forbidden – You do not have permissions to edit this invite.

  • NotFound – The invite is invalid or expired.

Тип результата:

None

await fetch_target_users_job_status()[исходный код]

This function is a coroutine.

Retrieves the status of the target users processing job for this invite.

You must have created this invite or have the manage_guild or view_audit_log permissions. permission to do this.

Результат:

The job status information.

Тип результата:

InviteTargetUsersJobStatus

Исключение:
  • HTTPException – Fetching the job status failed.

  • NotFound – The invite is invalid or expired.

  • Forbidden – You do not have permission to view the target users.

await delete(*, reason=None)[исходный код]

This function is a coroutine.

Revokes the instant invite.

You must have the manage_channels permission to do this.

Параметры:

reason (str | None) – The reason for deleting this invite. Shows up on the audit log.

Исключение:
  • 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.

Примечание

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.

Добавлено в версии 2.0.

Параметры:

event (ScheduledEvent) – The scheduled event object to link.

Тип результата:

None

Attributes
Methods
class discord.InviteTargetUsers(*, state, invite_code)[исходный код]

Represents the target users CSV file for an invite.

Добавлено в версии 2.8.

invite_code

The invite code for which the target users are associated.

Type:

str

Параметры:
  • state (ConnectionState)

  • invite_code (str)

await read()[исходный код]

This function is a coroutine.

Retrieves this invite’s target users CSV file as a bytes object.

You must have created this invite or the manage_guild or view_audit_log permission to do this.

Результат:

The content of the CSV file.

Тип результата:

bytes

Исключение:
  • DiscordException – There was no internal connection state.

  • HTTPException – Downloading the file failed.

  • NotFound – This invite does not have any target users set.

  • Forbidden – You do not have permission to view the target users.

await save(fp, *, seek_begin=True)[исходный код]

This function is a coroutine.

Saves this invite’s target users CSV file into a file-like object.

You must have created this invite or the manage_guild or view_audit_log permission to do this.

Параметры:
  • fp (str | bytes | PathLike[str] | BufferedIOBase) – The file-like object to save this file 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.

Результат:

The number of bytes written.

Тип результата:

int

Исключение:
  • DiscordException – There was no internal connection state.

  • HTTPException – Downloading the file failed.

  • NotFound – This invite does not have any target users set.

  • Forbidden – You do not have permission to view the target users.

await as_user_ids()[исходный код]

This function is a coroutine.

Retrieves a list of user IDs that can accept this invite. This internally reads the invite’s target users CSV file and parses the user IDs from it.

You must have created this invite or the manage_guild or view_audit_log permission to do this.

Результат:

A list of user IDs that can accept this invite.

Тип результата:

list[int]

class discord.InviteTargetUsersJobStatus(*, data)[исходный код]

Represents the status of a target users processing job for an invite.

Добавлено в версии 2.8.

total_users

The total number of users to process.

Type:

int

processed_users

The number of users that have been processed so far.

Type:

int

created_at

When the job was created. None if the creation time is not available.

Type:

Optional[datetime.datetime]

completed_at

When the job was completed. None if the job is still processing.

Type:

Optional[datetime.datetime]

error_message

The error message if the job failed. None if no error occurred.

Type:

Optional[str]

status

The current status of the job.

Type:

InviteTargetUsersJobStatusCode

Параметры:

data (InviteTargetUsersJobStatus)

Role

class discord.Role(*, guild, state, data)[исходный код]

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

position

The position of the role. This number is usually positive. The bottom role has a position of 0.

Предупреждение

Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.

Type:

int

managed

Indicates if the role is managed by the guild. This is true if any of Role.is_integration(), Role.is_premium_subscriber(), Role.is_bot_managed() or Role.is_guild_connections_role() is True.

Type:

bool

mentionable

Indicates if the role can be mentioned by users.

Type:

bool

tags

The role tags associated with this role. Tags indicate whether the role is a special role, such as but not limited to a bot role or the booster role.

Type:

Optional[RoleTags]

unicode_emoji

The role’s unicode emoji. Only available to guilds that contain ROLE_ICONS in Guild.features.

Добавлено в версии 2.0.

Type:

Optional[str]

flags

Extra attributes of the role.

Добавлено в версии 2.6.

Type:

RoleFlags

colours

The role’s colours.

Добавлено в версии 2.7.

Type:

RoleColours

Параметры:
  • guild (Guild)

  • state (ConnectionState)

  • data (Role)

is_default()[исходный код]

Checks if the role is the default role.

Тип результата:

bool

is_bot_managed()[исходный код]

Whether the role is associated with a bot.

Устарело, начиная с версии 2.8: Use Role.type instead.

Добавлено в версии 1.6.

Тип результата:

bool

is_premium_subscriber()[исходный код]

Whether the role is the premium subscriber, AKA «boost», role for the guild.

Устарело, начиная с версии 2.8: Use Role.type instead.

Добавлено в версии 1.6.

Тип результата:

bool

is_integration()[исходный код]

Whether the guild manages the role through some form of integrations such as Twitch or through guild subscriptions.

Устарело, начиная с версии 2.8: Use Role.type instead.

Добавлено в версии 1.6.

Тип результата:

bool

is_assignable()[исходный код]

Whether the role is able to be assigned or removed by the bot. This checks whether all of the following conditions are true:

  • The role is not the guild’s Guild.default_role

  • The role is not managed

  • The bot has the manage_roles permission

  • The bot’s top role is above this role

Добавлено в версии 2.0.

Изменено в версии 2.7.1: Added check for manage_roles permission

Тип результата:

bool

is_available_for_purchase()[исходный код]

Whether the role is available for purchase.

Returns True if the role is available for purchase, and False if it is not available for purchase or if the role is not linked to a guild subscription.

Устарело, начиная с версии 2.8: Use Role.type instead.

Добавлено в версии 2.7.

Тип результата:

bool

is_guild_connections_role()[исходный код]

Whether the role is a guild connections role.

Устарело, начиная с версии 2.8: Use Role.type instead.

Добавлено в версии 2.7.

Тип результата:

bool

property permissions: Permissions

Returns the role’s permissions.

property colour: Colour

Returns the role colour. Equivalent to colours.primary. An alias exists under color.

Изменено в версии 2.7.

property color: Colour

Returns the role’s primary color. Equivalent to colors.primary. An alias exists under colour.

Изменено в версии 2.7.

property colors: RoleColours

Returns the role’s colours. Equivalent to colours.

Добавлено в версии 2.7.

property created_at: datetime

Returns the role’s creation time in UTC.

property mention: str

Returns a string that allows you to mention a role.

property members: list[Member]

Returns all the members with this role.

property icon: Asset | None

Returns the role’s icon asset, if available.

Добавлено в версии 2.0.

property type: RoleType

The type of the role.

This is an alias for RoleTags.type.

Добавлено в версии 2.8.

await edit(*, name=..., permissions=..., colour=..., color=..., colours=..., colors=..., holographic=..., hoist=..., mentionable=..., position=..., reason=..., icon=..., unicode_emoji=...)[исходный код]

This function is a coroutine.

Edits the role.

You must have the manage_roles permission to use this.

All fields are optional.

Изменено в версии 1.4: Can now pass int to colour keyword-only parameter.

Изменено в версии 2.0: Edits are no longer in-place, the newly edited role is returned instead. Added icon and unicode_emoji.

Параметры:
  • name (str) – The new role name to change to.

  • permissions (Permissions) – The new permissions to change to.

  • colour (Colour | int) – The new colour to change to. (aliased to color as well)

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

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

  • position (int) – The new role’s position. This must be below your top role’s position, or it will fail.

  • reason (str | None) – The reason for editing this role. Shows up on the audit log.

  • icon (bytes | None) – A bytes-like object representing the icon. Only PNG/JPEG/WebP is supported. If this argument is passed, unicode_emoji is set to None. Only available to guilds that contain ROLE_ICONS in Guild.features. Could be None to denote removal of the icon.

  • unicode_emoji (str | None) – The role’s unicode emoji. If this argument is passed, icon is set to None. Only available to guilds that contain ROLE_ICONS in Guild.features.

  • color (Colour | int)

  • colours (RoleColours)

  • colors (RoleColours)

  • holographic (bool)

Результат:

The newly edited role.

Тип результата:

Role

Исключение:
  • 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.

Параметры:

reason (str | None) – The reason for deleting this role. Shows up on the audit log.

Исключение:
Тип результата:

None

class discord.RoleTags(data)[исходный код]

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.

Role tags are a fairly complex topic, since it’s usually hard to determine which role tag combination represents which role type. In order to make your life easier, pycord provides a RoleTags.type attribute that attempts to determine the role type based on the role tags. Its value is not provided by Discord but is rather computed based on the role tags. If you find an issue, please report it on GitHub. Read this if you need detailed information about how role tags work.

Добавлено в версии 1.6.

Изменено в версии 2.8: The type of the role is now determined by the RoleTags.type attribute.

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]

subscription_listing_id

The subscription SKU and listing ID of the role.

Добавлено в версии 2.7.

Type:

Optional[int]

Параметры:

data (RoleTags)

type

The type of the role.

Role tags are a fairly complex topic, since it’s usually hard to determine which role tag combination represents which role type. In order to make your life easier, pycord provides a RoleTags.type attribute that attempts to determine the role type based on the role tags. Its value is not provided by Discord but is rather computed based on the role tags. If you find an issue, please report it on GitHub. Read this if you need detailed information about how role tags work.

Type:

RoleType

is_bot_managed()[исходный код]

Whether the role is associated with a bot.

Устарело, начиная с версии 2.8: Use RoleTags.type == RoleType.APPLICATION instead.

Тип результата:

bool

is_premium_subscriber()[исходный код]

Whether the role is the premium subscriber, AKA «boost», role for the guild.

Устарело, начиная с версии 2.8: Use RoleTags.type == RoleType.BOOSTER instead.

Тип результата:

bool

is_integration()[исходный код]

Whether the guild manages the role through some form of integrations such as Twitch or through guild subscriptions.

Устарело, начиная с версии 2.8: Use RoleTags.type in (RoleType.INTEGRATION, RoleType.PREMIUM_SUBSCRIPTION_TIER, RoleType.DRAFT_PREMIUM_SUBSCRIPTION_TIER) instead.

Тип результата:

bool

is_available_for_purchase()[исходный код]

Whether the role is available for purchase.

Returns True if the role is available for purchase, and False if it is not available for purchase or if the role is not linked to a guild subscription.

Устарело, начиная с версии 2.8: Use RoleTags.type == RoleType.PREMIUM_SUBSCRIPTION_TIER instead.

Добавлено в версии 2.7.

Тип результата:

bool

is_guild_connections_role()[исходный код]

Whether the role is a guild connections role.

Устарело, начиная с версии 2.8: Use RoleTags.type == RoleType.CONNECTION instead.

Добавлено в версии 2.7.

Тип результата:

bool

class discord.RoleColours(primary, secondary=None, tertiary=None)[исходный код]

Represents a role’s gradient colours.

Добавлено в версии 2.7.

primary

The primary colour of the role.

Type:

Colour

secondary

The secondary colour of the role.

Type:

Optional[Colour]

tertiary

The tertiary colour of the role. At the moment, only 16761760 is allowed.

Type:

Optional[Colour]

Параметры:
classmethod default()[исходный код]

Returns a default RoleColours object with no colours set.

Тип результата:

RoleColours

classmethod holographic()[исходный код]

Returns a RoleColours that makes the role look holographic.

Currently holographic roles are only supported with colours 11127295, 16759788, and 16761760.

Тип результата:

RoleColours

property is_holographic: bool

Whether the role is holographic.

Currently roles are holographic when colours are set to 11127295, 16759788, and 16761760.

Methods
class discord.GuildRoleCounts[исходный код]

A dictionary subclass that maps role IDs to their member counts.

This class allows accessing member counts by either role ID (int) or by a Snowflake object (which has an .id attribute).

Добавлено в версии 2.7.

get(key, default=None)[исходный код]

Get the member count for a role, returning a default if not found.

Параметры:
  • key (int | Snowflake) – The role ID or a Snowflake object (e.g., a Role).

  • default (TypeVar(T)) – The value to return if the role ID is not found.

Результат:

The member count for the role, or default if the role is not present.

Тип результата:

int | TypeVar(T)

Scheduled Event

class discord.ScheduledEvent(*, state, guild, creator, data)[исходный код]

Represents a Discord Guild Scheduled Event.

x == y

Checks if two scheduled events are equal.

x != y

Checks if two scheduled events are not equal.

hash(x)

Returns the scheduled event’s hash.

str(x)

Returns the scheduled event’s name.

Добавлено в версии 2.0.

guild

The guild where the scheduled event is happening.

Type:

Guild

name

The name of the scheduled event.

Type:

str

description

The description of the scheduled event.

Type:

Optional[str]

start_time

The time when the event will start

Type:

datetime.datetime

end_time

The time when the event is supposed to end.

Type:

Optional[datetime.datetime]

status

The status of the scheduled event.

Type:

ScheduledEventStatus

location

The location of the event. See ScheduledEventLocation for more information.

Type:

ScheduledEventLocation

subscriber_count

The number of users that have marked themselves as interested in the event.

Type:

Optional[int]

creator_id

The ID of the user who created the event. It may be None because events created before October 25th, 2021 haven’t had their creators tracked.

Type:

Optional[int]

creator

The resolved user object of who created the event.

Type:

Optional[User]

privacy_level

The privacy level of the event. Currently, the only possible value is ScheduledEventPrivacyLevel.guild_only, which is default, so there is no need to use this attribute.

Type:

ScheduledEventPrivacyLevel

Параметры:
  • state (ConnectionState)

  • guild (Guild)

  • creator (Member | None)

  • data (ScheduledEvent)

property created_at: datetime

Returns the scheduled event’s creation time in UTC.

property interested: int | None

An alias to subscriber_count

property url: str

The url to reference the scheduled event.

property cover: Asset | None

Returns the scheduled event cover image asset, if available.

Устарело, начиная с версии 2.7: Use the image property instead.

property image: Asset | None

Returns the scheduled event cover image asset, if available.

await edit(*, reason=None, name=..., description=..., status=..., location=..., start_time=..., end_time=..., cover=..., image=..., privacy_level=('guild_only', 2))[исходный код]

This function is a coroutine.

Edits the Scheduled Event’s data

All parameters are optional unless location.type is ScheduledEventLocationType.external, then end_time is required.

Will return a new ScheduledEvent object if applicable.

Параметры:
  • name (str) – The new name of the event.

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

  • location (str | int | VoiceChannel | StageChannel | ScheduledEventLocation) – The location of the event.

  • status (int | ScheduledEventStatus) – The status of the event. It is recommended, however, to use start(), complete(), and cancel() to edit statuses instead.

  • start_time (datetime) – The new starting time for the event.

  • end_time (datetime) – The new ending time of the event.

  • privacy_level (ScheduledEventPrivacyLevel) – The privacy level of the event. Currently, the only possible value is ScheduledEventPrivacyLevel.guild_only, which is default, so there is no need to change this parameter.

  • reason (str | None) – The reason to show in the audit log.

  • image (bytes | None) – The cover image of the scheduled event.

  • cover (bytes | None) –

    The cover image of the scheduled event.

    Устарело, начиная с версии 2.7: Use the image argument instead.

Результат:

The newly updated scheduled event object. This is only returned when certain fields are updated.

Тип результата:

ScheduledEvent | None

Исключение:
await delete()[исходный код]

This function is a coroutine.

Deletes the scheduled event.

Исключение:
Тип результата:

None

await start(*, reason=None)[исходный код]

This function is a coroutine.

Starts the scheduled event. Shortcut from edit().

Примечание

This method can only be used if status is ScheduledEventStatus.scheduled.

Параметры:

reason (str | None) – The reason to show in the audit log.

Результат:

The newly updated scheduled event object.

Тип результата:

None

Исключение:
await complete(*, reason=None)[исходный код]

This function is a coroutine.

Ends/completes the scheduled event. Shortcut from edit().

Примечание

This method can only be used if status is ScheduledEventStatus.active.

Параметры:

reason (str | None) – The reason to show in the audit log.

Результат:

The newly updated scheduled event object.

Тип результата:

None

Исключение:
await cancel(*, reason=None)[исходный код]

This function is a coroutine.

Cancels the scheduled event. Shortcut from edit().

Примечание

This method can only be used if status is ScheduledEventStatus.scheduled.

Параметры:

reason (str | None) – The reason to show in the audit log.

Результат:

The newly updated scheduled event object.

Тип результата:

None

Исключение:
subscribers(*, limit=100, as_member=False, before=None, after=None)[исходный код]

Returns an AsyncIterator representing the users or members subscribed to the event.

The after and before parameters must represent member or user objects and meet the abc.Snowflake abc.

Примечание

Even is as_member is set to True, if the user is outside the guild, it will be a User object.

Параметры:
  • limit (int | None) – The maximum number of results to return.

  • as_member (bool) – Whether to fetch Member objects instead of user objects. There may still be User objects if the user is outside the guild.

  • before (Snowflake | datetime | None) – Retrieves users before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieves users after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

Yields:

Union[User, Member] – The subscribed Member. If as_member is set to False or the user is outside the guild, it will be a User object.

Исключение:

HTTPException – Fetching the subscribed users failed.

Тип результата:

ScheduledEventSubscribersIterator

Примеры

Usage

async for user in event.subscribers(limit=100):
    print(user.name)

Flattening into a list:

users = await event.subscribers(limit=100).flatten()
# users is now a list of User...

Getting members instead of user objects:

async for member in event.subscribers(limit=100, as_member=True):
    print(member.display_name)
class discord.ScheduledEventLocation(*, state, value)[исходный код]

Represents a scheduled event’s location.

Setting the value to its corresponding type will set the location type automatically:

Добавлено в версии 2.0.

value

The actual location of the scheduled event.

Type:

Union[str, StageChannel, VoiceChannel, Object]

type

The type of location.

Type:

ScheduledEventLocationType

Параметры:
  • state (ConnectionState)

  • value (str | int | StageChannel | VoiceChannel)

Welcome Screen

Methods
class discord.WelcomeScreen(data, guild)[исходный код]

Represents the welcome screen of a guild.

Добавлено в версии 2.0.

description

The description text displayed on the welcome screen.

Type:

str

welcome_channels

A list of channels displayed on welcome screen.

Type:

List[WelcomeScreenChannel]

Параметры:
  • data (WelcomeScreen)

  • guild (Guild)

property enabled: bool

Indicates whether the welcome screen is enabled or not.

property guild: Guild

The guild this welcome screen belongs to.

await edit(**options)[исходный код]

This function is a coroutine.

Edits the welcome screen.

You must have the manage_guild permission in the guild to do this.

Параметры:
  • description (Optional[str]) – The new description of welcome screen.

  • welcome_channels (Optional[List[WelcomeScreenChannel]]) – The welcome channels. The order of the channels would be same as the passed list order.

  • enabled (Optional[bool]) – Whether the welcome screen should be displayed.

  • reason (Optional[str]) – The reason that shows up on Audit log.

Исключение:
  • HTTPException – Editing the welcome screen failed somehow.

  • Forbidden – You don’t have permissions to edit the welcome screen.

  • NotFound – This welcome screen does not exist.

Пример

rules_channel = guild.get_channel(12345678)
announcements_channel = guild.get_channel(87654321)
custom_emoji = utils.get(guild.emojis, name='loudspeaker')
await welcome_screen.edit(
    description='This is a very cool community server!',
    welcome_channels=[
        WelcomeChannel(channel=rules_channel, description='Read the rules!', emoji='👨‍🏫'),
        WelcomeChannel(channel=announcements_channel, description='Watch out for announcements!',
                       emoji=custom_emoji),
    ]
)

Примечание

Welcome channels can only accept custom emojis if premium_tier is level 2 or above.

class discord.WelcomeScreenChannel(channel, description, emoji)[исходный код]

Represents a welcome channel displayed on WelcomeScreen

Добавлено в версии 2.0.

channel

The channel that is being referenced.

Type:

abc.Snowflake

description

The description of the channel that is shown on the welcome screen.

Type:

str

emoji

The emoji of the channel that is shown on welcome screen.

Type:

Union[GuildEmoji, PartialEmoji, str]

Параметры:

Onboarding

class discord.Onboarding(data, guild)[исходный код]

Represents the onboarding flow for a guild.

Добавлено в версии 2.5.

prompts

A list of prompts displayed in the onboarding flow.

Type:

List[OnboardingPrompt]

enabled

Whether onboarding is enabled in the guild.

Type:

bool

mode

The current onboarding mode.

Type:

OnboardingMode

Параметры:
  • data (Onboarding)

  • guild (Guild)

property default_channels: list[TextChannel | ForumChannel | VoiceChannel | Object][исходный код]

The channels that members are opted into by default.

If a channel is not found in the guild’s cache, then it will be returned as an Object.

await edit(*, prompts=..., default_channels=..., enabled=..., mode=..., reason=...)[исходный код]

This function is a coroutine.

Edits this onboarding flow.

You must have the manage_guild and manage_roles permissions in the guild to do this.

Параметры:
  • prompts (list[OnboardingPrompt] | None) – The new list of prompts for this flow.

  • default_channels (list[Snowflake] | None) – The new default channels that users are opted into.

  • enabled (bool | None) – Whether onboarding should be enabled. Setting this to True requires the guild to have COMMUNITY in features and at least 7 default_channels.

  • mode (OnboardingMode | None) – The new onboarding mode.

  • reason (str | None) – The reason for editing this onboarding flow. Shows up on the audit log.

Результат:

The updated onboarding flow.

Тип результата:

Onboarding

Исключение:
  • HTTPException – Editing the onboarding flow failed somehow.

  • Forbidden – You don’t have permissions to edit the onboarding flow.

await add_prompt(type, title, options, single_select, required, in_onboarding, *, reason=None)[исходный код]

This function is a coroutine.

Adds a new onboarding prompt.

You must have the manage_guild and manage_roles permissions in the guild to do this.

Параметры:
  • type (PromptType) – The type of onboarding prompt.

  • title (str) – The prompt’s title.

  • options (list[PromptOption]) – The list of options available in the prompt.

  • single_select (bool) – Whether the user is limited to selecting one option on this prompt.

  • required (bool) – Whether the user is required to answer this prompt.

  • in_onboarding (bool) – Whether this prompt is displayed in the initial onboarding flow.

  • reason (str | None) – The reason for adding this prompt. Shows up on the audit log.

Результат:

The updated onboarding flow.

Тип результата:

Onboarding

Исключение:
  • HTTPException – Editing the onboarding flow failed somehow.

  • Forbidden – You don’t have permissions to edit the onboarding flow.

await append_prompt(prompt, *, reason=None)[исходный код]

This function is a coroutine.

Append an onboarding prompt onto this flow.

You must have the manage_guild and manage_roles permissions in the guild to do this.

Параметры:
  • prompt (OnboardingPrompt) – The onboarding prompt to append.

  • reason (str | None) – The reason for appending this prompt. Shows up on the audit log.

Результат:

The updated onboarding flow.

Тип результата:

Onboarding

Исключение:
  • HTTPException – Editing the onboarding flow failed somehow.

  • Forbidden – You don’t have permissions to edit the onboarding flow.

get_prompt(id)[исходный код]

This function is a coroutine.

Get an onboarding prompt with the given ID.

Параметры:

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

Результат:

The matching prompt, or None if it didn’t exist.

Тип результата:

OnboardingPrompt

await delete_prompt(id, *, reason=...)[исходный код]

This function is a coroutine.

Delete an onboarding prompt with the given ID.

You must have the manage_guild and manage_roles permissions in the guild to do this.

Параметры:
  • id (int) – The ID of the prompt to delete.

  • reason (str | None) – The reason for deleting this prompt. Shows up on the audit log.

Результат:

The updated onboarding flow.

Тип результата:

Onboarding

Исключение:
  • ValueError – No prompt with this ID exists.

  • HTTPException – Editing the onboarding flow failed somehow.

  • Forbidden – You don’t have permissions to edit the onboarding flow.

class discord.OnboardingPrompt(type, title, options, single_select, required, in_onboarding, id=None)[исходный код]

Represents an onboarding prompt displayed in Onboarding.

Добавлено в версии 2.5.

id

The id of the prompt.

Type:

int

type

The type of onboarding prompt.

Type:

PromptType

title

The prompt’s title.

Type:

str

options

The list of options available in the prompt.

Type:

List[PromptOption]

single_select

Whether the user is limited to selecting one option on this prompt.

Type:

bool

required

Whether the user is required to answer this prompt.

Type:

bool

in_onboarding

Whether this prompt is displayed in the initial onboarding flow.

Type:

bool

Параметры:
class discord.PromptOption(title, channels=None, roles=None, description=None, emoji=None, id=None)[исходный код]

Represents an onboarding prompt option displayed in OnboardingPrompt.

Добавлено в версии 2.5.

id

The id of the prompt option.

Type:

int

channels

The channels assigned to the user when they select this option.

Type:

List[Snowflake]

roles

The roles assigned to the user when they select this option.

Type:

List[Snowflake]

emoji

The emoji displayed with the option.

Type:

Union[GuildEmoji, PartialEmoji]

title

The option’s title.

Type:

str

description

The option’s description.

Type:

Optional[str]

Параметры:

Integration

class discord.Integration(*, data, guild)[исходный код]

Represents a guild integration.

Добавлено в версии 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

Параметры:
  • data (BaseIntegration | StreamIntegration | BotIntegration)

  • guild (Guild)

await delete(*, reason=None)[исходный код]

This function is a coroutine.

Deletes the integration.

You must have the manage_guild permission to do this.

Параметры:

reason (str | None) –

The reason the integration was deleted. Shows up on the audit log.

Добавлено в версии 2.0.

Исключение:
  • Forbidden – You do not have permission to delete the integration.

  • HTTPException – Deleting the integration failed.

Тип результата:

None

class discord.IntegrationAccount(data)[исходный код]

Represents an integration account.

Добавлено в версии 1.4.

id

The account ID.

Type:

str

name

The account name.

Type:

str

Параметры:

data (IntegrationAccount)

class discord.BotIntegration(*, data, guild)[исходный код]

Represents a bot integration on discord.

Добавлено в версии 2.0.

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

user

The user that added this integration.

Type:

User

account

The integration account information.

Type:

IntegrationAccount

application

The application tied to this integration.

Type:

IntegrationApplication

Параметры:
  • data (BaseIntegration | StreamIntegration | BotIntegration)

  • guild (Guild)

class discord.IntegrationApplication(*, data, state)[исходный код]

Represents an application for a bot integration.

Добавлено в версии 2.0.

id

The ID for this application.

Type:

int

name

The application’s name.

Type:

str

icon

The application’s icon hash.

Type:

Optional[str]

description

The application’s description. Can be an empty string.

Type:

str

summary

The summary of the application. Can be an empty string.

Type:

str

user

The bot user on this application.

Type:

Optional[User]

Параметры:

data (IntegrationApplication)

class discord.StreamIntegration(*, data, guild)[исходный код]

Represents a stream integration for Twitch or YouTube.

Добавлено в версии 2.0.

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

syncing

Where the integration is currently syncing.

Type:

bool

enable_emoticons

Whether emoticons should be synced for this integration (currently twitch only).

Type:

Optional[bool]

expire_behaviour

The behaviour of expiring subscribers. Aliased to expire_behavior as well.

Type:

ExpireBehaviour

expire_grace_period

The grace period (in days) for expiring subscribers.

Type:

int

user

The user for the integration.

Type:

User

account

The integration account information.

Type:

IntegrationAccount

synced_at

An aware UTC datetime representing when the integration was last synced.

Type:

datetime.datetime

Параметры:
  • data (BaseIntegration | StreamIntegration | BotIntegration)

  • guild (Guild)

property expire_behavior: ExpireBehaviour

An alias for expire_behaviour.

property role: Role | None

The role which the integration uses for subscribers.

await edit(*, expire_behaviour=..., expire_grace_period=..., enable_emoticons=...)[исходный код]

This function is a coroutine.

Edits the integration.

You must have the manage_guild permission to do this.

Параметры:
  • expire_behaviour (ExpireBehaviour) – The behaviour when an integration subscription lapses. Aliased to expire_behavior as well.

  • expire_grace_period (int) – The period (in days) where the integration will ignore lapsed subscriptions.

  • enable_emoticons (bool) – Where emoticons should be synced for this integration (currently twitch only).

Исключение:
Тип результата:

None

await sync()[исходный код]

This function is a coroutine.

Syncs the integration.

You must have the manage_guild permission to do this.

Исключение:
  • Forbidden – You do not have permission to sync the integration.

  • HTTPException – Syncing the integration failed.

Тип результата:

None

Widget

class discord.Widget(*, state, data)[исходный код]

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:

List[WidgetChannel]

members

The online members in the server. Offline members do not appear in the widget.

Примечание

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:

List[Member]

Параметры:
  • state (ConnectionState)

  • data (Widget)

property created_at: datetime

Returns the member’s creation time in UTC.

property json_url: str

The JSON URL of the widget.

property invite_url: str

The invite URL for the guild, if available.

await fetch_invite(*, with_counts=True)[исходный код]

This function is a coroutine.

Retrieves an Invite from the widget’s invite URL. This is the same as Client.fetch_invite(); the invite code is abstracted away.

Параметры:

with_counts (bool) – Whether to include count information in the invite. This fills the Invite.approximate_member_count and Invite.approximate_presence_count fields.

Результат:

The invite from the widget’s invite URL.

Тип результата:

Invite

class discord.WidgetChannel(id, name, position)[исходный код]

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: str

The string that allows you to mention the channel.

property created_at: datetime

Returns the channel’s creation time in UTC.

class discord.WidgetMember(*, state, data, connected_channel=None)[исходный код]

Represents a «partial» member of the widget’s guild.

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 widget member’s name#discriminator.

id

The member’s ID.

Type:

int

name

The member’s username.

Type:

str

discriminator

The member’s discriminator.

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[WidgetChannel]

Параметры:
  • state (ConnectionState)

  • data (WidgetMember)

  • connected_channel (WidgetChannel | None)

property display_name: str

Returns the member’s display name.

property accent_color: Colour | None

Returns the user’s accent color, if applicable.

There is an alias for this named accent_colour.

Добавлено в версии 2.0.

Примечание

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

property accent_colour: Colour | None

Returns the user’s accent colour, if applicable.

There is an alias for this named accent_color.

Добавлено в версии 2.0.

Примечание

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

property avatar_decoration: Asset | None

Returns the user’s avatar decoration, if available.

Добавлено в версии 2.5.

property banner: Asset | None

Returns the user’s banner asset, if available.

Добавлено в версии 2.0.

Примечание

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

property collectibles: Collectibles | None

Returns the user’s equipped collectibles.

Добавлено в версии 2.8.

property color: Colour

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

There is an alias for this named colour.

property colour: Colour

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

There is an alias for this named color.

property created_at: datetime

Returns the user’s creation time in UTC.

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

property default_avatar: Asset

Returns the default avatar for a given user. This is calculated by the user’s ID if they’re on the new username system, otherwise their discriminator.

property display_avatar: Asset

Returns the user’s display avatar.

Returns the user’s uploaded avatar. If the user has not uploaded any avatar, their default avatar is returned instead.

Добавлено в версии 2.0.

property is_migrated: bool

Checks whether the user is already migrated to global name.

property jump_url: str

Returns a URL that allows the client to jump to the user.

Добавлено в версии 2.0.

property mention: str

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

mentioned_in(message)

Checks if the user is mentioned in the specified message.

Параметры:

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

Результат:

Indicates if the user is mentioned in the message.

Тип результата:

bool

property nameplate: Nameplate | None

The user’s nameplate, if the user has one equipped. Alias for User.collectibles.nameplate.

Добавлено в версии 2.7.

Изменено в версии 2.8: Now an alias for User.collectibles.nameplate.

property public_flags: PublicUserFlags

The publicly available flags the user has.

Threads

class discord.Thread(*, guild, state, data)[исходный код]

Represents a Discord thread.

x == y

Checks if two threads are equal.

x != y

Checks if two threads are not equal.

hash(x)

Returns the thread’s hash.

str(x)

Returns the thread’s name.

Добавлено в версии 2.0.

name

The thread name.

Type:

str

guild

The guild the thread belongs to.

Type:

Guild

id

The thread ID.

Примечание

This ID is the same as the thread starting message ID.

Type:

int

parent_id

The parent TextChannel ID this thread belongs to.

Type:

int

owner_id

The user’s ID that created this thread.

Type:

int

last_message_id

The last message ID of the message sent to this thread. 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 thread. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode.

Type:

int

message_count

An approximate number of messages in this thread. This caps at 50.

Type:

int

member_count

An approximate number of members in this thread. This caps at 50.

Type:

int

me

A thread member representing yourself, if you’ve joined the thread. This could not be available.

Type:

Optional[ThreadMember]

archived

Whether the thread is archived.

Type:

bool

locked

Whether the thread is locked.

Type:

bool

invitable

Whether non-moderators can add other non-moderators to this thread. This is always True for public threads.

Type:

bool

auto_archive_duration

The duration in minutes until the thread is automatically archived due to inactivity. Usually a value of 60, 1440, 4320 and 10080.

Type:

int

archive_timestamp

An aware timestamp of when the thread’s archived status was last updated in UTC.

Type:

datetime.datetime

created_at

An aware timestamp of when the thread was created. Only available for threads created after 2022-01-09.

Type:

Optional[datetime.datetime]

flags

Extra features of the thread.

Добавлено в версии 2.0.

Type:

ChannelFlags

total_message_sent

Number of messages ever sent in a thread. It’s similar to message_count on message creation, but will not decrement the number when a message is deleted.

Добавлено в версии 2.3.

Type:

int

Параметры:
  • guild (Guild)

  • state (ConnectionState)

  • data (Thread)

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.

Параметры:
  • limit (int | None) – 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 (Snowflake | datetime | None) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Snowflake | datetime | None) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.

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

Yields:

Message – The message with the message data parsed.

Исключение:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Тип результата:

HistoryIterator

Примеры

Usage

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

Flattening into a list:

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

All parameters are optional.

async with typing()

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

This is useful for denoting long computations in your bot.

Примечание

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():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
Тип результата:

Typing

property type: ChannelType

The channel’s Discord type.

property parent: TextChannel | ForumChannel | None

The parent channel this thread belongs to.

property owner: Member | None

The member this thread belongs to.

property mention: str

The string that allows you to mention the thread.

property jump_url: str

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

Добавлено в версии 2.0.

property members: list[ThreadMember]

A list of thread members in this thread, including the bot if it is a member of this thread.

This requires Intents.members to be properly filled. Most of the time however, this data is not provided by the gateway and a call to fetch_members() is needed.

property applied_tags: list[ForumTag]

A list of tags applied to this thread.

This is only available for threads in forum or media channels.

Type:

List[ForumTag]

property last_message: Message | None

Returns the last message from this thread 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.

Результат:

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

Тип результата:

Optional[Message]

property category: CategoryChannel | None

The category channel the parent channel belongs to, if applicable.

Результат:

The parent channel’s category.

Тип результата:

Optional[CategoryChannel]

Исключение:

ClientException – The parent channel was not cached and returned None.

property category_id: int | None

The category channel ID the parent channel belongs to, if applicable.

Результат:

The parent channel’s category ID.

Тип результата:

Optional[int]

Исключение:

ClientException – The parent channel was not cached and returned None.

property starting_message: Message | None

Returns the message that started this thread.

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

Примечание

The ID for this message is the same as the thread ID.

Результат:

The message that started this thread or None if not found in the cache.

Тип результата:

Optional[Message]

is_pinned()[исходный код]

Whether the thread is pinned to the top of its parent forum or media channel.

Добавлено в версии 2.3.

Тип результата:

bool

is_private()[исходный код]

Whether the thread is a private thread.

A private thread is only viewable by those that have been explicitly invited or have manage_threads.

Тип результата:

bool

is_news()[исходный код]

Whether the thread is a news thread.

A news thread is a thread that has a parent that is a news channel, i.e. TextChannel.is_news() is True.

Тип результата:

bool

is_nsfw()[исходный код]

Whether the thread is NSFW or not.

An NSFW thread is a thread that has a parent that is an NSFW channel, i.e. TextChannel.is_nsfw() is True.

Тип результата:

bool

permissions_for(obj, /)[исходный код]

Handles permission resolution for the Member or Role.

Since threads do not have their own permissions, they inherit them from the parent channel. This is a convenience method for calling permissions_for() on the parent channel.

Параметры:

obj (Member | Role) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

Результат:

The resolved permissions for the member or role.

Тип результата:

Permissions

Исключение:

ClientException – The parent channel was not cached and returned None

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.

Параметры:
  • messages (Iterable[Snowflake]) – An iterable of messages denoting which ones to bulk delete.

  • reason (str | None) – The reason for deleting the messages. Shows up on the audit log.

Исключение:
  • 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.

Тип результата:

None

await purge(*, limit=100, check=..., 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.

Параметры:
Результат:

The list of messages that were deleted.

Тип результата:

list[Message]

Исключение:
  • Forbidden – You do not have proper permissions to do the actions required.

  • HTTPException – Purging the messages failed.

Примеры

Deleting bot’s messages

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

deleted = await thread.purge(limit=100, check=is_me)
await thread.send(f'Deleted {len(deleted)} message(s)')
await edit(*, name=..., archived=..., locked=..., invitable=..., slowmode_delay=..., auto_archive_duration=..., pinned=..., applied_tags=..., reason=None)[исходный код]

This function is a coroutine.

Edits the thread.

Editing the thread requires Permissions.manage_threads. The thread creator can also edit name, archived or auto_archive_duration. Note that if the thread is locked then only those with Permissions.manage_threads can send messages in it or unarchive a thread.

The thread must be unarchived to be edited.

Параметры:
  • name (str) – The new name of the thread.

  • archived (bool) – Whether to archive the thread or not.

  • locked (bool) – Whether to lock the thread or not.

  • invitable (bool) – Whether non-moderators can add other non-moderators to this thread. Only available for private threads.

  • auto_archive_duration (Literal[60, 1440, 4320, 10080] | ThreadArchiveDuration) – The new duration in minutes before a thread is automatically archived for inactivity. Must be one of 60, 1440, 4320, or 10080. ThreadArchiveDuration can be used alternatively.

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

  • reason (str | None) – The reason for editing this thread. Shows up on the audit log.

  • pinned (bool) – Whether to pin the thread or not. This only works if the thread is part of a forum or media channel.

  • applied_tags (list[ForumTag]) –

    The set of tags to apply to the thread. Each tag object should have an ID set.

    Добавлено в версии 2.3.

Результат:

The newly edited thread.

Тип результата:

Thread

Исключение:
await archive(locked=...)[исходный код]

This function is a coroutine.

Archives the thread. This is a shorthand of edit().

Параметры:

locked (bool) – Whether to lock the thread on archive, Defaults to False.

Результат:

The updated thread.

Тип результата:

Thread

await unarchive()[исходный код]

This function is a coroutine.

Unarchives the thread. This is a shorthand of edit().

Результат:

The updated thread.

Тип результата:

Thread

await join()[исходный код]

This function is a coroutine.

Joins this thread.

You must have send_messages_in_threads to join a thread. If the thread is private, manage_threads is also needed.

Исключение:
await leave()[исходный код]

This function is a coroutine.

Leaves this thread.

Исключение:

HTTPException – Leaving the thread failed.

await add_user(user)[исходный код]

This function is a coroutine.

Adds a user to this thread.

You must have send_messages_in_threads to add a user to a public thread. If the thread is private and invitable is False, then manage_threads is required.

Параметры:

user (Snowflake) – The user to add to the thread.

Исключение:
  • Forbidden – You do not have permissions to add the user to the thread.

  • HTTPException – Adding the user to the thread failed.

await remove_user(user)[исходный код]

This function is a coroutine.

Removes a user from this thread.

You must have manage_threads or be the creator of the thread to remove a user.

Параметры:

user (Snowflake) – The user to remove from the thread.

Исключение:
  • Forbidden – You do not have permissions to remove the user from the thread.

  • HTTPException – Removing the user from the thread failed.

await fetch_members()[исходный код]

This function is a coroutine.

Retrieves all ThreadMember that are in this thread.

This requires Intents.members to get information about members other than yourself.

Результат:

All thread members in the thread.

Тип результата:

list[ThreadMember]

Исключение:

HTTPException – Retrieving the members failed.

await delete()[исходный код]

This function is a coroutine.

Deletes this thread.

You must have manage_threads to delete threads.

Исключение:
  • Forbidden – You do not have permissions to delete this thread.

  • HTTPException – Deleting the thread failed.

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.

Добавлено в версии 2.0.

Параметры:

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

Результат:

The partial message.

Тип результата:

PartialMessage

can_send(*objects)

Returns a bool indicating whether you have the permissions to send the object(s).

Результат:

Indicates whether you have the permissions to send the object(s).

Тип результата:

bool

Исключение:

TypeError – An invalid type has been passed.

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

Параметры:

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

Результат:

The message asked for.

Тип результата:

Message

Исключение:
  • NotFound – The specified message was not found.

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

  • HTTPException – Retrieving the message failed.

pins(*, limit=50, before=None)

Returns a MessagePinIterator that enables receiving the destination’s pinned messages.

You must have read_message_history permissions to use this.

Предупреждение

Starting from version 3.0, await channel.pins() will no longer return a list of Message. See examples below for new usage instead.

Параметры:
  • limit (int | None) – The number of pinned messages to retrieve. If None, retrieves every pinned message in the channel.

  • before (Snowflake | datetime | None) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

Yields:

MessagePin – The pinned message.

Исключение:
  • Forbidden – You do not have permissions to get pinned messages.

  • HTTPException – The request to get pinned messages failed.

Тип результата:

MessagePinIterator

Примеры

Usage

counter = 0
async for pin in channel.pins(limit=250):
    if pin.message.author == client.user:
        counter += 1

Flattening into a list:

pins = await channel.pins(limit=None).flatten()
# pins is now a list of MessagePin...

All parameters are optional.

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, suppress_embeds=None, silent=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Параметры:
  • content (Optional[str]) – The content of the message to send.

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

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

  • file (File) – The file to upload.

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

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

  • enforce_nonce (Optional[bool]) –

    Whether nonce is enforced to be validated.

    Добавлено в версии 2.5.

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

  • allowed_mentions (AllowedMentions) –

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

    Добавлено в версии 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message being replied to or forwarded. This can be created using to_reference(). When replying, 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.

    Добавлено в версии 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    Добавлено в версии 1.6.

  • view (discord.ui.BaseView) – A Discord UI View to add to the message.

  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    Добавлено в версии 2.0.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    Добавлено в версии 2.0.

  • suppress (bool) –

    Whether to suppress embeds for the message.

    Устарело, начиная с версии 2.8.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message.

    Добавлено в версии 2.8.

  • silent (bool) –

    Whether to suppress push and desktop notifications for the message.

    Добавлено в версии 2.4.

  • poll (Poll) –

    The poll to send.

    Добавлено в версии 2.6.

Результат:

The message that was sent.

Тип результата:

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.

Тип результата:

None

class discord.ThreadMember(parent, data)[исходный код]

Represents a Discord thread member.

x == y

Checks if two thread members are equal.

x != y

Checks if two thread members are not equal.

hash(x)

Returns the thread member’s hash.

str(x)

Returns the thread member’s name.

Добавлено в версии 2.0.

id

The thread member’s ID.

Type:

int

thread_id

The thread’s ID.

Type:

int

joined_at

The time the member joined the thread in UTC.

Type:

datetime.datetime

Параметры:
  • parent (Thread)

  • data (ThreadMember)

property thread: Thread

The thread this member belongs to.

Stages

class discord.StageChannel(*, state, guild, data)[исходный код]

Represents a Discord guild stage channel.

Добавлено в версии 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]

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. Can be None if the channel was received in an interaction.

Type:

Optional[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]

video_quality_mode

The camera video quality for the stage channel’s participants.

Добавлено в версии 2.0.

Type:

VideoQualityMode

flags

Extra features of the channel.

Добавлено в версии 2.0.

Type:

ChannelFlags

last_message_id

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

Type:

Optional[int]

slowmode_delay

Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is 21600.

Type:

int

nsfw

Whether the channel is marked as NSFW.

Добавлено в версии 2.7.

Type:

bool

Параметры:
  • state (ConnectionState)

  • guild (Guild)

  • data (VoiceChannel | StageChannel)

property requesting_to_speak: list[Member]

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

property speakers: list[Member]

A list of members who have been permitted to speak in the stage channel.

Добавлено в версии 2.0.

property listeners: list[Member]

A list of members who are listening in the stage channel.

Добавлено в версии 2.0.

is_nsfw()[исходный код]

Checks if the channel is NSFW.

Тип результата:

bool

property last_message: Message | None

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.

Результат:

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

Тип результата:

Optional[Message]

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.

Добавлено в версии 1.6.

Параметры:

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

Результат:

The partial message.

Тип результата:

PartialMessage

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.

Параметры:
  • messages (Iterable[Snowflake]) – An iterable of messages denoting which ones to bulk delete.

  • reason (str | None) – The reason for deleting the messages. Shows up on the audit log.

Исключение:
  • ClientException – The number of messages to delete was more than 100.

  • Forbidden – You do not have proper permissions to delete the messages.

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

  • HTTPException – Deleting the messages failed.

Тип результата:

None

await purge(*, limit=100, check=..., 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. The read_message_history permission is also needed to retrieve message history.

Параметры:
Результат:

The list of messages that were deleted.

Тип результата:

list[Message]

Исключение:
  • Forbidden – You do not have proper permissions to do the actions required.

  • HTTPException – Purging the messages failed.

Примеры

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(f'Deleted {len(deleted)} message(s)')
await webhooks()[исходный код]

This function is a coroutine.

Gets the list of webhooks from this channel.

Requires manage_webhooks permissions.

Результат:

The webhooks for this channel.

Тип результата:

list[Webhook]

Исключение:

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

await create_webhook(*, name, avatar=None, reason=None)[исходный код]

This function is a coroutine.

Creates a webhook for this channel.

Requires manage_webhooks permissions.

Изменено в версии 1.1: Added the reason keyword-only parameter.

Параметры:
  • name (str) – The webhook’s name.

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

  • reason (str | None) – The reason for creating this webhook. Shows up in the audit logs.

Результат:

The created webhook.

Тип результата:

Webhook

Исключение:
  • HTTPException – Creating the webhook failed.

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

property moderators: list[Member]

A list of members who are moderating the stage channel.

Добавлено в версии 2.0.

property type: ChannelType

The channel’s Discord type.

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.

Добавлено в версии 1.1.

Параметры:
  • name (str | None) – The name of the new channel. If not provided, defaults to this channel name.

  • reason (str | None) – The reason for cloning this channel. Shows up on the audit log.

Результат:

The channel that was created.

Тип результата:

StageChannel

Исключение:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

property instance: StageInstance | None

The running stage instance of the stage channel.

Добавлено в версии 2.0.

await create_instance(*, topic, privacy_level=..., reason=None, send_notification=False)[исходный код]

This function is a coroutine.

Create a stage instance.

You must have the manage_channels permission to use this.

Добавлено в версии 2.0.

Параметры:
  • topic (str) – The stage instance’s topic.

  • privacy_level (StagePrivacyLevel) – The stage instance’s privacy level. Defaults to StagePrivacyLevel.guild_only.

  • reason (str | None) – The reason the stage instance was created. Shows up on the audit log.

  • send_notification (bool | None) – Send a notification to everyone in the server that the stage instance has started. Defaults to False. Requires the mention_everyone permission.

Результат:

The newly created stage instance.

Тип результата:

StageInstance

Исключение:
  • InvalidArgument – If the privacy_level parameter is not the proper type.

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

  • HTTPException – Creating a stage instance failed.

await fetch_instance()[исходный код]

This function is a coroutine.

Gets the running StageInstance.

Добавлено в версии 2.0.

Результат:

The stage instance.

Тип результата:

StageInstance

Исключение:
  • NotFound – The stage instance or channel could not be found.

  • HTTPException – Getting the stage instance failed.

await edit(*, reason=None, **options)[исходный код]

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

Изменено в версии 2.0: The topic parameter must now be set via create_instance.

Изменено в версии 2.0: Edits are no longer in-place, the newly edited channel is returned instead.

Параметры:
  • name (str) – The new channel’s name.

  • 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[Union[Role, Member, Snowflake], PermissionOverwrite]) – The overwrites to apply to channel permissions. Useful for creating secret channels.

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

  • video_quality_mode (VideoQualityMode) –

    The camera video quality for the stage channel’s participants.

    Добавлено в версии 2.0.

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

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

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

Результат:

The newly edited stage channel. If the edit was only positional then None is returned instead.

Тип результата:

Optional[StageChannel]

Исключение:
  • 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.

can_send(*objects)

Returns a bool indicating whether you have the permissions to send the object(s).

Результат:

Indicates whether you have the permissions to send the object(s).

Тип результата:

bool

Исключение:

TypeError – An invalid type has been passed.

property category: CategoryChannel | None

The category this channel belongs to.

If there is no category then this is None.

property changed_roles: list[Role]

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

await connect(*, timeout=60.0, reconnect=True, cls=...)

This function is a coroutine.

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

This requires Intents.voice_states.

Параметры:
  • 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 (Callable[[Client, Connectable], TypeVar(T, bound= VoiceProtocol)]) – A type that subclasses VoiceProtocol to connect with. Defaults to VoiceClient.

Результат:

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

Тип результата:

TypeVar(T, bound= VoiceProtocol)

Исключение:
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, roles=None, target_users_file=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.

Параметры:
  • 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 (str | None) – The reason for creating this invite. Shows up on the audit log.

  • target_type (InviteTarget | None) –

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

    Добавлено в версии 2.0.

  • target_user (User | None) –

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

    Добавлено в версии 2.0.

  • target_application_id (int | None) –

    The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    Добавлено в версии 2.0.

  • target_event (ScheduledEvent | None) –

    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.

    Добавлено в версии 2.0.

  • roles (list[Role | Object] | None) –

    The roles to give a user when joining through this invite.

    You must have the manage_roles permission to do this and roles cannot be higher than your own.

    Добавлено в версии 2.8.

  • target_users_file (File | None) –

    A CSV file with a single column of user IDs for all the users able to accept this invite.

    You can use utils.users_to_csv() to generate a virtual CSV file from a sequence of user IDs.

    Добавлено в версии 2.8.

Результат:

The invite that was created.

Тип результата:

Invite

Исключение:
  • HTTPException – Invite creation failed.

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

property created_at: datetime

Returns the channel’s creation time in UTC.

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

Параметры:

reason (str | None) – The reason for deleting this channel. Shows up on the audit log.

Исключение:
  • 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.

Тип результата:

None

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

Параметры:

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

Результат:

The message asked for.

Тип результата:

Message

Исключение:
  • NotFound – The specified message was not found.

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

  • HTTPException – Retrieving the message failed.

history(*, limit=100, before=None, after=None, around=None, oldest_first=None)

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

You must have read_message_history permissions to use this.

Параметры:
  • limit (int | None) – 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 (Snowflake | datetime | None) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Snowflake | datetime | None) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.

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

Yields:

Message – The message with the message data parsed.

Исключение:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Тип результата:

HistoryIterator

Примеры

Usage

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

Flattening into a list:

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

All parameters are optional.

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

Результат:

The list of invites that are currently active.

Тип результата:

list[Invite]

Исключение:
  • Forbidden – You do not have proper permissions to get the information.

  • HTTPException – An error occurred while fetching the information.

property jump_url: str

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

Добавлено в версии 2.0.

property members: list[Member]

Returns all members that are currently inside this voice channel.

property mention: str

The string that allows you to mention the channel.

await move(**kwargs)

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.

Примечание

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

Добавлено в версии 1.7.

Параметры:
  • 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.

Исключение:
  • InvalidArgument – An invalid position was given or a bad mix of arguments was passed.

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

  • HTTPException – Moving the channel failed.

Тип результата:

None

property overwrites: dict[Role | Member, PermissionOverwrite]

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.

Результат:

The channel’s permission overwrites.

Тип результата:

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

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

Параметры:

obj (Role | User) – The role or user denoting whose overwrite to get.

Результат:

The permission overwrites for this object.

Тип результата:

PermissionOverwrite

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Изменено в версии 2.0: The object passed in can now be a role object.

Параметры:

obj (Member | Role) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

Результат:

The resolved permissions for the member or role.

Тип результата:

Permissions

property permissions_synced: bool

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

If there is no category then this is False.

Добавлено в версии 1.3.

pins(*, limit=50, before=None)

Returns a MessagePinIterator that enables receiving the destination’s pinned messages.

You must have read_message_history permissions to use this.

Предупреждение

Starting from version 3.0, await channel.pins() will no longer return a list of Message. See examples below for new usage instead.

Параметры:
  • limit (int | None) – The number of pinned messages to retrieve. If None, retrieves every pinned message in the channel.

  • before (Snowflake | datetime | None) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

Yields:

MessagePin – The pinned message.

Исключение:
  • Forbidden – You do not have permissions to get pinned messages.

  • HTTPException – The request to get pinned messages failed.

Тип результата:

MessagePinIterator

Примеры

Usage

counter = 0
async for pin in channel.pins(limit=250):
    if pin.message.author == client.user:
        counter += 1

Flattening into a list:

pins = await channel.pins(limit=None).flatten()
# pins is now a list of MessagePin...

All parameters are optional.

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, suppress_embeds=None, silent=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Параметры:
  • content (Optional[str]) – The content of the message to send.

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

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

  • file (File) – The file to upload.

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

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

  • enforce_nonce (Optional[bool]) –

    Whether nonce is enforced to be validated.

    Добавлено в версии 2.5.

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

  • allowed_mentions (AllowedMentions) –

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

    Добавлено в версии 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message being replied to or forwarded. This can be created using to_reference(). When replying, 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.

    Добавлено в версии 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    Добавлено в версии 1.6.

  • view (discord.ui.BaseView) – A Discord UI View to add to the message.

  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    Добавлено в версии 2.0.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    Добавлено в версии 2.0.

  • suppress (bool) –

    Whether to suppress embeds for the message.

    Устарело, начиная с версии 2.8.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message.

    Добавлено в версии 2.8.

  • silent (bool) –

    Whether to suppress push and desktop notifications for the message.

    Добавлено в версии 2.4.

  • poll (Poll) –

    The poll to send.

    Добавлено в версии 2.6.

Результат:

The message that was sent.

Тип результата:

Message

Исключение:
await set_permissions(target, *, overwrite=..., 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.

Примечание

This method replaces the old overwrites with the ones given.

Примеры

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)
Параметры:
  • 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.

Исключение:
  • 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.

Тип результата:

None

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.

Примечание

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():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
Тип результата:

Typing

property voice_states: dict[int, VoiceState]

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

Добавлено в версии 1.3.

Примечание

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

Результат:

The mapping of member ID to a voice state.

Тип результата:

Mapping[int, VoiceState]

class discord.StageInstance(*, state, guild, data)[исходный код]

Represents a stage instance of a stage channel in a guild.

Добавлено в версии 2.0.

x == y

Checks if two stage instances are equal.

x != y

Checks if two stage instances are not equal.

hash(x)

Returns the stage instance’s hash.

id

The stage instance’s ID.

Type:

int

guild

The guild that the stage instance is running in.

Type:

Guild

channel_id

The ID of the channel that the stage instance is running in.

Type:

int

topic

The topic of the stage instance.

Type:

str

privacy_level

The privacy level of the stage instance.

Type:

StagePrivacyLevel

discoverable_disabled

Whether discoverability for the stage instance is disabled.

Type:

bool

scheduled_event

The scheduled event linked with the stage instance, if any.

Type:

Optional[ScheduledEvent]

Параметры:
  • state (ConnectionState)

  • guild (Guild)

  • data (StageInstance)

channel

The channel that stage instance is running in.

await edit(*, topic=..., privacy_level=..., reason=None)[исходный код]

This function is a coroutine.

Edits the stage instance.

You must have the manage_channels permission to use this.

Параметры:
  • topic (str) – The stage instance’s new topic.

  • privacy_level (StagePrivacyLevel) – The stage instance’s new privacy level.

  • reason (str | None) – The reason the stage instance was edited. Shows up on the audit log.

Исключение:
  • InvalidArgument – If the privacy_level parameter is not the proper type.

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

  • HTTPException – Editing a stage instance failed.

Тип результата:

None

await delete(*, reason=None)[исходный код]

This function is a coroutine.

Deletes the stage instance.

You must have the manage_channels permission to use this.

Параметры:

reason (str | None) – The reason the stage instance was deleted. Shows up on the audit log.

Исключение:
  • Forbidden – You do not have permissions to delete the stage instance.

  • HTTPException – Deleting the stage instance failed.

Тип результата:

None

Interactions

class discord.Interaction(*, data, state)[исходный код]

Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are application commands, components, and modals.

Добавлено в версии 2.0.

id

The interaction’s ID.

Type:

int

type

The interaction type.

Type:

InteractionType

guild_id

The guild ID the interaction was sent from.

Type:

Optional[int]

channel

The channel the interaction was sent from.

Type:

Optional[Union[abc.GuildChannel, abc.PrivateChannel, Thread, PartialMessageable]]

channel_id

The ID of the channel the interaction was sent from.

Type:

Optional[int]

application_id

The application ID that the interaction was for.

Type:

int

user

The user or member that sent the interaction. Will be None in PING interactions.

Type:

Optional[Union[User, Member]]

message

The message that sent this interaction.

Type:

Optional[Message]

token

The token to continue the interaction. These are valid for 15 minutes.

Type:

str

data

The raw interaction data.

Type:

dict

locale

The user’s locale.

Type:

str

guild_locale

The guilds preferred locale, if invoked in a guild.

Type:

str

custom_id

The custom ID for the interaction.

Type:

Optional[str]

entitlements

Entitlements that apply to the invoking user, showing access to premium SKUs.

Добавлено в версии 2.5.

Type:

list[Entitlement]

authorizing_integration_owners

Contains the entities (users or guilds) that authorized this interaction.

Добавлено в версии 2.6.

Type:

AuthorizingIntegrationOwners

context

The context in which this command was executed.

Добавлено в версии 2.6.

Type:

Optional[InteractionContextType]

callback

The callback of the interaction. Contains information about the status of the interaction response. Will be None until the interaction is responded to.

Добавлено в версии 2.7.

Type:

Optional[InteractionCallback]

command

The command that this interaction belongs to.

Добавлено в версии 2.7.

Type:

Optional[ApplicationCommand]

view

The view that this interaction belongs to.

Добавлено в версии 2.7.

Type:

Optional[BaseView]

modal

The modal that this interaction belongs to.

Добавлено в версии 2.7.

Type:

Optional[BaseModal]

attachment_size_limit

The attachment size limit.

Добавлено в версии 2.7.

Type:

int

Параметры:
  • data (Interaction)

  • state (ConnectionState)

property client: Client

Returns the client that sent the interaction.

property guild: Guild | None

The guild the interaction was sent from.

property created_at: datetime

Returns the interaction’s creation time in UTC.

is_command()[исходный код]

Indicates whether the interaction is an application command.

Тип результата:

bool

is_component()[исходный код]

Indicates whether the interaction is a message component.

Тип результата:

bool

property cached_channel: VoiceChannel | StageChannel | TextChannel | ForumChannel | CategoryChannel | Thread | DMChannel | GroupChannel | PartialMessageable | None

The cached channel from which the interaction was sent. DM channels are not resolved. These are PartialMessageable instead.

Устарело, начиная с версии 2.7.

property permissions: Permissions

The resolved permissions of the member in the channel, including overwrites.

In a non-guild context where this doesn’t apply, an empty permissions object is returned.

app_permissions

The resolved permissions of the application in the channel, including overwrites.

response

Returns an object responsible for handling responding to the interaction.

A response can only be done once. If secondary messages need to be sent, consider using followup instead.

followup

Returns the followup webhook for followup interactions.

is_guild_authorised()[исходный код]

bool: Checks if the interaction is guild authorised.

There is an alias for this called is_guild_authorized().

Добавлено в версии 2.7.

Тип результата:

bool

is_user_authorised()[исходный код]

bool: Checks if the interaction is user authorised.

There is an alias for this called is_user_authorized().

Добавлено в версии 2.7.

Тип результата:

bool

is_guild_authorized()[исходный код]

bool: Checks if the interaction is guild authorized.

There is an alias for this called is_guild_authorised().

Добавлено в версии 2.7.

Тип результата:

bool

is_user_authorized()[исходный код]

bool: Checks if the interaction is user authorized.

There is an alias for this called is_user_authorised().

Добавлено в версии 2.7.

Тип результата:

bool

await original_response()[исходный код]

This function is a coroutine.

Fetches the original interaction response message associated with the interaction.

If the interaction response was InteractionResponse.send_message() then this would return the message that was sent using that response. Otherwise, this would return the message that triggered the interaction.

Repeated calls to this will return a cached value.

Результат:

The original interaction response message.

Тип результата:

InteractionMessage

Исключение:
await original_message()[исходный код]

An alias for original_response().

Результат:

The original interaction response message.

Тип результата:

InteractionMessage

Исключение:
await edit_original_response(*, content=..., embeds=..., embed=..., file=..., files=..., attachments=..., view=..., allowed_mentions=None, delete_after=None, suppress=None, suppress_embeds=None)[исходный код]

This function is a coroutine.

Edits the original interaction response message.

This is a lower level interface to InteractionMessage.edit() in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.

Параметры:
  • content (str | None) – The content to edit the message with or None to clear it.

  • embeds (list[Embed]) – A list of embeds to edit the message with.

  • embed (Embed | None) – The embed to edit the message with. None suppresses the embeds. This should not be mixed with the embeds parameter.

  • file (File) – The file to upload. This cannot be mixed with files parameter.

  • files (list[File]) – A list of files to send with the content. This cannot be mixed with the file parameter.

  • attachments (list[Attachment]) – A list of attachments to keep in the message. If [] is passed then all attachments are removed.

  • allowed_mentions (AllowedMentions | None) – Controls the mentions being processed in this message. See abc.Messageable.send() for more information.

  • view (BaseView | None) – The updated view to update this message with. If None is passed then the view is removed.

  • delete_after (float | None) – 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.

  • suppress (bool | None) –

    Whether to suppress embeds for the message.

    Устарело, начиная с версии 2.8.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message.

    Добавлено в версии 2.8.

Результат:

The newly edited message.

Тип результата:

InteractionMessage

Исключение:
  • HTTPException – Editing the message failed.

  • Forbidden – Edited a message that is not yours.

  • TypeError – You specified both embed and embeds or file and files

  • ValueError – The length of embeds was invalid.

await edit_original_message(**kwargs)[исходный код]

An alias for edit_original_response().

Результат:

The newly edited message.

Тип результата:

InteractionMessage

Исключение:
  • HTTPException – Editing the message failed.

  • Forbidden – Edited a message that is not yours.

  • TypeError – You specified both embed and embeds or file and files

  • ValueError – The length of embeds was invalid.

await delete_original_response(*, delay=None)[исходный код]

This function is a coroutine.

Deletes the original interaction response message.

This is a lower level interface to InteractionMessage.delete() in case you do not want to fetch the message and save an HTTP request.

Параметры:

delay (float | None) – If provided, the number of seconds to wait before deleting the message. The waiting is done in the background and deletion failures are ignored.

Исключение:
Тип результата:

None

await delete_original_message(**kwargs)[исходный код]

An alias for delete_original_response().

Исключение:
await respond(*args, **kwargs)[исходный код]

This function is a coroutine.

Sends either a response or a message using the followup webhook determined by whether the interaction has been responded to or not.

Параметры:
  • content (Optional[str]) – The content of the message to send.

  • embeds (List[Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the embed parameter.

  • embed (Embed) – The rich embed for the content to send. This cannot be mixed with embeds parameter.

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

  • view (discord.ui.BaseView) – The view to send with the message.

  • ephemeral (bool) – Indicates if the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message, and it has no timeout set then the timeout is set to 15 minutes.

  • allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message. See abc.Messageable.send() for more information.

  • delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent.

  • file (File) – The file to upload.

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

  • poll (Poll) –

    The poll to send.

    Добавлено в версии 2.6.

  • silent (bool) –

    Whether to suppress push and desktop notifications for the message.

    Добавлено в версии 2.8.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message.

    Добавлено в версии 2.8.

Результат:

The response, its type depending on whether it’s an interaction response or a followup.

Тип результата:

Interaction | WebhookMessage

await edit(*args, **kwargs)[исходный код]

This function is a coroutine.

Either respond to the interaction with an edit_message or edits the existing response, determined by whether the interaction has been responded to or not.

Результат:

The response, its type depending on whether it’s an interaction response or a followup.

Тип результата:

InteractionMessage | None

to_dict()[исходный код]

Converts this interaction object into a dict.

Результат:

A dictionary of str interaction keys bound to the respective value.

Тип результата:

dict[str, Any]

class discord.InteractionResponse(parent)[исходный код]

Represents a Discord interaction response.

This type can be accessed through Interaction.response.

Добавлено в версии 2.0.

Параметры:

parent (Interaction)

is_done()[исходный код]

Indicates whether an interaction response has been done before.

An interaction can only be responded to once.

Тип результата:

bool

await defer(*, ephemeral=False, invisible=True)[исходный код]

This function is a coroutine.

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This can only be used with the following interaction types:

Примечание

The follow-up response will also be non-ephemeral if the ephemeral argument is False, and ephemeral if True.

Параметры:
Исключение:
Тип результата:

None

await pong()[исходный код]

This function is a coroutine.

Pongs the ping interaction.

This should rarely be used.

Исключение:
Тип результата:

None

await send_message(content=None, *, embed=None, embeds=None, view=None, tts=False, ephemeral=False, allowed_mentions=None, file=None, files=None, poll=None, delete_after=None, silent=False, suppress_embeds=False)[исходный код]

This function is a coroutine.

Responds to this interaction by sending a message.

Параметры:
  • content (Any | None) – The content of the message to send.

  • embeds (list[Embed] | None) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the embed parameter.

  • embed (Embed | None) – The rich embed for the content to send. This cannot be mixed with embeds parameter.

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

  • view (BaseView | None) – The view to send with the message.

  • ephemeral (bool) – Indicates if the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message, and it has no timeout set then the timeout is set to 15 minutes.

  • allowed_mentions (AllowedMentions | None) – Controls the mentions being processed in this message. See abc.Messageable.send() for more information.

  • delete_after (float | None) – If provided, the number of seconds to wait in the background before deleting the message we just sent.

  • file (File | None) – The file to upload.

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

  • poll (Poll | None) –

    The poll to send.

    Добавлено в версии 2.6.

  • silent (bool) –

    Whether to suppress push and desktop notifications for the message.

    Добавлено в версии 2.8.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message.

    Добавлено в версии 2.8.

Результат:

The interaction object associated with the sent message.

Тип результата:

Interaction

Исключение:
  • HTTPException – Sending the message failed.

  • TypeError – You specified both embed and embeds, or sent content or embeds with V2 components.

  • ValueError – The length of embeds was invalid.

  • InteractionResponded – This interaction has already been responded to before.

await edit_message(*, content=..., embed=..., embeds=..., file=..., files=..., attachments=..., view=..., delete_after=None, suppress=..., allowed_mentions=None)[исходный код]

This function is a coroutine.

Responds to this interaction by editing the original message of a component or modal interaction.

Параметры:
  • content (Any | None) – The new content to replace the message with. None removes the content.

  • embeds (list[Embed]) – A list of embeds to edit the message with.

  • embed (Embed | None) – The embed to edit the message with. None suppresses the embeds. This should not be mixed with the embeds parameter.

  • file (File) – A new file to add to the message. This cannot be mixed with files parameter.

  • files (list[File]) – A list of new files to add to the message. Must be a maximum of 10. This cannot be mixed with the file parameter.

  • attachments (list[Attachment]) – A list of attachments to keep in the message. If [] is passed then all attachments are removed.

  • view (BaseView | None) – The updated view to update this message with. If None is passed then the view is removed.

  • delete_after (float | None) – 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.

  • suppress (bool | None) – Whether to suppress embeds for the message.

  • allowed_mentions (AllowedMentions | None) – 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.

Исключение:
Тип результата:

None

await send_autocomplete_result(*, choices)[исходный код]

This function is a coroutine. Responds to this interaction by sending the autocomplete choices.

Параметры:

choices (list[OptionChoice]) – A list of choices.

Исключение:
Тип результата:

None

await send_modal(modal)[исходный код]

This function is a coroutine. Responds to this interaction by sending a modal dialog. This cannot be used to respond to another modal dialog submission.

Параметры:

modal (BaseModal) – The modal dialog to display to the user.

Исключение:
Тип результата:

Interaction

await premium_required()[исходный код]

This function is a coroutine.

Responds to this interaction by sending a premium required message.

Устарело, начиная с версии 2.6: A button with type ButtonType.premium should be used instead.

Исключение:
Тип результата:

Interaction

Methods
class discord.InteractionMessage(*, state, channel, data)[исходный код]

Represents the original interaction response message.

This allows you to edit or delete the message associated with the interaction response. To retrieve this object see Interaction.original_response().

This inherits from discord.Message with changes to edit() and delete() to work.

Добавлено в версии 2.0.

Параметры:
await edit(content=..., embeds=..., embed=..., file=..., files=..., attachments=..., view=..., allowed_mentions=None, delete_after=None, suppress=..., suppress_embeds=...)[исходный код]

This function is a coroutine.

Edits the message.

Параметры:
  • content (str | None) – The content to edit the message with or None to clear it.

  • embeds (list[Embed]) – A list of embeds to edit the message with.

  • embed (Embed | None) – The embed to edit the message with. None suppresses the embeds. This should not be mixed with the embeds parameter.

  • file (File) – The file to upload. This cannot be mixed with files parameter.

  • files (list[File]) – A list of files to send with the content. This cannot be mixed with the file parameter.

  • attachments (list[Attachment]) – A list of attachments to keep in the message. If [] is passed then all attachments are removed.

  • allowed_mentions (AllowedMentions | None) – Controls the mentions being processed in this message. See abc.Messageable.send() for more information.

  • view (BaseView | None) – The updated view to update this message with. If None is passed then the view is removed.

  • delete_after (float | None) – 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.

  • suppress (bool | None) –

    Whether to suppress embeds for the message.

    Устарело, начиная с версии 2.8.

  • suppress_embeds (bool | None) –

    Whether to suppress embeds for the message.

    Добавлено в версии 2.8.

Результат:

The newly edited message.

Тип результата:

InteractionMessage

Исключение:
  • HTTPException – Editing the message failed.

  • Forbidden – Edited a message that is not yours.

  • TypeError – You specified both embed and embeds or file and files

  • ValueError – The length of embeds was invalid.

await delete(*, delay=None)[исходный код]

This function is a coroutine.

Deletes the message.

Параметры:

delay (float | None) – If provided, the number of seconds to wait before deleting the message. The waiting is done in the background and deletion failures are ignored.

Исключение:
  • Forbidden – You do not have proper permissions to delete the message.

  • NotFound – The message was deleted already.

  • HTTPException – Deleting the message failed.

Тип результата:

None

Attributes
class discord.MessageInteraction(*, data, state)[исходный код]

Represents a Discord message interaction.

This is sent on the message object when the message is a response to an interaction without an existing message e.g. application command.

Добавлено в версии 2.0.

Устарело, начиная с версии 2.6: See InteractionMetadata.

Примечание

Responses to message components do not include this property.

id

The interaction’s ID.

Type:

int

type

The interaction type.

Type:

InteractionType

name

The name of the invoked application command.

Type:

str

user

The user that sent the interaction.

Type:

User

data

The raw interaction data.

Type:

dict

Параметры:
  • data (MessageInteraction)

  • state (ConnectionState)

class discord.InteractionMetadata(*, data, state)[исходный код]

Represents metadata about an interaction.

This is sent on the message object when the message is related to an interaction

Добавлено в версии 2.6.

id

The interaction’s ID.

Type:

int

type

The interaction type.

Type:

InteractionType

user

The user that sent the interaction.

Type:

User

authorizing_integration_owners

The authorizing user or server for the installation(s) relevant to the interaction.

Type:

AuthorizingIntegrationOwners

original_response_message_id

The ID of the original response message. Only present on interaction follow-up messages.

Type:

Optional[int]

interacted_message_id

The ID of the message that triggered the interaction. Only present on interactions of type InteractionType.component.

Type:

Optional[int]

triggering_interaction_metadata

The metadata of the interaction that opened the model. Only present on interactions of type InteractionType.modal_submit.

Type:

Optional[InteractionMetadata]

Параметры:
  • data (InteractionMetadata)

  • state (ConnectionState)

original_response_message

The original response message. Returns None if the message is not in cache, or if original_response_message_id is None.

Type:

Optional[Message]

interacted_message

The message that triggered the interaction. Returns None if the message is not in cache, or if interacted_message_id is None.

Type:

Optional[Message]

Attributes
class discord.AuthorizingIntegrationOwners(data, state)[исходный код]

Contains details on the authorizing user or server for the installation(s) relevant to the interaction.

Добавлено в версии 2.6.

user_id

The ID of the user that authorized the integration.

Type:

int | None

guild_id

The ID of the guild that authorized the integration. This will be 0 if the integration was triggered from the user in the bot’s DMs.

Type:

int | None

Параметры:
user

The user that authorized the integration. Returns None if the user is not in cache, or if user_id is None.

Type:

Optional[User]

guild

The guild that authorized the integration. Returns None if the guild is not in cache, or if guild_id is 0 or None.

Type:

Optional[Guild]

Methods
class discord.InteractionCallback(data)[исходный код]

Information about the status of the interaction response.

Добавлено в версии 2.7.

Параметры:

data (InteractionCallback)

is_loading()[исходный код]

Indicates whether the response message is in a loading state.

Тип результата:

bool

is_ephemeral()[исходный код]

Indicates whether the response message is ephemeral.

This might be useful for determining if the message was forced to be ephemeral.

Тип результата:

bool

UI Components

Attributes
Methods
class discord.Component[исходный код]

Represents a Discord Bot UI Kit Component.

The components supported by Discord in messages are as follows:

This class is abstract and cannot be instantiated.

Добавлено в версии 2.0.

type

The type of component.

Type:

ComponentType

id

The component’s ID. If not provided by the user, it is set sequentially by Discord. The ID 0 is treated as if no ID was provided.

Type:

int

is_v2()[исходный код]

Whether this component was introduced in Components V2.

Тип результата:

bool

Attributes
Methods
class discord.ActionRow(data)[исходный код]

Represents a Discord Bot UI Kit Action Row.

This is a component that holds up to 5 children components in a row.

This inherits from Component.

Добавлено в версии 2.0.

type

The type of component.

Type:

ComponentType

children

The children components that this holds, if any.

Type:

List[Component]

Параметры:

data (ActionRow | ButtonComponent | SelectMenu | InputText | TextDisplayComponent | SectionComponent | ThumbnailComponent | MediaGalleryComponent | FileComponent | SeparatorComponent | ContainerComponent | LabelComponent | FileUploadComponent | RadioGroupComponent | CheckboxGroupComponent | CheckboxComponent)

property width

Returns the sum of the item’s widths.

get_component(id)[исходный код]

Get a component from this action row. Roughly equivalent to utils.get(row.children, …). If an int is provided, the component will be retrieved by id, otherwise by custom_id.

Параметры:

id (str | int) – The custom_id or id of the component to get.

Результат:

The component with the matching id or custom_id if it exists.

Тип результата:

Component | None

Methods
class discord.Button(data)[исходный код]

Represents a button from the Discord Bot UI Kit.

This inherits from Component.

Примечание

This class is not useable by end-users; see discord.ui.Button instead.

Добавлено в версии 2.0.

style

The style of the button.

Type:

ButtonStyle

custom_id

The ID of the button that gets received during an interaction. If this button is for a URL, it does not have a custom ID.

Type:

Optional[str]

url

The URL this button sends you to.

Type:

Optional[str]

disabled

Whether the button is disabled or not.

Type:

bool

label

The label of the button, if any.

Type:

Optional[str]

emoji

The emoji of the button, if available.

Type:

Optional[PartialEmoji]

sku_id

The ID of the SKU this button refers to.

Type:

Optional[int]

Параметры:

data (ButtonComponent)

is_v2()

Whether this component was introduced in Components V2.

Тип результата:

bool

class discord.SelectMenu(data)[исходный код]

Represents a select menu from the Discord Bot UI Kit.

A select menu is functionally the same as a dropdown, however on mobile it renders a bit differently.

Примечание

This class is not useable by end-users; see discord.ui.Select instead.

Добавлено в версии 2.0.

Изменено в версии 2.7: Added the required attribute for use in modals.

type

The select menu’s type.

Type:

ComponentType

custom_id

The ID of the select menu that gets received during an interaction.

Type:

Optional[str]

placeholder

The placeholder text that is shown if nothing is selected, if any.

Type:

Optional[str]

min_values

The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 0 and 25.

Type:

int

max_values

The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.

Type:

int

options

A list of options that can be selected in this menu. Will be an empty list for all component types except for ComponentType.string_select.

Type:

List[SelectOption]

channel_types

A list of channel types that can be selected. Will be an empty list for all component types except for ComponentType.channel_select.

Type:

List[ChannelType]

disabled

Whether the select is disabled or not. Not usable in modals. Defaults to False.

Type:

bool

required

Whether the select is required or not. Only useable in modals. Defaults to True.

Type:

Optional[bool]

Параметры:

data (SelectMenu)

is_v2()

Whether this component was introduced in Components V2.

Тип результата:

bool

Attributes
Methods
class discord.Section(data, state=None)[исходный код]

Represents a Section from Components V2.

This is a component that groups other components together with an additional component to the right as the accessory.

This inherits from Component.

Примечание

This class is not useable by end-users; see discord.ui.Section instead.

Добавлено в версии 2.7.

components

The components contained in this section. Currently supports TextDisplay.

Type:

List[Component]

accessory

The accessory attached to this Section. Currently supports Button and Thumbnail.

Type:

Optional[Component]

Параметры:

data (SectionComponent)

get_component(id)[исходный код]

Get a component from this section. Roughly equivalent to utils.get(section.walk_components(), …). If an int is provided, the component will be retrieved by id, otherwise by custom_id.

Параметры:

id (str | int) – The custom_id or id of the component to get.

Результат:

The component with the matching id or custom_id if it exists.

Тип результата:

Component | None

is_v2()

Whether this component was introduced in Components V2.

Тип результата:

bool

Attributes
Methods
class discord.TextDisplay(data)[исходный код]

Represents a Text Display from Components V2.

This is a component that displays text.

This inherits from Component.

Примечание

This class is not useable by end-users; see discord.ui.TextDisplay instead.

Добавлено в версии 2.7.

content

The component’s text content.

Type:

str

Параметры:

data (TextDisplayComponent)

is_v2()

Whether this component was introduced in Components V2.

Тип результата:

bool

Methods
class discord.Thumbnail(data, state=None)[исходный код]

Represents a Thumbnail from Components V2.

This is a component that displays media, such as images and videos.

This inherits from Component.

Примечание

This class is not useable by end-users; see discord.ui.Thumbnail instead.

Добавлено в версии 2.7.

media

The component’s underlying media object.

Type:

UnfurledMediaItem

description

The thumbnail’s description, up to 1024 characters.

Type:

Optional[str]

spoiler

Whether the thumbnail has the spoiler overlay.

Type:

Optional[bool]

Параметры:

data (ThumbnailComponent)

property url: str

Returns the URL of this thumbnail’s underlying media item.

is_v2()

Whether this component was introduced in Components V2.

Тип результата:

bool

Attributes
Methods
class discord.MediaGallery(data, state=None)[исходный код]

Represents a Media Gallery from Components V2.

This is a component that displays up to 10 different MediaGalleryItem objects.

This inherits from Component.

Примечание

This class is not useable by end-users; see discord.ui.MediaGallery instead.

Добавлено в версии 2.7.

items

The media this gallery contains.

Type:

List[MediaGalleryItem]

Параметры:

data (MediaGalleryComponent)

is_v2()

Whether this component was introduced in Components V2.

Тип результата:

bool

Attributes
Methods
class discord.FileComponent(data, state=None)[исходный код]

Represents a File from Components V2.

This component displays a downloadable file in a message.

This inherits from Component.

Примечание

This class is not useable by end-users; see discord.ui.File instead.

Добавлено в версии 2.7.

file

The file’s media item.

Type:

UnfurledMediaItem

name

The file’s name.

Type:

Optional[str]

size

The file’s size in bytes.

Type:

Optional[int]

spoiler

Whether the file has the spoiler overlay.

Type:

Optional[bool]

Параметры:

data (FileComponent)

is_v2()

Whether this component was introduced in Components V2.

Тип результата:

bool

Attributes
Methods
class discord.Separator(data)[исходный код]

Represents a Separator from Components V2.

This is a component that visually separates components.

This inherits from Component.

Примечание

This class is not useable by end-users; see discord.ui.Separator instead.

Добавлено в версии 2.7.

divider

Whether the separator will show a horizontal line in addition to vertical spacing.

Type:

bool

spacing

The separator’s spacing size.

Type:

Optional[SeparatorSpacingSize]

Параметры:

data (SeparatorComponent)

is_v2()

Whether this component was introduced in Components V2.

Тип результата:

bool

class discord.Container(data, state=None)[исходный код]

Represents a Container from Components V2.

This is a component that contains different Component objects. It may only contain:

This inherits from Component.

Примечание

This class is not useable by end-users; see discord.ui.Container instead.

Добавлено в версии 2.7.

components

The components contained in this container.

Type:

List[Component]

accent_color

The accent color of the container.

Type:

Optional[Colour]

spoiler

Whether the entire container has the spoiler overlay.

Type:

Optional[bool]

Параметры:

data (ContainerComponent)

get_component(id)[исходный код]

Get a component from this container. Roughly equivalent to utils.get(container.components, …). If an int is provided, the component will be retrieved by id, otherwise by custom_id. This method will also search for nested components.

Параметры:

id (str | int) – The custom_id or id of the component to get.

Результат:

The component with the matching id or custom_id if it exists.

Тип результата:

Component | None

is_v2()

Whether this component was introduced in Components V2.

Тип результата:

bool

class discord.Label(data)[исходный код]

Represents a Label used in modals as the top-level component.

This is a component that allows you to add additional text to another component. component may only be:

This inherits from Component.

Добавлено в версии 2.7.

component

The component contained in this label. Currently supports InputText and SelectMenu.

Type:

Component

label

The main text associated with this label’s component, up to 45 characters.

Type:

str

description

The description associated with this label’s component, up to 100 characters.

Type:

Optional[str]

Параметры:

data (LabelComponent)

class discord.FileUpload(data)[исходный код]

Represents an File Upload component from the Discord Bot UI Kit.

This inherits from Component.

Примечание

This class is not useable by end-users; see discord.ui.FileUpload instead.

Добавлено в версии 2.7.

custom_id

The custom ID of the file upload field that gets received during an interaction.

Type:

Optional[str]

min_values

The minimum number of files that must be uploaded.

Type:

Optional[int]

max_values

The maximum number of files that can be uploaded.

Type:

Optional[int]

required

Whether the file upload field is required or not. Defaults to True.

Type:

Optional[bool]

id

The file upload’s ID.

Type:

Optional[int]

Параметры:

data (FileUploadComponent)

is_v2()

Whether this component was introduced in Components V2.

Тип результата:

bool

Methods
class discord.RadioGroup(data)[исходный код]

Represents an Radio Group component from the Discord Bot UI Kit.

This inherits from Component.

Примечание

This class is not useable by end-users; see discord.ui.RadioGroup instead.

Добавлено в версии 2.8.

custom_id

The custom ID of the radio group that gets received during an interaction.

Type:

Optional[str]

options

A list of options that can be selected in this group, between 2 and 10.

Type:

List[RadioGroupOption]

required

Whether the radio group requires a selection or not. Defaults to True.

Type:

Optional[bool]

id

The radio group’s ID.

Type:

Optional[int]

Параметры:

data (RadioGroupComponent)

is_v2()

Whether this component was introduced in Components V2.

Тип результата:

bool

class discord.CheckboxGroup(data)[исходный код]

Represents an Checkbox Group component from the Discord Bot UI Kit.

This inherits from Component.

Примечание

This class is not useable by end-users; see discord.ui.CheckboxGroup instead.

Добавлено в версии 2.8.

custom_id

The custom ID of the checkbox group that gets received during an interaction.

Type:

Optional[str]

options

A list of options that can be selected in this group.

Type:

List[CheckboxGroupOption]

min_values

The minimum number of options that must be selected. Defaults to 1 and must be between 0 and 25. If set to 0, required must be False.

Type:

Optional[int]

max_values

The maximum number of options that can be selected. Must be between 1 and 10.

Type:

Optional[int]

required

Whether the checkbox group requires a selection or not. Defaults to True.

Type:

Optional[bool]

id

The checkbox group’s ID.

Type:

Optional[int]

Параметры:

data (CheckboxGroupComponent)

is_v2()

Whether this component was introduced in Components V2.

Тип результата:

bool

Attributes
Methods
class discord.Checkbox(data)[исходный код]

Represents an Checkbox component from the Discord Bot UI Kit.

This inherits from Component.

Примечание

This class is not useable by end-users; see discord.ui.Checkbox instead.

Добавлено в версии 2.8.

custom_id

The custom ID of the checkbox group that gets received during an interaction.

Type:

Optional[str]

default

Whether this checkbox is selected by default.

Type:

Optional[bool]

id

The checkbox group’s ID.

Type:

Optional[int]

Параметры:

data (CheckboxComponent)

is_v2()

Whether this component was introduced in Components V2.

Тип результата:

bool

Emoji

class discord.GuildEmoji(*, guild, state, data)[исходный код]

Represents a custom emoji in a guild.

Depending on the way this object was created, some 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]

Параметры:
  • guild (Guild)

  • state (ConnectionState)

  • data (Emoji)

property roles: list[Role]

A list of roles that is allowed to use this emoji.

If roles is empty, the emoji is unrestricted.

property guild: Guild

The guild this emoji belongs to.

is_usable()[исходный код]

Whether the bot can use this emoji.

Добавлено в версии 1.3.

Тип результата:

bool

await delete(*, reason=None)[исходный код]

This function is a coroutine.

Deletes the custom emoji.

You must have manage_emojis permission to do this.

Параметры:

reason (str | None) – The reason for deleting this emoji. Shows up on the audit log.

Исключение:
Тип результата:

None

await edit(*, name=..., roles=..., reason=None)[исходный код]

This function is a coroutine.

Edits the custom emoji.

You must have manage_emojis permission to do this.

Изменено в версии 2.0: The newly updated emoji is returned.

Параметры:
  • name (str) – The new emoji name.

  • roles (list[Snowflake]) – A list of roles that can use this emoji. An empty list can be passed to make it available to everyone.

  • reason (str | None) – The reason for editing this emoji. Shows up on the audit log.

Исключение:
Результат:

The newly updated emoji.

Тип результата:

GuildEmoji

property created_at: datetime

Returns the emoji’s creation time in UTC.

property extension: Literal['webp', 'png']

Return the file extension of the emoji.

Добавлено в версии 2.7.1.

property mention: str

Return a string that allows you to mention the emoji in a message.

await read()

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

Результат:

The content of the asset.

Тип результата:

bytes

Исключение:
await save(fp, *, seek_begin=True)

This function is a coroutine.

Saves this asset into a file-like object.

Параметры:
  • fp (str | bytes | PathLike | BufferedIOBase) – 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.

Результат:

The number of bytes written.

Тип результата:

int

Исключение:
property url: str

Returns the URL of the emoji.

class discord.AppEmoji(*, application_id, state, data)[исходный код]

Represents a custom emoji from an application.

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

Добавлено в версии 2.7.

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

application_id

The application ID the emoji belongs to, if available.

Type:

Optional[int]

available

Whether the emoji is available for use.

Type:

bool

user

The user that created the emoji.

Type:

Optional[User]

Параметры:
  • application_id (int)

  • state (ConnectionState)

  • data (Emoji)

property guild: Guild

The guild this emoji belongs to. This is always None for AppEmoji.

property roles: list[Role]

A list of roles that is allowed to use this emoji. This is always empty for AppEmoji.

is_usable()[исходный код]

Whether the bot can use this emoji.

Тип результата:

bool

await delete()[исходный код]

This function is a coroutine.

Deletes the application emoji.

You must own the emoji to do this.

Исключение:
  • Forbidden – You are not allowed to delete the emoji.

  • HTTPException – An error occurred deleting the emoji.

Тип результата:

None

await edit(*, name=...)[исходный код]

This function is a coroutine.

Edits the application emoji.

You must own the emoji to do this.

Параметры:

name (str) – The new emoji name.

Исключение:
Результат:

The newly updated emoji.

Тип результата:

AppEmoji

property created_at: datetime

Returns the emoji’s creation time in UTC.

property extension: Literal['webp', 'png']

Return the file extension of the emoji.

Добавлено в версии 2.7.1.

property mention: str

Return a string that allows you to mention the emoji in a message.

await read()

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

Результат:

The content of the asset.

Тип результата:

bytes

Исключение:
await save(fp, *, seek_begin=True)

This function is a coroutine.

Saves this asset into a file-like object.

Параметры:
  • fp (str | bytes | PathLike | BufferedIOBase) – 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.

Результат:

The number of bytes written.

Тип результата:

int

Исключение:
property url: str

Returns the URL of the emoji.

class discord.PartialEmoji(*, name, animated=False, id=None)[исходный код]

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_str(value)[исходный код]

Converts a Discord string representation of an emoji to a PartialEmoji.

The formats accepted are:

  • a:name:id

  • <a:name:id>

  • name:id

  • <:name:id>

If the format does not match then it is assumed to be a Unicode emoji block, either as Unicode characters or as a Discord alias (:smile:).

Добавлено в версии 2.0.

Параметры:

value (str) – The string representation of an emoji.

Результат:

The partial emoji from this string.

Тип результата:

TypeVar(PE, bound= PartialEmoji)

is_custom_emoji()[исходный код]

Checks if this is a custom non-Unicode emoji.

Тип результата:

bool

is_unicode_emoji()[исходный код]

Checks if this is a Unicode emoji.

Тип результата:

bool

property created_at: datetime | None

Returns the emoji’s creation time in UTC, or None if Unicode emoji.

Добавлено в версии 1.6.

property url: str

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

If this isn’t a custom emoji then an empty string is returned

property extension: Literal['webp', 'png']

Return the file extension of the emoji.

Добавлено в версии 2.7.1.

await read()[исходный код]

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

Результат:

The content of the asset.

Тип результата:

bytes

Исключение:
await save(fp, *, seek_begin=True)

This function is a coroutine.

Saves this asset into a file-like object.

Параметры:
  • fp (str | bytes | PathLike | BufferedIOBase) – 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.

Результат:

The number of bytes written.

Тип результата:

int

Исключение:

Channels

class discord.TextChannel(*, state, guild, data)[исходный код]

Represents a Discord 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]

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0. Can be None if the channel was received in an interaction.

Type:

Optional[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

nsfw

If the channel is marked as «not safe for work».

Примечание

To check if the channel or the guild of that channel are marked as NSFW, consider is_nsfw() instead.

Type:

bool

default_auto_archive_duration

The default auto archive duration in minutes for threads created in this channel.

Добавлено в версии 2.0.

Type:

int

flags

Extra features of the channel.

Добавлено в версии 2.0.

Type:

ChannelFlags

default_thread_slowmode_delay

The initial slowmode delay to set on newly created threads in this channel.

Добавлено в версии 2.3.

Type:

Optional[int]

Параметры:
  • state (ConnectionState)

  • guild (Guild)

  • data (TextChannel)

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.

Параметры:
  • limit (int | None) – 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 (Snowflake | datetime | None) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Snowflake | datetime | None) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.

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

Yields:

Message – The message with the message data parsed.

Исключение:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Тип результата:

HistoryIterator

Примеры

Usage

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

Flattening into a list:

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

All parameters are optional.

async with typing()

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

This is useful for denoting long computations in your bot.

Примечание

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():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
Тип результата:

Typing

is_news()[исходный код]

Checks if the channel is a news/announcements channel.

Тип результата:

bool

property news: bool

Equivalent to is_news().

await edit(*, reason=None, **options)[исходный код]

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

Изменено в версии 1.3: The overwrites keyword-only parameter was added.

Изменено в версии 1.4: The type keyword-only parameter was added.

Изменено в версии 2.0: Edits are no longer in-place, the newly edited channel is returned instead.

Параметры:
  • name (str) – The new channel name.

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

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

  • nsfw (bool) – Whether the channel is marked as NSFW.

  • 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[Union[Role, Member, Snowflake], PermissionOverwrite]) – The overwrites to apply to channel permissions. Useful for creating secret channels.

  • default_auto_archive_duration (int) – The new default auto archive duration in minutes for threads created in this channel. Must be one of 60, 1440, 4320, or 10080.

  • default_thread_slowmode_delay (int) –

    The new default slowmode delay in seconds for threads created in this channel.

    Добавлено в версии 2.3.

Результат:

The newly edited text channel. If the edit was only positional then None is returned instead.

Тип результата:

Optional[TextChannel]

Исключение:
  • 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 create_thread(*, name, message=None, auto_archive_duration=..., type=None, slowmode_delay=None, invitable=None, reason=None)[исходный код]

This function is a coroutine.

Creates a thread in this text channel.

To create a public thread, you must have create_public_threads. For a private thread, create_private_threads is needed instead.

Добавлено в версии 2.0.

Параметры:
  • name (str) – The name of the thread.

  • message (Snowflake | None) – A snowflake representing the message to create the thread with. If None is passed then a private thread is created. Defaults to None.

  • auto_archive_duration (Literal[60, 1440, 4320, 10080]) – The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used.

  • type (ChannelType | None) – The type of thread to create. If a message is passed then this parameter is ignored, as a thread created with a message is always a public thread. By default, this creates a private thread if this is None.

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

  • invitable (bool | None) – Whether non-moderators can add other non-moderators to this thread. Only available for private threads, where it defaults to True.

  • reason (str | None) – The reason for creating a new thread. Shows up on the audit log.

Результат:

The created thread

Тип результата:

Thread

Исключение:
archived_threads(*, private=False, joined=False, limit=50, before=None)

Returns an AsyncIterator that iterates over all archived threads in the guild.

You must have read_message_history to use this. If iterating over private threads then manage_threads is also required.

Добавлено в версии 2.0.

Параметры:
  • limit (int | None) – The number of threads to retrieve. If None, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation.

  • before (Snowflake | datetime | None) – Retrieve archived channels before the given date or ID.

  • private (bool) – Whether to retrieve private archived threads.

  • joined (bool) – Whether to retrieve private archived threads that you’ve joined. You cannot set joined to True and private to False.

Yields:

Thread – The archived threads.

Исключение:
  • Forbidden – You do not have permissions to get archived threads.

  • HTTPException – The request to get the archived threads failed.

Тип результата:

ArchivedThreadIterator

can_send(*objects)

Returns a bool indicating whether you have the permissions to send the object(s).

Результат:

Indicates whether you have the permissions to send the object(s).

Тип результата:

bool

Исключение:

TypeError – An invalid type has been passed.

property category: CategoryChannel | None

The category this channel belongs to.

If there is no category then this is None.

property changed_roles: list[Role]

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

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.

Добавлено в версии 1.1.

Параметры:
  • name (str | None) – The name of the new channel. If not provided, defaults to this channel name.

  • reason (str | None) – The reason for cloning this channel. Shows up on the audit log.

Результат:

The channel that was created.

Тип результата:

TextChannel

Исключение:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, roles=None, target_users_file=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.

Параметры:
  • 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 (str | None) – The reason for creating this invite. Shows up on the audit log.

  • target_type (InviteTarget | None) –

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

    Добавлено в версии 2.0.

  • target_user (User | None) –

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

    Добавлено в версии 2.0.

  • target_application_id (int | None) –

    The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    Добавлено в версии 2.0.

  • target_event (ScheduledEvent | None) –

    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.

    Добавлено в версии 2.0.

  • roles (list[Role | Object] | None) –

    The roles to give a user when joining through this invite.

    You must have the manage_roles permission to do this and roles cannot be higher than your own.

    Добавлено в версии 2.8.

  • target_users_file (File | None) –

    A CSV file with a single column of user IDs for all the users able to accept this invite.

    You can use utils.users_to_csv() to generate a virtual CSV file from a sequence of user IDs.

    Добавлено в версии 2.8.

Результат:

The invite that was created.

Тип результата:

Invite

Исключение:
  • HTTPException – Invite creation failed.

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

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

This function is a coroutine.

Creates a webhook for this channel.

Requires manage_webhooks permissions.

Изменено в версии 1.1: Added the reason keyword-only parameter.

Параметры:
  • name (str) – The webhook’s name.

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

  • reason (str | None) – The reason for creating this webhook. Shows up in the audit logs.

Результат:

The created webhook.

Тип результата:

Webhook

Исключение:
  • HTTPException – Creating the webhook failed.

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

property created_at: datetime

Returns the channel’s creation time in UTC.

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

Параметры:

reason (str | None) – The reason for deleting this channel. Shows up on the audit log.

Исключение:
  • 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.

Тип результата:

None

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.

Параметры:
  • messages (Iterable[Snowflake]) – An iterable of messages denoting which ones to bulk delete.

  • reason (str | None) – The reason for deleting the messages. Shows up on the audit log.

Исключение:
  • ClientException – The number of messages to delete was more than 100.

  • Forbidden – You do not have proper permissions to delete the messages.

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

  • HTTPException – Deleting the messages failed.

Тип результата:

None

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

Параметры:

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

Результат:

The message asked for.

Тип результата:

Message

Исключение:
  • NotFound – The specified message was not found.

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

  • HTTPException – Retrieving the message failed.

await follow(*, destination, reason=None)

Follows a channel using a webhook.

Only news channels can be followed.

Примечание

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

Добавлено в версии 1.3.

Параметры:
  • destination (TextChannel) – The channel you would like to follow from.

  • reason (str | None) –

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

    Добавлено в версии 1.4.

Результат:

The created webhook.

Тип результата:

Webhook

Исключение:
  • HTTPException – Following the channel failed.

  • Forbidden – You do not have the permissions to create a 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.

Добавлено в версии 1.6.

Параметры:

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

Результат:

The partial message.

Тип результата:

PartialMessage

get_thread(thread_id, /)

Returns a thread with the given ID.

Добавлено в версии 2.0.

Параметры:

thread_id (int) – The ID to search for.

Результат:

The returned thread or None if not found.

Тип результата:

Thread | None

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.

Результат:

The list of invites that are currently active.

Тип результата:

list[Invite]

Исключение:
  • Forbidden – You do not have proper permissions to get the information.

  • HTTPException – An error occurred while fetching the information.

is_nsfw()

Checks if the channel is NSFW.

Тип результата:

bool

property jump_url: str

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

Добавлено в версии 2.0.

property last_message: Message | None

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.

Результат:

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

Тип результата:

Optional[Message]

property members: list[Member]

Returns all members that can see this channel.

property mention: str

The string that allows you to mention the channel.

await move(**kwargs)

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.

Примечание

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

Добавлено в версии 1.7.

Параметры:
  • 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.

Исключение:
  • InvalidArgument – An invalid position was given or a bad mix of arguments was passed.

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

  • HTTPException – Moving the channel failed.

Тип результата:

None

property overwrites: dict[Role | Member, PermissionOverwrite]

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.

Результат:

The channel’s permission overwrites.

Тип результата:

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

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

Параметры:

obj (Role | User) – The role or user denoting whose overwrite to get.

Результат:

The permission overwrites for this object.

Тип результата:

PermissionOverwrite

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Изменено в версии 2.0: The object passed in can now be a role object.

Параметры:

obj (Member | Role) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

Результат:

The resolved permissions for the member or role.

Тип результата:

Permissions

property permissions_synced: bool

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

If there is no category then this is False.

Добавлено в версии 1.3.

pins(*, limit=50, before=None)

Returns a MessagePinIterator that enables receiving the destination’s pinned messages.

You must have read_message_history permissions to use this.

Предупреждение

Starting from version 3.0, await channel.pins() will no longer return a list of Message. See examples below for new usage instead.

Параметры:
  • limit (int | None) – The number of pinned messages to retrieve. If None, retrieves every pinned message in the channel.

  • before (Snowflake | datetime | None) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

Yields:

MessagePin – The pinned message.

Исключение:
  • Forbidden – You do not have permissions to get pinned messages.

  • HTTPException – The request to get pinned messages failed.

Тип результата:

MessagePinIterator

Примеры

Usage

counter = 0
async for pin in channel.pins(limit=250):
    if pin.message.author == client.user:
        counter += 1

Flattening into a list:

pins = await channel.pins(limit=None).flatten()
# pins is now a list of MessagePin...

All parameters are optional.

await purge(*, limit=100, check=..., 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. The read_message_history permission is also needed to retrieve message history.

Параметры:
Результат:

The list of messages that were deleted.

Тип результата:

list[Message]

Исключение:
  • Forbidden – You do not have proper permissions to do the actions required.

  • HTTPException – Purging the messages failed.

Примеры

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(f'Deleted {len(deleted)} message(s)')
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, suppress_embeds=None, silent=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Параметры:
  • content (Optional[str]) – The content of the message to send.

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

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

  • file (File) – The file to upload.

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

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

  • enforce_nonce (Optional[bool]) –

    Whether nonce is enforced to be validated.

    Добавлено в версии 2.5.

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

  • allowed_mentions (AllowedMentions) –

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

    Добавлено в версии 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message being replied to or forwarded. This can be created using to_reference(). When replying, 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.

    Добавлено в версии 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    Добавлено в версии 1.6.

  • view (discord.ui.BaseView) – A Discord UI View to add to the message.

  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    Добавлено в версии 2.0.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    Добавлено в версии 2.0.

  • suppress (bool) –

    Whether to suppress embeds for the message.

    Устарело, начиная с версии 2.8.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message.

    Добавлено в версии 2.8.

  • silent (bool) –

    Whether to suppress push and desktop notifications for the message.

    Добавлено в версии 2.4.

  • poll (Poll) –

    The poll to send.

    Добавлено в версии 2.6.

Результат:

The message that was sent.

Тип результата:

Message

Исключение:
await set_permissions(target, *, overwrite=..., 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.

Примечание

This method replaces the old overwrites with the ones given.

Примеры

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)
Параметры:
  • 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.

Исключение:
  • 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.

property threads: list[Thread]

Returns all the threads that you can see.

Добавлено в версии 2.0.

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.

Тип результата:

None

property type: ChannelType

The channel’s Discord type.

await webhooks()

This function is a coroutine.

Gets the list of webhooks from this channel.

Requires manage_webhooks permissions.

Результат:

The webhooks for this channel.

Тип результата:

list[Webhook]

Исключение:

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

class discord.ForumChannel(*, state, guild, data)[исходный код]

Represents a Discord 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.

Примечание

guidelines exists as an alternative to this attribute.

Type:

Optional[str]

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0. Can be None if the channel was received in an interaction.

Type:

Optional[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

nsfw

If the channel is marked as «not safe for work».

Примечание

To check if the channel or the guild of that channel are marked as NSFW, consider is_nsfw() instead.

Type:

bool

default_auto_archive_duration

The default auto archive duration in minutes for threads created in this channel.

Добавлено в версии 2.0.

Type:

int

flags

Extra features of the channel.

Добавлено в версии 2.0.

Type:

ChannelFlags

available_tags

The set of tags that can be used in a forum channel.

Добавлено в версии 2.3.

Type:

List[ForumTag]

default_sort_order

The default sort order type used to order posts in this channel.

Добавлено в версии 2.3.

Type:

Optional[SortOrder]

default_thread_slowmode_delay

The initial slowmode delay to set on newly created threads in this channel.

Добавлено в версии 2.3.

Type:

Optional[int]

default_reaction_emoji

The default forum reaction emoji.

Добавлено в версии 2.5.

Type:

Optional[str | discord.GuildEmoji]

Параметры:
  • state (ConnectionState)

  • guild (Guild)

  • data (ForumChannel)

property guidelines: str | None

The channel’s guidelines. An alias of topic.

property requires_tag: bool

Whether a tag is required to be specified when creating a thread in this forum or media channel.

Tags are specified in applied_tags.

Добавлено в версии 2.3.

get_tag(id, /)[исходный код]

Returns the ForumTag from this forum channel with the given ID, if any.

Добавлено в версии 2.3.

Параметры:

id (int)

Тип результата:

ForumTag | None

await edit(*, reason=None, **options)[исходный код]

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

Параметры:
  • name (str) – The new channel name.

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

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

  • nsfw (bool) – Whether the channel is marked as NSFW.

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

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

  • overwrites (Dict[Union[Role, Member, Snowflake], PermissionOverwrite]) – The overwrites to apply to channel permissions. Useful for creating secret channels.

  • default_auto_archive_duration (int) – The new default auto archive duration in minutes for threads created in this channel. Must be one of 60, 1440, 4320, or 10080. ThreadArchiveDuration can be used alternatively.

  • default_thread_slowmode_delay (int) –

    The new default slowmode delay in seconds for threads created in this channel.

    Добавлено в версии 2.3.

  • default_sort_order (Optional[SortOrder]) –

    The default sort order type to use to order posts in this channel.

    Добавлено в версии 2.3.

  • default_reaction_emoji (Optional[discord.GuildEmoji | int | str]) –

    The default reaction emoji. Can be a unicode emoji or a custom emoji in the forms: GuildEmoji, snowflake ID, string representation (eg. „<a:emoji_name:emoji_id>“).

    Добавлено в версии 2.5.

  • available_tags (List[ForumTag]) –

    The set of tags that can be used in this channel. Must be less than 20.

    Добавлено в версии 2.3.

  • require_tag (bool) –

    Whether a tag should be required to be specified when creating a thread in this channel.

    Добавлено в версии 2.3.

Результат:

The newly edited forum channel. If the edit was only positional then None is returned instead.

Тип результата:

Optional[ForumChannel]

Исключение:
  • 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 create_thread(name, content=None, *, embed=None, embeds=None, file=None, files=None, stickers=None, delete_message_after=None, nonce=None, allowed_mentions=None, view=None, applied_tags=None, suppress=False, silent=False, auto_archive_duration=..., slowmode_delay=..., reason=None)[исходный код]

This function is a coroutine.

Creates a thread in this forum channel.

To create a public thread, you must have create_public_threads. For a private thread, create_private_threads is needed instead.

Добавлено в версии 2.0.

Параметры:
  • name (str) – The name of the thread.

  • content (str | None) – The content of the message to send.

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

  • embeds (list[Embed] | None) – A list of embeds to upload. Must be a maximum of 10.

  • file (File | None) – The file to upload.

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

  • stickers (Sequence[GuildSticker | StickerItem] | None) – A list of stickers to upload. Must be a maximum of 3.

  • delete_message_after (float | None) – The time to wait before deleting the thread.

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

  • allowed_mentions (AllowedMentions | None) – 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.

  • view (BaseView | None) – A Discord UI View to add to the message.

  • applied_tags (list[ForumTag] | None) – A list of tags to apply to the new thread.

  • auto_archive_duration (Literal[60, 1440, 4320, 10080]) – The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used.

  • slowmode_delay (int) – The number of seconds a member must wait between sending messages in the new thread. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode. If not provided, the forum channel’s default slowmode is used.

  • reason (str | None) – The reason for creating a new thread. Shows up on the audit log.

  • suppress (bool)

  • silent (bool)

Результат:

The created thread

Тип результата:

Thread

Исключение:
archived_threads(*, private=False, joined=False, limit=50, before=None)

Returns an AsyncIterator that iterates over all archived threads in the guild.

You must have read_message_history to use this. If iterating over private threads then manage_threads is also required.

Добавлено в версии 2.0.

Параметры:
  • limit (int | None) – The number of threads to retrieve. If None, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation.

  • before (Snowflake | datetime | None) – Retrieve archived channels before the given date or ID.

  • private (bool) – Whether to retrieve private archived threads.

  • joined (bool) – Whether to retrieve private archived threads that you’ve joined. You cannot set joined to True and private to False.

Yields:

Thread – The archived threads.

Исключение:
  • Forbidden – You do not have permissions to get archived threads.

  • HTTPException – The request to get the archived threads failed.

Тип результата:

ArchivedThreadIterator

property category: CategoryChannel | None

The category this channel belongs to.

If there is no category then this is None.

property changed_roles: list[Role]

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

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.

Добавлено в версии 1.1.

Параметры:
  • name (str | None) – The name of the new channel. If not provided, defaults to this channel name.

  • reason (str | None) – The reason for cloning this channel. Shows up on the audit log.

Результат:

The channel that was created.

Тип результата:

TextChannel

Исключение:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, roles=None, target_users_file=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.

Параметры:
  • 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 (str | None) – The reason for creating this invite. Shows up on the audit log.

  • target_type (InviteTarget | None) –

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

    Добавлено в версии 2.0.

  • target_user (User | None) –

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

    Добавлено в версии 2.0.

  • target_application_id (int | None) –

    The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    Добавлено в версии 2.0.

  • target_event (ScheduledEvent | None) –

    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.

    Добавлено в версии 2.0.

  • roles (list[Role | Object] | None) –

    The roles to give a user when joining through this invite.

    You must have the manage_roles permission to do this and roles cannot be higher than your own.

    Добавлено в версии 2.8.

  • target_users_file (File | None) –

    A CSV file with a single column of user IDs for all the users able to accept this invite.

    You can use utils.users_to_csv() to generate a virtual CSV file from a sequence of user IDs.

    Добавлено в версии 2.8.

Результат:

The invite that was created.

Тип результата:

Invite

Исключение:
  • HTTPException – Invite creation failed.

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

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

This function is a coroutine.

Creates a webhook for this channel.

Requires manage_webhooks permissions.

Изменено в версии 1.1: Added the reason keyword-only parameter.

Параметры:
  • name (str) – The webhook’s name.

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

  • reason (str | None) – The reason for creating this webhook. Shows up in the audit logs.

Результат:

The created webhook.

Тип результата:

Webhook

Исключение:
  • HTTPException – Creating the webhook failed.

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

property created_at: datetime

Returns the channel’s creation time in UTC.

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

Параметры:

reason (str | None) – The reason for deleting this channel. Shows up on the audit log.

Исключение:
  • 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.

Тип результата:

None

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.

Параметры:
  • messages (Iterable[Snowflake]) – An iterable of messages denoting which ones to bulk delete.

  • reason (str | None) – The reason for deleting the messages. Shows up on the audit log.

Исключение:
  • ClientException – The number of messages to delete was more than 100.

  • Forbidden – You do not have proper permissions to delete the messages.

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

  • HTTPException – Deleting the messages failed.

Тип результата:

None

await follow(*, destination, reason=None)

Follows a channel using a webhook.

Only news channels can be followed.

Примечание

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

Добавлено в версии 1.3.

Параметры:
  • destination (TextChannel) – The channel you would like to follow from.

  • reason (str | None) –

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

    Добавлено в версии 1.4.

Результат:

The created webhook.

Тип результата:

Webhook

Исключение:
  • HTTPException – Following the channel failed.

  • Forbidden – You do not have the permissions to create a 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.

Добавлено в версии 1.6.

Параметры:

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

Результат:

The partial message.

Тип результата:

PartialMessage

get_thread(thread_id, /)

Returns a thread with the given ID.

Добавлено в версии 2.0.

Параметры:

thread_id (int) – The ID to search for.

Результат:

The returned thread or None if not found.

Тип результата:

Thread | None

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.

Результат:

The list of invites that are currently active.

Тип результата:

list[Invite]

Исключение:
  • Forbidden – You do not have proper permissions to get the information.

  • HTTPException – An error occurred while fetching the information.

is_nsfw()

Checks if the channel is NSFW.

Тип результата:

bool

property jump_url: str

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

Добавлено в версии 2.0.

property last_message: Message | None

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.

Результат:

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

Тип результата:

Optional[Message]

property members: list[Member]

Returns all members that can see this channel.

property mention: str

The string that allows you to mention the channel.

await move(**kwargs)

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.

Примечание

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

Добавлено в версии 1.7.

Параметры:
  • 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.

Исключение:
  • InvalidArgument – An invalid position was given or a bad mix of arguments was passed.

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

  • HTTPException – Moving the channel failed.

Тип результата:

None

property overwrites: dict[Role | Member, PermissionOverwrite]

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.

Результат:

The channel’s permission overwrites.

Тип результата:

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

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

Параметры:

obj (Role | User) – The role or user denoting whose overwrite to get.

Результат:

The permission overwrites for this object.

Тип результата:

PermissionOverwrite

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Изменено в версии 2.0: The object passed in can now be a role object.

Параметры:

obj (Member | Role) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

Результат:

The resolved permissions for the member or role.

Тип результата:

Permissions

property permissions_synced: bool

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

If there is no category then this is False.

Добавлено в версии 1.3.

await purge(*, limit=100, check=..., 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. The read_message_history permission is also needed to retrieve message history.

Параметры:
  • limit (int | None) – 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 (Snowflake | datetime | None) – Same as before in history().

  • after (Snowflake | datetime | None) – Same as after in history().

  • around (Snowflake | datetime | None) – Same as around in history().

  • oldest_first (bool | None) – 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 messages are older than two weeks.

  • reason (str | None) – The reason for deleting the messages. Shows up on the audit log.

Результат:

The list of messages that were deleted.

Тип результата:

list[Message]

Исключение:
  • Forbidden – You do not have proper permissions to do the actions required.

  • HTTPException – Purging the messages failed.

Примеры

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(f'Deleted {len(deleted)} message(s)')
await set_permissions(target, *, overwrite=..., 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.

Примечание

This method replaces the old overwrites with the ones given.

Примеры

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)
Параметры:
  • 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.

Исключение:
  • 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.

property threads: list[Thread]

Returns all the threads that you can see.

Добавлено в версии 2.0.

property type: ChannelType

The channel’s Discord type.

await webhooks()

This function is a coroutine.

Gets the list of webhooks from this channel.

Requires manage_webhooks permissions.

Результат:

The webhooks for this channel.

Тип результата:

list[Webhook]

Исключение:

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

class discord.MediaChannel(*, state, guild, data)[исходный код]

Represents a Discord media channel. Subclass of ForumChannel.

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.

Добавлено в версии 2.7.

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.

Примечание

guidelines exists as an alternative to this attribute.

Type:

Optional[str]

position

The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0. Can be None if the channel was received in an interaction.

Type:

Optional[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

nsfw

If the channel is marked as «not safe for work».

Примечание

To check if the channel or the guild of that channel are marked as NSFW, consider is_nsfw() instead.

Type:

bool

default_auto_archive_duration

The default auto archive duration in minutes for threads created in this channel.

Type:

int

flags

Extra features of the channel.

Type:

ChannelFlags

available_tags

The set of tags that can be used in a forum channel.

Type:

List[ForumTag]

default_sort_order

The default sort order type used to order posts in this channel.

Type:

Optional[SortOrder]

default_thread_slowmode_delay

The initial slowmode delay to set on newly created threads in this channel.

Type:

Optional[int]

default_reaction_emoji

The default forum reaction emoji.

Type:

Optional[str | discord.GuildEmoji]

Параметры:
  • state (ConnectionState)

  • guild (Guild)

  • data (ForumChannel)

property media_download_options_hidden: bool

Whether media download options are hidden in this media channel.

Добавлено в версии 2.7.

await edit(*, reason=None, **options)[исходный код]

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

Параметры:
  • name (str) – The new channel name.

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

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

  • nsfw (bool) – Whether the channel is marked as NSFW.

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

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

  • overwrites (Dict[Union[Role, Member, Snowflake], PermissionOverwrite]) – The overwrites to apply to channel permissions. Useful for creating secret channels.

  • default_auto_archive_duration (int) – The new default auto archive duration in minutes for threads created in this channel. Must be one of 60, 1440, 4320, or 10080.

  • default_thread_slowmode_delay (int) – The new default slowmode delay in seconds for threads created in this channel.

  • default_sort_order (Optional[SortOrder]) – The default sort order type to use to order posts in this channel.

  • default_reaction_emoji (Optional[discord.GuildEmoji | int | str]) – The default reaction emoji. Can be a unicode emoji or a custom emoji in the forms: GuildEmoji, snowflake ID, string representation (e.g., „<a:emoji_name:emoji_id>“).

  • available_tags (List[ForumTag]) – The set of tags that can be used in this channel. Must be less than 20.

  • require_tag (bool) – Whether a tag should be required to be specified when creating a thread in this channel.

  • hide_media_download_options (bool) – Whether media download options should be hidden in this media channel.

Результат:

The newly edited media channel. If the edit was only positional then None is returned instead.

Тип результата:

Optional[MediaChannel]

Исключение:
  • 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.

archived_threads(*, private=False, joined=False, limit=50, before=None)

Returns an AsyncIterator that iterates over all archived threads in the guild.

You must have read_message_history to use this. If iterating over private threads then manage_threads is also required.

Добавлено в версии 2.0.

Параметры:
  • limit (int | None) – The number of threads to retrieve. If None, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation.

  • before (Snowflake | datetime | None) – Retrieve archived channels before the given date or ID.

  • private (bool) – Whether to retrieve private archived threads.

  • joined (bool) – Whether to retrieve private archived threads that you’ve joined. You cannot set joined to True and private to False.

Yields:

Thread – The archived threads.

Исключение:
  • Forbidden – You do not have permissions to get archived threads.

  • HTTPException – The request to get the archived threads failed.

Тип результата:

ArchivedThreadIterator

property category: CategoryChannel | None

The category this channel belongs to.

If there is no category then this is None.

property changed_roles: list[Role]

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

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.

Добавлено в версии 1.1.

Параметры:
  • name (str | None) – The name of the new channel. If not provided, defaults to this channel name.

  • reason (str | None) – The reason for cloning this channel. Shows up on the audit log.

Результат:

The channel that was created.

Тип результата:

TextChannel

Исключение:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, roles=None, target_users_file=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.

Параметры:
  • 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 (str | None) – The reason for creating this invite. Shows up on the audit log.

  • target_type (InviteTarget | None) –

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

    Добавлено в версии 2.0.

  • target_user (User | None) –

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

    Добавлено в версии 2.0.

  • target_application_id (int | None) –

    The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    Добавлено в версии 2.0.

  • target_event (ScheduledEvent | None) –

    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.

    Добавлено в версии 2.0.

  • roles (list[Role | Object] | None) –

    The roles to give a user when joining through this invite.

    You must have the manage_roles permission to do this and roles cannot be higher than your own.

    Добавлено в версии 2.8.

  • target_users_file (File | None) –

    A CSV file with a single column of user IDs for all the users able to accept this invite.

    You can use utils.users_to_csv() to generate a virtual CSV file from a sequence of user IDs.

    Добавлено в версии 2.8.

Результат:

The invite that was created.

Тип результата:

Invite

Исключение:
  • HTTPException – Invite creation failed.

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

await create_thread(name, content=None, *, embed=None, embeds=None, file=None, files=None, stickers=None, delete_message_after=None, nonce=None, allowed_mentions=None, view=None, applied_tags=None, suppress=False, silent=False, auto_archive_duration=..., slowmode_delay=..., reason=None)

This function is a coroutine.

Creates a thread in this forum channel.

To create a public thread, you must have create_public_threads. For a private thread, create_private_threads is needed instead.

Добавлено в версии 2.0.

Параметры:
  • name (str) – The name of the thread.

  • content (str | None) – The content of the message to send.

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

  • embeds (list[Embed] | None) – A list of embeds to upload. Must be a maximum of 10.

  • file (File | None) – The file to upload.

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

  • stickers (Sequence[GuildSticker | StickerItem] | None) – A list of stickers to upload. Must be a maximum of 3.

  • delete_message_after (float | None) – The time to wait before deleting the thread.

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

  • allowed_mentions (AllowedMentions | None) – 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.

  • view (BaseView | None) – A Discord UI View to add to the message.

  • applied_tags (list[ForumTag] | None) – A list of tags to apply to the new thread.

  • auto_archive_duration (Literal[60, 1440, 4320, 10080]) – The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used.

  • slowmode_delay (int) – The number of seconds a member must wait between sending messages in the new thread. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode. If not provided, the forum channel’s default slowmode is used.

  • reason (str | None) – The reason for creating a new thread. Shows up on the audit log.

  • suppress (bool)

  • silent (bool)

Результат:

The created thread

Тип результата:

Thread

Исключение:
await create_webhook(*, name, avatar=None, reason=None)

This function is a coroutine.

Creates a webhook for this channel.

Requires manage_webhooks permissions.

Изменено в версии 1.1: Added the reason keyword-only parameter.

Параметры:
  • name (str) – The webhook’s name.

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

  • reason (str | None) – The reason for creating this webhook. Shows up in the audit logs.

Результат:

The created webhook.

Тип результата:

Webhook

Исключение:
  • HTTPException – Creating the webhook failed.

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

property created_at: datetime

Returns the channel’s creation time in UTC.

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

Параметры:

reason (str | None) – The reason for deleting this channel. Shows up on the audit log.

Исключение:
  • 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.

Тип результата:

None

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.

Параметры:
  • messages (Iterable[Snowflake]) – An iterable of messages denoting which ones to bulk delete.

  • reason (str | None) – The reason for deleting the messages. Shows up on the audit log.

Исключение:
  • ClientException – The number of messages to delete was more than 100.

  • Forbidden – You do not have proper permissions to delete the messages.

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

  • HTTPException – Deleting the messages failed.

Тип результата:

None

await follow(*, destination, reason=None)

Follows a channel using a webhook.

Only news channels can be followed.

Примечание

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

Добавлено в версии 1.3.

Параметры:
  • destination (TextChannel) – The channel you would like to follow from.

  • reason (str | None) –

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

    Добавлено в версии 1.4.

Результат:

The created webhook.

Тип результата:

Webhook

Исключение:
  • HTTPException – Following the channel failed.

  • Forbidden – You do not have the permissions to create a 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.

Добавлено в версии 1.6.

Параметры:

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

Результат:

The partial message.

Тип результата:

PartialMessage

get_tag(id, /)

Returns the ForumTag from this forum channel with the given ID, if any.

Добавлено в версии 2.3.

Параметры:

id (int)

Тип результата:

ForumTag | None

get_thread(thread_id, /)

Returns a thread with the given ID.

Добавлено в версии 2.0.

Параметры:

thread_id (int) – The ID to search for.

Результат:

The returned thread or None if not found.

Тип результата:

Thread | None

property guidelines: str | None

The channel’s guidelines. An alias of topic.

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.

Результат:

The list of invites that are currently active.

Тип результата:

list[Invite]

Исключение:
  • Forbidden – You do not have proper permissions to get the information.

  • HTTPException – An error occurred while fetching the information.

is_nsfw()

Checks if the channel is NSFW.

Тип результата:

bool

property jump_url: str

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

Добавлено в версии 2.0.

property last_message: Message | None

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.

Результат:

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

Тип результата:

Optional[Message]

property members: list[Member]

Returns all members that can see this channel.

property mention: str

The string that allows you to mention the channel.

await move(**kwargs)

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.

Примечание

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

Добавлено в версии 1.7.

Параметры:
  • 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.

Исключение:
  • InvalidArgument – An invalid position was given or a bad mix of arguments was passed.

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

  • HTTPException – Moving the channel failed.

Тип результата:

None

property overwrites: dict[Role | Member, PermissionOverwrite]

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.

Результат:

The channel’s permission overwrites.

Тип результата:

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

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

Параметры:

obj (Role | User) – The role or user denoting whose overwrite to get.

Результат:

The permission overwrites for this object.

Тип результата:

PermissionOverwrite

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Изменено в версии 2.0: The object passed in can now be a role object.

Параметры:

obj (Member | Role) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

Результат:

The resolved permissions for the member or role.

Тип результата:

Permissions

property permissions_synced: bool

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

If there is no category then this is False.

Добавлено в версии 1.3.

await purge(*, limit=100, check=..., 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. The read_message_history permission is also needed to retrieve message history.

Параметры:
  • limit (int | None) – 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 (Snowflake | datetime | None) – Same as before in history().

  • after (Snowflake | datetime | None) – Same as after in history().

  • around (Snowflake | datetime | None) – Same as around in history().

  • oldest_first (bool | None) – 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 messages are older than two weeks.

  • reason (str | None) – The reason for deleting the messages. Shows up on the audit log.

Результат:

The list of messages that were deleted.

Тип результата:

list[Message]

Исключение:
  • Forbidden – You do not have proper permissions to do the actions required.

  • HTTPException – Purging the messages failed.

Примеры

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(f'Deleted {len(deleted)} message(s)')
property requires_tag: bool

Whether a tag is required to be specified when creating a thread in this forum or media channel.

Tags are specified in applied_tags.

Добавлено в версии 2.3.

await set_permissions(target, *, overwrite=..., 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.

Примечание

This method replaces the old overwrites with the ones given.

Примеры

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)
Параметры:
  • 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.

Исключение:
  • 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.

property threads: list[Thread]

Returns all the threads that you can see.

Добавлено в версии 2.0.

property type: ChannelType

The channel’s Discord type.

await webhooks()

This function is a coroutine.

Gets the list of webhooks from this channel.

Requires manage_webhooks permissions.

Результат:

The webhooks for this channel.

Тип результата:

list[Webhook]

Исключение:

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

class discord.VoiceChannel(*, state, guild, data)[исходный код]

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. Can be None if the channel was received in an interaction.

Type:

Optional[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 voice channel.

Type:

int

rtc_region

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

Добавлено в версии 1.7.

Type:

Optional[VoiceRegion]

video_quality_mode

The camera video quality for the voice channel’s participants.

Добавлено в версии 2.0.

Type:

VideoQualityMode

last_message_id

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

Добавлено в версии 2.0.

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.

Добавлено в версии 2.5.

Type:

int

status

The channel’s status, if set.

Добавлено в версии 2.5.

Type:

Optional[str]

flags

Extra features of the channel.

Добавлено в версии 2.0.

Type:

ChannelFlags

nsfw

Whether the channel is marked as NSFW.

Добавлено в версии 2.7.

Type:

bool

Параметры:
  • state (ConnectionState)

  • guild (Guild)

  • data (VoiceChannel)

is_nsfw()[исходный код]

Checks if the channel is NSFW.

Тип результата:

bool

property last_message: Message | None

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.

Результат:

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

Тип результата:

Optional[Message]

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.

Добавлено в версии 1.6.

Параметры:

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

Результат:

The partial message.

Тип результата:

PartialMessage

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.

Параметры:
  • messages (Iterable[Snowflake]) – An iterable of messages denoting which ones to bulk delete.

  • reason (str | None) – The reason for deleting the messages. Shows up on the audit log.

Исключение:
  • ClientException – The number of messages to delete was more than 100.

  • Forbidden – You do not have proper permissions to delete the messages.

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

  • HTTPException – Deleting the messages failed.

Тип результата:

None

await purge(*, limit=100, check=..., 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. The read_message_history permission is also needed to retrieve message history.

Параметры:
Результат:

The list of messages that were deleted.

Тип результата:

list[Message]

Исключение:
  • Forbidden – You do not have proper permissions to do the actions required.

  • HTTPException – Purging the messages failed.

Примеры

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(f'Deleted {len(deleted)} message(s)')
await webhooks()[исходный код]

This function is a coroutine.

Gets the list of webhooks from this channel.

Requires manage_webhooks permissions.

Результат:

The webhooks for this channel.

Тип результата:

list[Webhook]

Исключение:

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

await create_webhook(*, name, avatar=None, reason=None)[исходный код]

This function is a coroutine.

Creates a webhook for this channel.

Requires manage_webhooks permissions.

Изменено в версии 1.1: Added the reason keyword-only parameter.

Параметры:
  • name (str) – The webhook’s name.

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

  • reason (str | None) – The reason for creating this webhook. Shows up in the audit logs.

Результат:

The created webhook.

Тип результата:

Webhook

Исключение:
  • HTTPException – Creating the webhook failed.

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

property type: ChannelType

The channel’s Discord type.

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.

Добавлено в версии 1.1.

Параметры:
  • name (str | None) – The name of the new channel. If not provided, defaults to this channel name.

  • reason (str | None) – The reason for cloning this channel. Shows up on the audit log.

Результат:

The channel that was created.

Тип результата:

VoiceChannel

Исключение:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

await edit(*, reason=None, **options)[исходный код]

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

Изменено в версии 1.3: The overwrites keyword-only parameter was added.

Изменено в версии 2.0: Edits are no longer in-place, the newly edited channel is returned instead.

Параметры:
  • 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[Union[Role, Member, Snowflake], PermissionOverwrite]) – The overwrites to apply to channel permissions. Useful for creating secret channels.

  • rtc_region (Optional[VoiceRegion]) –

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

    Добавлено в версии 1.7.

  • video_quality_mode (VideoQualityMode) –

    The camera video quality for the voice channel’s participants.

    Добавлено в версии 2.0.

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

  • nsfw (bool) –

    Whether the channel is marked as NSFW.

    Добавлено в версии 2.7.

Результат:

The newly edited voice channel. If the edit was only positional then None is returned instead.

Тип результата:

Optional[VoiceChannel]

Исключение:
  • 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 create_activity_invite(activity, **kwargs)[исходный код]

This function is a coroutine.

A shortcut method that creates an instant activity invite.

You must have the start_embedded_activities permission to do this.

Параметры:
  • activity (EmbeddedActivity | int) – The activity to create an invite for which can be an application id as well.

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

Результат:

The invite that was created.

Тип результата:

Invite

Исключение:
  • TypeError – If the activity is not a valid activity or application id.

  • HTTPException – Invite creation failed.

await set_status(status, *, reason=None)[исходный код]

This function is a coroutine.

Sets the status of the voice channel.

You must have the set_voice_channel_status permission to use this.

Параметры:
  • status (str | None) – The new status.

  • reason (str | None) – The reason for setting the status. Shows up on the audit log.

Исключение:
  • Forbidden – You do not have proper permissions to set the status.

  • HTTPException – Setting the status failed.

Тип результата:

None

await send_soundboard_sound(sound)[исходный код]

This function is a coroutine.

Sends a soundboard sound to the voice channel.

Параметры:

sound (PartialSoundboardSound) – The soundboard sound to send.

Исключение:
  • Forbidden – You do not have proper permissions to send the soundboard sound.

  • HTTPException – Sending the soundboard sound failed.

Тип результата:

None

can_send(*objects)

Returns a bool indicating whether you have the permissions to send the object(s).

Результат:

Indicates whether you have the permissions to send the object(s).

Тип результата:

bool

Исключение:

TypeError – An invalid type has been passed.

property category: CategoryChannel | None

The category this channel belongs to.

If there is no category then this is None.

property changed_roles: list[Role]

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

await connect(*, timeout=60.0, reconnect=True, cls=...)

This function is a coroutine.

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

This requires Intents.voice_states.

Параметры:
  • 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 (Callable[[Client, Connectable], TypeVar(T, bound= VoiceProtocol)]) – A type that subclasses VoiceProtocol to connect with. Defaults to VoiceClient.

Результат:

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

Тип результата:

TypeVar(T, bound= VoiceProtocol)

Исключение:
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, roles=None, target_users_file=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.

Параметры:
  • 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 (str | None) – The reason for creating this invite. Shows up on the audit log.

  • target_type (InviteTarget | None) –

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

    Добавлено в версии 2.0.

  • target_user (User | None) –

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

    Добавлено в версии 2.0.

  • target_application_id (int | None) –

    The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    Добавлено в версии 2.0.

  • target_event (ScheduledEvent | None) –

    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.

    Добавлено в версии 2.0.

  • roles (list[Role | Object] | None) –

    The roles to give a user when joining through this invite.

    You must have the manage_roles permission to do this and roles cannot be higher than your own.

    Добавлено в версии 2.8.

  • target_users_file (File | None) –

    A CSV file with a single column of user IDs for all the users able to accept this invite.

    You can use utils.users_to_csv() to generate a virtual CSV file from a sequence of user IDs.

    Добавлено в версии 2.8.

Результат:

The invite that was created.

Тип результата:

Invite

Исключение:
  • HTTPException – Invite creation failed.

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

property created_at: datetime

Returns the channel’s creation time in UTC.

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

Параметры:

reason (str | None) – The reason for deleting this channel. Shows up on the audit log.

Исключение:
  • 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.

Тип результата:

None

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

Параметры:

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

Результат:

The message asked for.

Тип результата:

Message

Исключение:
  • NotFound – The specified message was not found.

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

  • HTTPException – Retrieving the message failed.

history(*, limit=100, before=None, after=None, around=None, oldest_first=None)

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

You must have read_message_history permissions to use this.

Параметры:
  • limit (int | None) – 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 (Snowflake | datetime | None) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Snowflake | datetime | None) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.

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

Yields:

Message – The message with the message data parsed.

Исключение:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Тип результата:

HistoryIterator

Примеры

Usage

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

Flattening into a list:

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

All parameters are optional.

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

Результат:

The list of invites that are currently active.

Тип результата:

list[Invite]

Исключение:
  • Forbidden – You do not have proper permissions to get the information.

  • HTTPException – An error occurred while fetching the information.

property jump_url: str

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

Добавлено в версии 2.0.

property members: list[Member]

Returns all members that are currently inside this voice channel.

property mention: str

The string that allows you to mention the channel.

await move(**kwargs)

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.

Примечание

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

Добавлено в версии 1.7.

Параметры:
  • 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.

Исключение:
  • InvalidArgument – An invalid position was given or a bad mix of arguments was passed.

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

  • HTTPException – Moving the channel failed.

Тип результата:

None

property overwrites: dict[Role | Member, PermissionOverwrite]

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.

Результат:

The channel’s permission overwrites.

Тип результата:

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

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

Параметры:

obj (Role | User) – The role or user denoting whose overwrite to get.

Результат:

The permission overwrites for this object.

Тип результата:

PermissionOverwrite

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Изменено в версии 2.0: The object passed in can now be a role object.

Параметры:

obj (Member | Role) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

Результат:

The resolved permissions for the member or role.

Тип результата:

Permissions

property permissions_synced: bool

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

If there is no category then this is False.

Добавлено в версии 1.3.

pins(*, limit=50, before=None)

Returns a MessagePinIterator that enables receiving the destination’s pinned messages.

You must have read_message_history permissions to use this.

Предупреждение

Starting from version 3.0, await channel.pins() will no longer return a list of Message. See examples below for new usage instead.

Параметры:
  • limit (int | None) – The number of pinned messages to retrieve. If None, retrieves every pinned message in the channel.

  • before (Snowflake | datetime | None) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

Yields:

MessagePin – The pinned message.

Исключение:
  • Forbidden – You do not have permissions to get pinned messages.

  • HTTPException – The request to get pinned messages failed.

Тип результата:

MessagePinIterator

Примеры

Usage

counter = 0
async for pin in channel.pins(limit=250):
    if pin.message.author == client.user:
        counter += 1

Flattening into a list:

pins = await channel.pins(limit=None).flatten()
# pins is now a list of MessagePin...

All parameters are optional.

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, suppress_embeds=None, silent=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Параметры:
  • content (Optional[str]) – The content of the message to send.

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

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

  • file (File) – The file to upload.

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

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

  • enforce_nonce (Optional[bool]) –

    Whether nonce is enforced to be validated.

    Добавлено в версии 2.5.

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

  • allowed_mentions (AllowedMentions) –

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

    Добавлено в версии 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message being replied to or forwarded. This can be created using to_reference(). When replying, 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.

    Добавлено в версии 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    Добавлено в версии 1.6.

  • view (discord.ui.BaseView) – A Discord UI View to add to the message.

  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    Добавлено в версии 2.0.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    Добавлено в версии 2.0.

  • suppress (bool) –

    Whether to suppress embeds for the message.

    Устарело, начиная с версии 2.8.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message.

    Добавлено в версии 2.8.

  • silent (bool) –

    Whether to suppress push and desktop notifications for the message.

    Добавлено в версии 2.4.

  • poll (Poll) –

    The poll to send.

    Добавлено в версии 2.6.

Результат:

The message that was sent.

Тип результата:

Message

Исключение:
await set_permissions(target, *, overwrite=..., 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.

Примечание

This method replaces the old overwrites with the ones given.

Примеры

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)
Параметры:
  • 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.

Исключение:
  • 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.

Тип результата:

None

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.

Примечание

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():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
Тип результата:

Typing

property voice_states: dict[int, VoiceState]

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

Добавлено в версии 1.3.

Примечание

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

Результат:

The mapping of member ID to a voice state.

Тип результата:

Mapping[int, VoiceState]

class discord.CategoryChannel(*, state, guild, data)[исходный код]

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. Can be None if the channel was received in an interaction.

Type:

Optional[int]

flags

Extra features of the channel.

Добавлено в версии 2.0.

Type:

ChannelFlags

Параметры:
  • state (ConnectionState)

  • guild (Guild)

  • data (CategoryChannel)

property type: ChannelType

The channel’s Discord type.

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.

Добавлено в версии 1.1.

Параметры:
  • name (str | None) – The name of the new channel. If not provided, defaults to this channel name.

  • reason (str | None) – The reason for cloning this channel. Shows up on the audit log.

Результат:

The channel that was created.

Тип результата:

CategoryChannel

Исключение:
  • Forbidden – You do not have the proper permissions to create this channel.

  • HTTPException – Creating the channel failed.

await edit(*, reason=None, **options)[исходный код]

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

Изменено в версии 1.3: The overwrites keyword-only parameter was added.

Изменено в версии 2.0: Edits are no longer in-place, the newly edited channel is returned instead.

Параметры:
  • name (str) – The new category’s name.

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

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

  • overwrites (Dict[Union[Role, Member, Snowflake], PermissionOverwrite]) – The overwrites to apply to channel permissions. Useful for creating secret channels.

Результат:

The newly edited category channel. If the edit was only positional then None is returned instead.

Тип результата:

Optional[CategoryChannel]

Исключение:
  • 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(**kwargs) 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.

Примечание

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

Добавлено в версии 1.7.

Параметры:
  • 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.

Исключение:
  • InvalidArgument – An invalid position was given or a bad mix of arguments was passed.

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

  • HTTPException – Moving the channel failed.

property channels: list[VoiceChannel | StageChannel | TextChannel | ForumChannel | CategoryChannel]

Returns the channels that are under this category.

These are sorted by the official Discord UI, which places voice channels below the text channels.

property text_channels: list[TextChannel]

Returns the text channels that are under this category.

property voice_channels: list[VoiceChannel]

Returns the voice channels that are under this category.

property stage_channels: list[StageChannel]

Returns the stage channels that are under this category.

Добавлено в версии 1.7.

property forum_channels: list[ForumChannel]

Returns the forum channels that are under this category.

Добавлено в версии 2.0.

await create_text_channel(name, **options)[исходный код]

This function is a coroutine.

A shortcut method to Guild.create_text_channel() to create a TextChannel in the category.

Результат:

The channel that was just created.

Тип результата:

TextChannel

Параметры:
await create_voice_channel(name, **options)[исходный код]

This function is a coroutine.

A shortcut method to Guild.create_voice_channel() to create a VoiceChannel in the category.

Результат:

The channel that was just created.

Тип результата:

VoiceChannel

Параметры:
await create_stage_channel(name, **options)[исходный код]

This function is a coroutine.

A shortcut method to Guild.create_stage_channel() to create a StageChannel in the category.

Добавлено в версии 1.7.

Результат:

The channel that was just created.

Тип результата:

StageChannel

Параметры:
await create_forum_channel(name, **options)[исходный код]

This function is a coroutine.

A shortcut method to Guild.create_forum_channel() to create a ForumChannel in the category.

Добавлено в версии 2.0.

Результат:

The channel that was just created.

Тип результата:

ForumChannel

Параметры:
property category: CategoryChannel | None

The category this channel belongs to.

If there is no category then this is None.

property changed_roles: list[Role]

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

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None, roles=None, target_users_file=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.

Параметры:
  • 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 (str | None) – The reason for creating this invite. Shows up on the audit log.

  • target_type (InviteTarget | None) –

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

    Добавлено в версии 2.0.

  • target_user (User | None) –

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

    Добавлено в версии 2.0.

  • target_application_id (int | None) –

    The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.

    Добавлено в версии 2.0.

  • target_event (ScheduledEvent | None) –

    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.

    Добавлено в версии 2.0.

  • roles (list[Role | Object] | None) –

    The roles to give a user when joining through this invite.

    You must have the manage_roles permission to do this and roles cannot be higher than your own.

    Добавлено в версии 2.8.

  • target_users_file (File | None) –

    A CSV file with a single column of user IDs for all the users able to accept this invite.

    You can use utils.users_to_csv() to generate a virtual CSV file from a sequence of user IDs.

    Добавлено в версии 2.8.

Результат:

The invite that was created.

Тип результата:

Invite

Исключение:
  • HTTPException – Invite creation failed.

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

property created_at: datetime

Returns the channel’s creation time in UTC.

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

Параметры:

reason (str | None) – The reason for deleting this channel. Shows up on the audit log.

Исключение:
  • 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.

Тип результата:

None

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.

Результат:

The list of invites that are currently active.

Тип результата:

list[Invite]

Исключение:
  • Forbidden – You do not have proper permissions to get the information.

  • HTTPException – An error occurred while fetching the information.

property jump_url: str

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

Добавлено в версии 2.0.

property mention: str

The string that allows you to mention the channel.

property overwrites: dict[Role | Member, PermissionOverwrite]

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.

Результат:

The channel’s permission overwrites.

Тип результата:

Dict[Union[Role, Member], PermissionOverwrite]

overwrites_for(obj)

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

Параметры:

obj (Role | User) – The role or user denoting whose overwrite to get.

Результат:

The permission overwrites for this object.

Тип результата:

PermissionOverwrite

permissions_for(obj, /)

Handles permission resolution for the Member or Role.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

If a Role is passed, then it checks the permissions someone with that role would have, which is essentially:

  • The default role permissions

  • The permissions of the role used as a parameter

  • The default role permission overwrites

  • The permission overwrites of the role used as a parameter

Изменено в версии 2.0: The object passed in can now be a role object.

Параметры:

obj (Member | Role) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.

Результат:

The resolved permissions for the member or role.

Тип результата:

Permissions

property permissions_synced: bool

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

If there is no category then this is False.

Добавлено в версии 1.3.

await set_permissions(target, *, overwrite=..., 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.

Примечание

This method replaces the old overwrites with the ones given.

Примеры

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)
Параметры:
  • 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.

Исключение:
  • 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.

class discord.DMChannel(*, me, state, data)[исходный код]

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. If this channel is received through the gateway, the recipient information may not be always available.

Type:

Optional[User]

me

The user presenting yourself.

Type:

ClientUser

id

The direct message channel ID.

Type:

int

Параметры:
  • me (ClientUser)

  • state (ConnectionState)

  • data (DMChannel)

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.

Параметры:
  • limit (int | None) – 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 (Snowflake | datetime | None) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Snowflake | datetime | None) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.

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

Yields:

Message – The message with the message data parsed.

Исключение:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Тип результата:

HistoryIterator

Примеры

Usage

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

Flattening into a list:

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

All parameters are optional.

async with typing()

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

This is useful for denoting long computations in your bot.

Примечание

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():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
Тип результата:

Typing

property type: ChannelType

The channel’s Discord type.

property jump_url: str

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

Добавлено в версии 2.0.

property created_at: datetime

Returns the direct message channel’s creation time in UTC.

permissions_for(obj=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:

Параметры:

obj (Any) – The user to check permissions for. This parameter is ignored but kept for compatibility with other permissions_for methods.

Результат:

The resolved permissions.

Тип результата:

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.

Добавлено в версии 1.6.

Параметры:

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

Результат:

The partial message.

Тип результата:

PartialMessage

can_send(*objects)

Returns a bool indicating whether you have the permissions to send the object(s).

Результат:

Indicates whether you have the permissions to send the object(s).

Тип результата:

bool

Исключение:

TypeError – An invalid type has been passed.

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

Параметры:

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

Результат:

The message asked for.

Тип результата:

Message

Исключение:
  • NotFound – The specified message was not found.

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

  • HTTPException – Retrieving the message failed.

pins(*, limit=50, before=None)

Returns a MessagePinIterator that enables receiving the destination’s pinned messages.

You must have read_message_history permissions to use this.

Предупреждение

Starting from version 3.0, await channel.pins() will no longer return a list of Message. See examples below for new usage instead.

Параметры:
  • limit (int | None) – The number of pinned messages to retrieve. If None, retrieves every pinned message in the channel.

  • before (Snowflake | datetime | None) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

Yields:

MessagePin – The pinned message.

Исключение:
  • Forbidden – You do not have permissions to get pinned messages.

  • HTTPException – The request to get pinned messages failed.

Тип результата:

MessagePinIterator

Примеры

Usage

counter = 0
async for pin in channel.pins(limit=250):
    if pin.message.author == client.user:
        counter += 1

Flattening into a list:

pins = await channel.pins(limit=None).flatten()
# pins is now a list of MessagePin...

All parameters are optional.

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, suppress_embeds=None, silent=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Параметры:
  • content (Optional[str]) – The content of the message to send.

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

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

  • file (File) – The file to upload.

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

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

  • enforce_nonce (Optional[bool]) –

    Whether nonce is enforced to be validated.

    Добавлено в версии 2.5.

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

  • allowed_mentions (AllowedMentions) –

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

    Добавлено в версии 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message being replied to or forwarded. This can be created using to_reference(). When replying, 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.

    Добавлено в версии 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    Добавлено в версии 1.6.

  • view (discord.ui.BaseView) – A Discord UI View to add to the message.

  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    Добавлено в версии 2.0.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    Добавлено в версии 2.0.

  • suppress (bool) –

    Whether to suppress embeds for the message.

    Устарело, начиная с версии 2.8.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message.

    Добавлено в версии 2.8.

  • silent (bool) –

    Whether to suppress push and desktop notifications for the message.

    Добавлено в версии 2.4.

  • poll (Poll) –

    The poll to send.

    Добавлено в версии 2.6.

Результат:

The message that was sent.

Тип результата:

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.

Тип результата:

None

class discord.GroupChannel(*, me, state, data)[исходный код]

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:

Optional[User]

owner_id

The owner ID that owns the group channel.

Добавлено в версии 2.0.

Type:

int

name

The group channel’s name if provided.

Type:

Optional[str]

Параметры:
  • me (ClientUser)

  • state (ConnectionState)

  • data (GroupDMChannel)

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.

Параметры:
  • limit (int | None) – 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 (Snowflake | datetime | None) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • after (Snowflake | datetime | None) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

  • around (Snowflake | datetime | None) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.

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

Yields:

Message – The message with the message data parsed.

Исключение:
  • Forbidden – You do not have permissions to get channel message history.

  • HTTPException – The request to get message history failed.

Тип результата:

HistoryIterator

Примеры

Usage

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

Flattening into a list:

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

All parameters are optional.

async with typing()

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

This is useful for denoting long computations in your bot.

Примечание

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():
    # simulate something heavy
    await asyncio.sleep(10)

await channel.send('done!')
Тип результата:

Typing

property type: ChannelType

The channel’s Discord type.

property icon: Asset | None

Returns the channel’s icon asset if available.

property created_at: datetime

Returns the channel’s creation time in UTC.

property jump_url: str

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

Добавлено в версии 2.0.

permissions_for(obj, /)[исходный код]

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.

Параметры:

obj (Snowflake) – The user to check permissions for.

Результат:

The resolved permissions for the user.

Тип результата:

Permissions

await leave()[исходный код]

This function is a coroutine.

Leave the group.

If you are the only one in the group, this deletes it as well.

Исключение:

HTTPException – Leaving the group failed.

Тип результата:

None

can_send(*objects)

Returns a bool indicating whether you have the permissions to send the object(s).

Результат:

Indicates whether you have the permissions to send the object(s).

Тип результата:

bool

Исключение:

TypeError – An invalid type has been passed.

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

Параметры:

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

Результат:

The message asked for.

Тип результата:

Message

Исключение:
  • NotFound – The specified message was not found.

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

  • HTTPException – Retrieving the message failed.

pins(*, limit=50, before=None)

Returns a MessagePinIterator that enables receiving the destination’s pinned messages.

You must have read_message_history permissions to use this.

Предупреждение

Starting from version 3.0, await channel.pins() will no longer return a list of Message. See examples below for new usage instead.

Параметры:
  • limit (int | None) – The number of pinned messages to retrieve. If None, retrieves every pinned message in the channel.

  • before (Snowflake | datetime | None) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.

Yields:

MessagePin – The pinned message.

Исключение:
  • Forbidden – You do not have permissions to get pinned messages.

  • HTTPException – The request to get pinned messages failed.

Тип результата:

MessagePinIterator

Примеры

Usage

counter = 0
async for pin in channel.pins(limit=250):
    if pin.message.author == client.user:
        counter += 1

Flattening into a list:

pins = await channel.pins(limit=None).flatten()
# pins is now a list of MessagePin...

All parameters are optional.

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, suppress_embeds=None, silent=None)

This function is a coroutine.

Sends a message to the destination with the content given.

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

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Параметры:
  • content (Optional[str]) – The content of the message to send.

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

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

  • file (File) – The file to upload.

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

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

  • enforce_nonce (Optional[bool]) –

    Whether nonce is enforced to be validated.

    Добавлено в версии 2.5.

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

  • allowed_mentions (AllowedMentions) –

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

    Добавлено в версии 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) –

    A reference to the Message being replied to or forwarded. This can be created using to_reference(). When replying, 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.

    Добавлено в версии 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    Добавлено в версии 1.6.

  • view (discord.ui.BaseView) – A Discord UI View to add to the message.

  • embeds (List[Embed]) –

    A list of embeds to upload. Must be a maximum of 10.

    Добавлено в версии 2.0.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) –

    A list of stickers to upload. Must be a maximum of 3.

    Добавлено в версии 2.0.

  • suppress (bool) –

    Whether to suppress embeds for the message.

    Устарело, начиная с версии 2.8.

  • suppress_embeds (bool) –

    Whether to suppress embeds for the message.

    Добавлено в версии 2.8.

  • silent (bool) –

    Whether to suppress push and desktop notifications for the message.

    Добавлено в версии 2.4.

  • poll (Poll) –

    The poll to send.

    Добавлено в версии 2.6.

Результат:

The message that was sent.

Тип результата:

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.

Тип результата:

None

Stickers

class discord.Sticker(*, state, data)[исходный код]

Represents a sticker.

Добавлено в версии 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:

StickerFormatType

url

The URL for the sticker’s image.

Type:

str

Параметры:
  • state (ConnectionState)

  • data (BaseSticker | StandardSticker | GuildSticker)

property created_at: datetime

Returns the sticker’s creation time in UTC.

class discord.StickerPack(*, state, data)[исходный код]

Represents a sticker pack.

Добавлено в версии 2.0.

str(x)

Returns the name of the sticker pack.

x == y

Checks if the sticker pack is equal to another sticker pack.

x != y

Checks if the sticker pack is not equal to another sticker pack.

name

The name of the sticker pack.

Type:

str

description

The description of the sticker pack.

Type:

str

id

The id of the sticker pack.

Type:

int

stickers

The stickers of this sticker pack.

Type:

List[StandardSticker]

sku_id

The SKU ID of the sticker pack.

Type:

int

cover_sticker_id

The ID of the sticker used for the cover of the sticker pack.

Type:

int

cover_sticker

The sticker used for the cover of the sticker pack.

Type:

StandardSticker

Параметры:
  • state (ConnectionState)

  • data (StickerPack)

property banner: Asset

The banner asset of the sticker pack.

Attributes
Methods
class discord.StickerItem(*, state, data)[исходный код]

Represents a sticker item.

Добавлено в версии 2.0.

str(x)

Returns the name of the sticker item.

x == y

Checks if the sticker item is equal to another sticker item.

x != y

Checks if the sticker item is not equal to another sticker item.

name

The sticker’s name.

Type:

str

id

The id of the sticker.

Type:

int

format

The format for the sticker’s image.

Type:

StickerFormatType

url

The URL for the sticker’s image.

Type:

str

Параметры:
  • state (ConnectionState)

  • data (StickerItem)

await fetch()[исходный код]

This function is a coroutine.

Attempts to retrieve the full sticker data of the sticker item.

Результат:

The retrieved sticker.

Тип результата:

Sticker | StandardSticker | GuildSticker

Исключение:

HTTPException – Retrieving the sticker failed.

Methods
class discord.StandardSticker(*, state, data)[исходный код]

Represents a sticker that is found in a standard sticker pack.

Добавлено в версии 2.0.

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:

StickerFormatType

tags

A list of tags for the sticker.

Type:

List[str]

sort_value

The sticker’s sort order within its pack.

Type:

int

Параметры:
  • state (ConnectionState)

  • data (BaseSticker | StandardSticker | GuildSticker)

await pack()[исходный код]

This function is a coroutine.

Retrieves the sticker pack that this sticker belongs to.

Результат:

The retrieved sticker pack.

Тип результата:

StickerPack

Исключение:
class discord.GuildSticker(*, state, data)[исходный код]

Represents a sticker that belongs to a guild.

Добавлено в версии 2.0.

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

format

The format for the sticker’s image.

Type:

StickerFormatType

available

Whether this sticker is available for use.

Type:

bool

guild_id

The ID of the guild that this sticker is from.

Type:

int

user

The user that created this sticker. This can only be retrieved using Guild.fetch_sticker() and having the manage_emojis_and_stickers permission.

Type:

Optional[User]

emoji

The name of a unicode emoji that represents this sticker.

Type:

str

Параметры:
  • state (ConnectionState)

  • data (BaseSticker | StandardSticker | GuildSticker)

guild

The guild that this sticker is from. Could be None if the bot is not in the guild.

Добавлено в версии 2.0.

await edit(*, name=..., description=..., emoji=..., reason=None)[исходный код]

This function is a coroutine.

Edits a GuildSticker for the guild.

Параметры:
  • name (str) – The sticker’s new name. Must be at least 2 characters.

  • description (str) – The sticker’s new description. Can be None.

  • emoji (str) – The name of a unicode emoji that represents the sticker’s expression.

  • reason (str | None) – The reason for editing this sticker. Shows up on the audit log.

Результат:

The newly modified sticker.

Тип результата:

GuildSticker

Исключение:
  • Forbidden – You are not allowed to edit stickers.

  • HTTPException – An error occurred editing the sticker.

await delete(*, reason=None)[исходный код]

This function is a coroutine.

Deletes the custom Sticker from the guild.

You must have manage_emojis_and_stickers permission to do this.

Параметры:

reason (str | None) – The reason for deleting this sticker. Shows up on the audit log.

Исключение:
  • Forbidden – You are not allowed to delete stickers.

  • HTTPException – An error occurred deleting the sticker.

Тип результата:

None

Soundboard

Attributes
class discord.PartialSoundboardSound(data, state, http)[исходный код]

A partial soundboard sound.

Добавлено в версии 2.7.

id

The sound’s ID.

Type:

int

volume

The sound’s volume.

Type:

float

emoji

The sound’s emoji. Could be None if the sound has no emoji.

Type:

PartialEmoji | None

Параметры:
  • data (SoundboardSound | VoiceChannelEffectSendEvent)

  • state (ConnectionState)

  • http (HTTPClient)

property file: Asset

Returns the sound’s file.

Type:

Asset

class discord.SoundboardSound(*, state, http, data)[исходный код]

Represents a soundboard sound.

Добавлено в версии 2.7.

id

The sound’s ID.

Type:

int

volume

The sound’s volume.

Type:

float

emoji

The sound’s emoji. Could be None if the sound has no emoji.

Type:

PartialEmoji | None

name

The sound’s name.

Type:

str

available

Whether the sound is available. Could be False if the sound is not available. This is the case, for example, when the guild loses the boost level required to use the sound.

Type:

bool

guild_id

The ID of the guild to which the sound belongs. Could be None if the sound is a default sound.

Type:

int | None

user

The sound’s owner. Could be None if the sound is a default sound.

Type:

User | None

Параметры:
  • state (ConnectionState)

  • http (HTTPClient)

  • data (SoundboardSound)

guild

Guild | None The guild the sound belongs to. Could be None if the sound is a default sound.

property is_default_sound: bool

Whether the sound is a default sound.

Type:

bool

edit(*, name=None, volume=None, emoji=None, reason=None)[исходный код]

Edits the sound.

Добавлено в версии 2.7.

Параметры:
  • name (str | None) – The new name of the sound.

  • volume (float | None) – The new volume of the sound.

  • emoji (PartialEmoji | str | None) – The new emoji of the sound.

  • reason (str | None) – The reason for editing the sound. Shows up in the audit log.

Результат:

The edited sound.

Тип результата:

Coroutine[Any, Any, SoundboardSound]

Исключение:

ValueError – Editing a default sound is not allowed.

delete(*, reason=None)[исходный код]

Deletes the sound.

Добавлено в версии 2.7.

Параметры:

reason (str | None) – The reason for deleting the sound. Shows up in the audit log.

Исключение:

ValueError – Deleting a default sound is not allowed.

Тип результата:

Coroutine[Any, Any, None]

property file: Asset

Returns the sound’s file.

Type:

Asset

Events

class discord.AutoModActionExecutionEvent(state, data)[исходный код]

Represents the payload for an on_auto_moderation_action_execution()

Добавлено в версии 2.0.

action

The action that was executed.

Type:

AutoModAction

rule_id

The ID of the rule that the action belongs to.

Type:

int

rule_trigger_type

The category of trigger the rule belongs to.

Добавлено в версии 2.4.

Type:

AutoModTriggerType

guild_id

The ID of the guild that the action was executed in.

Type:

int

guild

The guild that the action was executed in, if cached.

Type:

Optional[Guild]

user_id

The ID of the user that triggered the action.

Type:

int

member

The member that triggered the action, if cached.

Type:

Optional[Member]

channel_id

The ID of the channel in which the member’s content was posted.

Type:

Optional[int]

channel

The channel in which the member’s content was posted, if cached.

Type:

Optional[Union[TextChannel, Thread, VoiceChannel, StageChannel]]

message_id

The ID of the message that triggered the action. This is only available if the message was not blocked.

Type:

Optional[int]

message

The message that triggered the action, if cached.

Type:

Optional[Message]

alert_system_message_id

The ID of the system auto moderation message that was posted as a result of the action.

Type:

Optional[int]

alert_system_message

The system auto moderation message that was posted as a result of the action, if cached.

Type:

Optional[Message]

content

The content of the message that triggered the action.

Type:

str

matched_keyword

The word or phrase configured that was matched in the content.

Type:

str

matched_content

The substring in the content that was matched.

Type:

str

data

The raw data sent by the gateway.

Добавлено в версии 2.5.

Type:

dict

Параметры:
  • state (ConnectionState)

  • data (AutoModActionExecutionEvent)

class discord.RawTypingEvent(data)[исходный код]

Represents the payload for a on_raw_typing() event.

Добавлено в версии 2.0.

channel_id

The channel ID where the typing originated from.

Type:

int

user_id

The ID of the user that started typing.

Type:

int

when

When the typing started as an aware datetime in UTC.

Type:

datetime.datetime

guild_id

The guild ID where the typing originated from, if applicable.

Type:

Optional[int]

member

The member who started typing. Only available if the member started typing in a guild.

Type:

Optional[Member]

data

The raw data sent by the gateway.

Добавлено в версии 2.5.

Type:

dict

Параметры:

data (TypingEvent)

class discord.RawMessageDeleteEvent(data)[исходный код]

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]

data

The raw data sent by the gateway.

Добавлено в версии 2.5.

Type:

dict

Параметры:

data (MessageDeleteEvent)

class discord.RawBulkMessageDeleteEvent(data)[исходный код]

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]

data

The raw data sent by the gateway.

Добавлено в версии 2.5.

Type:

dict

Параметры:

data (BulkMessageDeleteEvent)

class discord.RawMessageUpdateEvent(data, new_message)[исходный код]

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.

Добавлено в версии 1.3.

Type:

int

guild_id

The guild ID where the message got updated, if applicable.

Добавлено в версии 1.7.

Type:

Optional[int]

data

The raw data sent 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]

new_message

The new message object. Represents the message after it is modified by the data in RawMessageUpdateEvent.data.

Добавлено в версии 2.7.

Type:

Message

Параметры:
  • data (MessageUpdateEvent)

  • new_message (Message)

class discord.RawReactionActionEvent(data, emoji, event_type)[исходный код]

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 the reaction occurs within a guild.

Добавлено в версии 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.

Добавлено в версии 1.3.

Type:

str

burst

Whether this reaction is a burst (super) reaction.

Type:

bool

burst_colours

A list of hex codes this reaction can be. Only available if event_type is REACTION_ADD and this emoji has super reactions available.

Type:

Optional[list]

burst_colors

Alias for burst_colours.

Type:

Optional[list]

type

The type of reaction added.

Type:

ReactionType

data

The raw data sent by the gateway.

Добавлено в версии 2.5.

Type:

dict

Параметры:
class discord.RawReactionClearEvent(data)[исходный код]

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]

data

The raw data sent by the gateway.

Добавлено в версии 2.5.

Type:

dict

Параметры:

data (ReactionClearEvent)

class discord.RawReactionClearEmojiEvent(data, emoji)[исходный код]

Represents the payload for a on_raw_reaction_clear_emoji() event.

Добавлено в версии 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

burst

Whether this reaction was a burst (super) reaction.

Type:

bool

burst_colours

The available HEX codes of the removed super reaction.

Type:

list

burst_colors

Alias for burst_colours.

Type:

Optional[list]

type

The type of reaction removed.

Type:

ReactionType

data

The raw data sent by the gateway.

Добавлено в версии 2.5.

Type:

dict

Параметры:
class discord.RawIntegrationDeleteEvent(data)[исходный код]

Represents the payload for a on_raw_integration_delete() event.

Добавлено в версии 2.0.

integration_id

The ID of the integration that got deleted.

Type:

int

application_id

The ID of the bot/OAuth2 application for this deleted integration.

Type:

Optional[int]

guild_id

The guild ID where the integration got deleted.

Type:

int

data

The raw data sent by the gateway.

Добавлено в версии 2.5.

Type:

dict

Параметры:

data (IntegrationDeleteEvent)

class discord.RawThreadDeleteEvent(data)[исходный код]

Represents the payload for on_raw_thread_delete() event.

Добавлено в версии 2.0.

thread_id

The ID of the thread that was deleted.

Type:

int

thread_type

The channel type of the deleted thread.

Type:

discord.ChannelType

guild_id

The ID of the guild the deleted thread belonged to.

Type:

int

parent_id

The ID of the channel the thread belonged to.

Type:

int

thread

The thread that was deleted. This may be None if deleted thread is not found in internal cache.

Type:

Optional[discord.Thread]

data

The raw data sent by the gateway.

Добавлено в версии 2.5.

Type:

dict

Параметры:

data (ThreadDeleteEvent)

class discord.RawScheduledEventSubscription(data, event_type)[исходный код]

Represents the payload for a raw_scheduled_event_user_add() or raw_scheduled_event_user_remove() event.

Добавлено в версии 2.0.

event_id

The event ID where the typing originated from.

Type:

int

user_id

The ID of the user that subscribed/unsubscribed.

Type:

int

guild

The guild where the subscription/unsubscription happened.

Type:

Optional[Guild]

event_type

Can be either USER_ADD or USER_REMOVE depending on the event called.

Type:

str

data

The raw data sent by the gateway.

Добавлено в версии 2.5.

Type:

dict

Параметры:
  • data (ScheduledEventSubscription)

  • event_type (str)

Attributes
class discord.RawMemberRemoveEvent(data, user)[исходный код]

Represents the payload for an on_raw_member_remove() event.

Добавлено в версии 2.4.

user

The user that left the guild.

Type:

discord.User

guild_id

The ID of the guild the user left.

Type:

int

data

The raw data sent by the gateway.

Добавлено в версии 2.5.

Type:

dict

Параметры:
  • data (MemberRemoveEvent)

  • user (User)

class discord.RawThreadUpdateEvent(data)[исходный код]

Represents the payload for an on_raw_thread_update() event.

Добавлено в версии 2.4.

thread_id

The ID of the updated thread.

Type:

int

thread_type

The channel type of the updated thread.

Type:

discord.ChannelType

guild_id

The ID of the guild the thread belongs to.

Type:

int

parent_id

The ID of the channel the thread belongs to.

Type:

int

data

The raw data sent by the gateway.

Type:

dict

thread

The thread, if it could be found in the internal cache.

Type:

discord.Thread | None

Параметры:

data (Thread)

class discord.RawThreadMembersUpdateEvent(data)[исходный код]

Represents the payload for an on_raw_thread_member_remove() event.

Добавлено в версии 2.4.

thread_id

The ID of the thread that was updated.

Type:

int

guild_id

The ID of the guild the thread is in.

Type:

int

member_count

The approximate number of members in the thread. Maximum of 50.

Type:

int

data

The raw data sent by the gateway.

Добавлено в версии 2.5.

Type:

dict

Параметры:

data (ThreadMembersUpdateEvent)

class discord.RawAuditLogEntryEvent(data)[исходный код]

Represents the payload for an on_raw_audit_log_entry() event.

Добавлено в версии 2.5.

action_type

The action that was done.

Type:

AuditLogAction

id

The entry ID.

Type:

int

guild_id

The ID of the guild this action came from.

Type:

int

user_id

The ID of the user who initiated this action.

Type:

Optional[int]

target_id

The ID of the target that got changed.

Type:

Optional[int]

reason

The reason this action was done.

Type:

Optional[str]

changes

The changes that were made to the target.

Type:

Optional[list]

extra

Extra information that this entry has that might be useful. For most actions, this is None. However, in some cases it contains extra information. See AuditLogAction for which actions have this field filled out.

Type:

Any

data

The raw data sent by the gateway.

Type:

dict

Параметры:

data (AuditLogEntryEvent)

Attributes
class discord.RawVoiceChannelStatusUpdateEvent(data)[исходный код]

Represents the payload for an on_raw_voice_channel_status_update() event.

Добавлено в версии 2.5.

id

The channel ID where the voice channel status update originated from.

Type:

int

guild_id

The guild ID where the voice channel status update originated from.

Type:

int

status

The new new voice channel status.

Type:

Optional[str]

data

The raw data sent by the gateway.

Type:

dict

Параметры:

data (VoiceChannelStatusUpdateEvent)

class discord.VoiceChannelEffectSendEvent(data, state, sound=None)[исходный код]

Represents the payload for an on_voice_channel_effect_send().

Добавлено в версии 2.7.

animation_type

The type of animation that is being sent.

Type:

int

animation_id

The ID of the animation that is being sent.

Type:

int

sound

The sound that is being sent, could be None if the effect is not a sound effect.

Type:

Optional[SoundboardSound]

guild

The guild in which the sound is being sent.

Type:

Guild

user

The member that sent the sound.

Type:

Member

channel

The voice channel in which the sound is being sent.

Type:

VoiceChannel

data

The raw data sent by the gateway.

Type:

dict

Параметры:

Webhooks

Attributes
class discord.PartialWebhookGuild[исходный код]

Represents a partial guild for webhooks.

These are typically given for channel follower webhooks.

Добавлено в версии 2.0.

id

The partial guild’s ID.

Type:

int

name

The partial guild’s name.

Type:

str

property icon: Asset | None

Returns the guild’s icon asset, if available.

Attributes
class discord.PartialWebhookChannel[исходный код]

Represents a partial channel for webhooks.

These are typically given for channel follower webhooks.

Добавлено в версии 2.0.

id

The partial channel’s ID.

Type:

int

name

The partial channel’s name.

Type:

str

Collectibles

Attributes
class discord.Collectibles(data, state)[исходный код]

Represents a user or member’s equipped collectibles.

Добавлено в версии 2.8.

x == y

Checks if two sets of collectibles are equal.

x != y

Checks if two sets of collectibles are not equal.

nameplate

The user’s nameplate.

Type:

Nameplate

Параметры:
  • data (Collectibles)

  • state (ConnectionState)

Attributes
class discord.Nameplate(data, state)[исходный код]

Represents a Discord Nameplate.

Добавлено в версии 2.7.

Изменено в версии 2.8: Nameplates are now comparable.

x == y

Checks if two nameplates are equal.

x != y

Checks if two nameplates are not equal.

sku_id

The SKU ID of the nameplate.

Type:

int

palette

The color palette of the nameplate.

Type:

str

Параметры:
  • data (Nameplate)

  • state (ConnectionState)