Abstract Base Classes

An abstract base class (also known as an abc) is a class that models can inherit to get their behaviour. The Python implementation of an abc is slightly different in that you can register them at run-time. Abstract base classes cannot be instantiated. They are mainly there for usage with isinstance() and issubclass().

This library has a module related to abstract base classes, some of which are actually from the abc standard module, others which are not.

Snowflake

Attributes
class discord.abc.Snowflake(*args, **kwargs)

Bases: Protocol

An ABC that details the common operations on a Discord model.

Almost all Discord models meet this abstract base class.

If you want to create a snowflake on your own, consider using Object.

id

The model’s unique ID.

Type:

int

User

class discord.abc.User(*args, **kwargs)

Bases: Snowflake, Protocol

An ABC that details the common operations on a Discord user.

The following implement this ABC:

This ABC must also implement Snowflake.

username

The user’s username.

Type:

str

global_name

The users display name, if set.

Type:

Optional[str]

discriminator

The user’s discriminator.

Type:

str

avatar

The avatar hash the user has.

Type:

Optional[str]

bot

If the user is a bot account.

Type:

bool

property name

An alias for name.

Type:

str

property display_name

Returns the user’s display name.

Type:

str

property display_avatar

Returns the user’s display avatar. For regular users this is just their default or uploaded avatar.

Type:

Asset

property mention

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

Type:

str

PrivateChannel

Attributes
class discord.abc.PrivateChannel(*args, **kwargs)

Bases: Snowflake, Protocol

An ABC that details the common operations on a private Discord channel.

The following implement this ABC:

This ABC must also implement Snowflake.

me

The user presenting yourself.

Type:

ClientUser

GuildChannel

class discord.abc.GuildChannel

Bases: object

An ABC that details the common operations on a Discord guild channel.

The following implement this ABC:

This ABC must also implement Snowflake.

name

The channel name.

Type:

str

guild

The guild the channel belongs to.

Type:

Guild

position

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

Type:

int

property changed_roles

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

Type:

List[Role]

property mention

The string that allows you to mention the channel.

Type:

str

property jump_url

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

Added in version 2.0.

Type:

str

property created_at

Returns the channel’s creation time in UTC.

Type:

datetime.datetime

overwrites_for(obj)

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

Parameters:

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

Returns:

The permission overwrites for this object.

Return type:

PermissionOverwrite

property overwrites

Returns all of the channel’s overwrites.

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

Returns:

The channel’s permission overwrites.

Return type:

Mapping[Union[Role, Member], PermissionOverwrite]

property category

The category this channel belongs to.

If there is no category then this is None.

Type:

Optional[CategoryChannel]

property permissions_synced

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

If there is no category then this is False.

Added in version 1.3.

Type:

bool

permissions_for(member, /)

Handles permission resolution for the current Member.

This function takes into consideration the following cases:

  • Guild owner

  • Guild roles

  • Channel overrides

  • Member overrides

Parameters:

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

Returns:

The resolved permissions for the member.

Return type:

Permissions

await delete(*, reason=None)

This function is a coroutine.

Deletes the channel.

You must have manage_channels permission to use this.

Parameters:

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

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

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

  • HTTPException – Deleting the channel failed.

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

This function is a coroutine.

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

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

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

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

You must have the manage_roles permission to use this.

Examples

Setting allow and deny:

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

Deleting overwrites

await channel.set_permissions(member, overwrite=None)

Using PermissionOverwrite

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

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

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

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

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

  • HTTPException – Editing channel specific permissions failed.

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

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

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

This function is a coroutine.

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

You must have the manage_channels permission to do this.

Added in version 1.1.

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

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

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

  • HTTPException – Creating the channel failed.

Returns:

The channel that was created.

Return type:

abc.GuildChannel

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

This function is a coroutine.

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

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

You must have the manage_channels permission to do this.

Note

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

Added in version 1.7.

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

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

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

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

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

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

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

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

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

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

  • HTTPException – Moving the channel failed.

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

This function is a coroutine.

Creates an instant invite from a text or voice channel.

You must have the create_instant_invite permission to do this.

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

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

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

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

  • target_type (Optional[InviteTargetType]) –

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

    Added in version 2.0.

  • target_user (Optional[int]) –

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

    Added in version 2.0.

  • target_application_id (Optional[int]) –

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

    Added in version 2.0.

  • target_event (Optional[GuildScheduledEvent]) –

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

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

    Added in version 2.0.

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

Raises:
  • HTTPException – Invite creation failed.

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

Returns:

The invite that was created.

Return type:

Invite

await invites()

This function is a coroutine.

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

You must have manage_channels to get this information.

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

  • HTTPException – An error occurred while fetching the information.

Returns:

The list of invites that are currently active.

Return type:

List[Invite]

Messageable

Methods
class discord.abc.Messageable

Bases: object

An ABC that details the common operations on a model that can send messages.

The following implement this ABC:

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

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

You must have read_message_history permissions to use this.

Examples

Usage

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

Flattening into a list:

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

All parameters are optional.

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

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

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

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

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

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

  • HTTPException – The request to get message history failed.

Yields:

Message – The message with the message data parsed.

async with typing()

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

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

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

This function is a coroutine.

Sends a message to the destination with the content given.

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

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

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

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

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

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

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

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

  • file (File) – The file to upload.

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

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

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

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

  • allowed_mentions (AllowedMentions) –

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

    Added in version 1.4.

  • reference (Union[Message, MessageReference]) –

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

    Added in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the replied_user attribute of allowed_mentions.

    Added in version 1.6.

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

  • suppress_notifications (bool) –

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

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

    Added in version 2.0.

Raises:
Returns:

The message that was sent.

Return type:

Message

await trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

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

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

This can only be used by bot accounts.

Parameters:

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

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

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

  • HTTPException – Retrieving the message failed.

Returns:

The message asked for.

Return type:

Message

await pins()

This function is a coroutine.

Retrieves all messages that are currently pinned in the channel.

Note

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

Raises:

HTTPException – Retrieving the pinned messages failed.

Returns:

The messages that are currently pinned.

Return type:

List[Message]

Connectable

Methods
class discord.abc.Connectable(*args, **kwargs)

Bases: Protocol

An ABC that details the common operations on a channel that can connect to a voice server.

The following implement this ABC:

Note

This ABC is not decorated with typing.runtime_checkable(), so will fail isinstance()/issubclass() checks.

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

This function is a coroutine.

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

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

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

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

Raises:
Returns:

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

Return type:

VoiceProtocol