discord package

Submodules

discord.abc module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.abc.Snowflake

Bases: object

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

Almost all Discord models meet this abstract base class.

id

int – The model’s unique ID.

created_at

Returns the model’s creation time in UTC.

class discord.abc.User

Bases: object

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

The following implement this ABC:

  • User

  • ClientUser

  • Member

This ABC must also implement abc.Snowflake.

name

str – The user’s username.

discriminator

str – The user’s discriminator.

avatar

Optional[str] – The avatar hash the user has.

bot

bool – If the user is a bot account.

display_name

Returns the user’s display name.

mention

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

class discord.abc.PrivateChannel

Bases: object

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

The following implement this ABC:

  • DMChannel

  • GroupChannel

This ABC must also implement abc.Snowflake.

me

ClientUser – The user presenting yourself.

class discord.abc.GuildChannel

Bases: object

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

The following implement this ABC:

  • TextChannel

  • VoiceChannel

  • CategoryChannel

This ABC must also implement abc.Snowflake.

name

str – The channel name.

guild

Guild – The guild the channel belongs to.

position

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

changed_roles

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

mention

str – The string that allows you to mention the channel.

created_at

Returns the channel’s creation time in UTC.

overwrites_for(obj)

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

Parameters

obj – The Role or abc.User denoting whose overwrite to get.

Returns

The permission overwrites for this object.

Return type

PermissionOverwrite

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]

category

Optional[CategoryChannel] – The category this channel belongs to.

If there is no category then this is None.

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

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

This function is a coroutine.

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

New in version 1.1.0.

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.

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

This function is a coroutine.

Creates an instant invite.

You must have create_instant_invite permission to do this.

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

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

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

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

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

Raises

HTTPException – Invite creation failed.

Returns

The invite that was created.

Return type

Invite

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

coroutine invites()

This function is a coroutine.

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

You must have manage_guild 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]

coroutine set_permissions(target, *, overwrite=see-below, 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 – The Member or Role to overwrite permissions for.

  • overwrite (PermissionOverwrite) – The permissions to allow and deny to the target.

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

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:

  • TextChannel

  • DMChannel

  • GroupChannel

  • User

  • Member

  • Context

This ABC must also implement abc.Snowflake.

coroutine 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

coroutine pins()

This function is a coroutine.

Returns a list of Message that are currently pinned.

Raises

HTTPException – Retrieving the pinned messages failed.

coroutine send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=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.

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

Parameters
  • content – 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 (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.

Raises
  • HTTPException – Sending the message failed.

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

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

Returns

The message that was sent.

Return type

Message

coroutine trigger_typing()

This function is a coroutine.

Triggers a typing indicator to the destination.

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

typing()

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # do expensive stuff here
    await channel.send('done!')
history(*, limit=100, before=None, after=None, around=None, oldest_first=None)

Return 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 (Message or 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 (Message or 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 (Message or 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.

class discord.abc.Connectable

Bases: object

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

The following implement this ABC:

  • VoiceChannel

coroutine connect(*, timeout=60.0, reconnect=True)

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.

Raises
  • asyncio.TimeoutError – Could not connect to the voice channel in time.

  • ClientException – You are already connected to a voice channel.

  • OpusNotLoaded – The opus library has not been loaded.

Returns

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

Return type

VoiceClient

discord.activity module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.activity.Activity(**kwargs)

Bases: discord.activity._ActivityTag

Represents an activity in Discord.

This could be an activity such as streaming, playing, listening or watching.

For memory optimisation purposes, some activities are offered in slimmed down versions:

application_id

int – The application ID of the game.

name

str – The name of the activity.

url

str – A stream URL that the activity could be doing.

type

ActivityType – The type of activity currently being done.

state

str – The user’s current state. For example, “In Game”.

details

str – The detail of the user’s current activity.

timestamps

dict – A dictionary of timestamps. It contains the following optional keys:

  • start: Corresponds to when the user started doing the activity in milliseconds since Unix epoch.

  • end: Corresponds to when the user will finish doing the activity in milliseconds since Unix epoch.

assets

dict – A dictionary representing the images and their hover text of an activity. It contains the following optional keys:

  • large_image: A string representing the ID for the large image asset.

  • large_text: A string representing the text when hovering over the large image asset.

  • small_image: A string representing the ID for the small image asset.

  • small_text: A string representing the text when hovering over the small image asset.

party

dict – A dictionary representing the activity party. It contains the following optional keys:

  • id: A string representing the party ID.

  • size: A list of up to two integer elements denoting (current_size, maximum_size).

state
details
timestamps
assets
party
application_id
name
url
flags
sync_id
session_id
type
to_dict()
start

Optional[datetime.datetime] – When the user started doing this activity in UTC, if applicable.

end

Optional[datetime.datetime] – When the user will stop doing this activity in UTC, if applicable.

large_image_url

Optional[str] – Returns a URL pointing to the large image asset of this activity if applicable.

small_image_url

Optional[str] – Returns a URL pointing to the small image asset of this activity if applicable.

large_image_text

Optional[str] – Returns the large image asset hover text of this activity if applicable.

small_image_text

Optional[str] – Returns the small image asset hover text of this activity if applicable.

class discord.activity.Game(name, **extra)

Bases: discord.activity._ActivityTag

A slimmed down version of Activity that represents a Discord game.

This is typically displayed via Playing on the official Discord client.

x == y

Checks if two games are equal.

x != y

Checks if two games are not equal.

hash(x)

Returns the game’s hash.

str(x)

Returns the game’s name.

Parameters
  • name (str) – The game’s name.

  • start (Optional[datetime.datetime]) – A naive UTC timestamp representing when the game started. Keyword-only parameter. Ignored for bots.

  • end (Optional[datetime.datetime]) – A naive UTC timestamp representing when the game ends. Keyword-only parameter. Ignored for bots.

name

str – The game’s name.

name
type

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

It always returns ActivityType.playing.

start

Optional[datetime.datetime] – When the user started playing this game in UTC, if applicable.

end

Optional[datetime.datetime] – When the user will stop playing this game in UTC, if applicable.

to_dict()
class discord.activity.Streaming(*, name, url, **extra)

Bases: discord.activity._ActivityTag

A slimmed down version of Activity that represents a Discord streaming status.

This is typically displayed via Streaming on the official Discord client.

x == y

Checks if two streams are equal.

x != y

Checks if two streams are not equal.

hash(x)

Returns the stream’s hash.

str(x)

Returns the stream’s name.

name

str – The stream’s name.

url

str – The stream’s URL. Currently only twitch.tv URLs are supported. Anything else is silently discarded.

details

Optional[str] – If provided, typically the game the streamer is playing.

assets

dict – A dictionary comprising of similar keys than those in Activity.assets.

name
url
details
assets
type

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

It always returns ActivityType.streaming.

twitch_name

Optional[str] – If provided, the twitch name of the user streaming.

This corresponds to the large_image key of the Streaming.assets dictionary if it starts with twitch:. Typically set by the Discord client.

to_dict()
class discord.activity.Spotify(**data)

Bases: object

Represents a Spotify listening activity from Discord. This is a special case of Activity that makes it easier to work with the Spotify integration.

x == y

Checks if two activities are equal.

x != y

Checks if two activities are not equal.

hash(x)

Returns the activity’s hash.

str(x)

Returns the string ‘Spotify’.

type

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

It always returns ActivityType.listening.

colour

Returns the Spotify integration colour, as a Colour.

There is an alias for this named color()

color

Returns the Spotify integration colour, as a Colour.

There is an alias for this named colour()

to_dict()
name

str – The activity’s name. This will always return “Spotify”.

title

str – The title of the song being played.

artists

List[str] – The artists of the song being played.

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.

album

str – The album that the song being played belongs to.

album_cover_url

str – The album cover image URL from Spotify’s CDN.

track_id

str – The track ID used by Spotify to identify this song.

start

datetime.datetime – When the user started playing this song in UTC.

end

datetime.datetime – When the user will stop playing this song in UTC.

duration

datetime.timedelta – The duration of the song being played.

party_id

str – The party ID of the listening party.

discord.appinfo module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.appinfo.AppInfo(state, data)

Bases: object

Represents the application info for the bot provided by Discord.

id

int – The application ID.

name

str – The application name.

owner

User – The application owner.

icon

Optional[str] – The icon hash, if it exists.

description

Optional[str] – The application description.

bot_public

bool – Whether the bot can be invited by anyone or if it is locked to the application owner.

bot_require_code_grant

bool – Whether the bot requires the completion of the full oauth2 code grant flow to join.

rpc_origins

Optional[List[str]] – A list of RPC origin URLs, if RPC is enabled.

id
name
description
icon
rpc_origins
bot_public
bot_require_code_grant
owner
icon_url

Asset – Retrieves the application’s icon asset.

discord.asset module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.asset.Asset(state, url=None)

Bases: object

Represents a CDN asset on Discord.

str(x)

Returns the URL of the CDN asset.

len(x)

Returns the length of the CDN asset’s URL.

bool(x)

Checks if the Asset has a URL.

x == y

Checks if the asset is equal to another asset.

x != y

Checks if the asset is not equal to another asset.

hash(x)

Returns the hash of the asset.

coroutine read()

This function is a coroutine.

Retrieves the content of this asset as a bytes object.

Warning

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

New in version 1.1.0.

Raises
  • DiscordException – There was no valid URL or internal connection state.

  • HTTPException – Downloading the asset failed.

  • NotFound – The asset was deleted.

Returns

The content of the asset.

Return type

bytes

coroutine save(fp, *, seek_begin=True)

This function is a coroutine.

Saves this asset into a file-like object.

Parameters
  • fp (Union[BinaryIO, os.PathLike]) – Same as in Attachment.save().

  • seek_begin (bool) – Same as in Attachment.save().

Raises

Same as read().

Returns

The number of bytes written.

Return type

int

discord.audit_logs module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.audit_logs.AuditLogDiff

Bases: object

class discord.audit_logs.AuditLogChanges(entry, data)

Bases: object

TRANSFORMERS = {'afk_channel_id': ('afk_channel', <function _transform_channel at 0x7ff548fcdbf8>), 'allow': (None, <function _transform_permissions at 0x7ff548fcda60>), 'avatar_hash': ('avatar', None), 'channel_id': ('channel', <function _transform_channel at 0x7ff548fcdbf8>), 'color': ('colour', <function _transform_color at 0x7ff548fcdae8>), 'default_message_notifications': ('default_notifications', <function _transform_default_notifications at 0x7ff548fc2378>), 'deny': (None, <function _transform_permissions at 0x7ff548fcda60>), 'explicit_content_filter': (None, <function _transform_explicit_content_filter at 0x7ff548fc2400>), 'icon_hash': ('icon', None), 'id': (None, <function _transform_snowflake at 0x7ff548fcdb70>), 'inviter_id': ('inviter', <function _transform_inviter_id at 0x7ff548fcdd08>), 'owner_id': ('owner', <function _transform_owner_id at 0x7ff548fcdc80>), 'permission_overwrites': ('overwrites', <function _transform_overwrites at 0x7ff548fcdd90>), 'permissions': (None, <function _transform_permissions at 0x7ff548fcda60>), 'rate_limit_per_user': ('slowmode_delay', None), 'splash_hash': ('splash', None), 'system_channel_id': ('system_channel', <function _transform_channel at 0x7ff548fcdbf8>), 'verification_level': (None, <function _transform_verification_level at 0x7ff54900d1e0>), 'widget_channel_id': ('widget_channel', <function _transform_channel at 0x7ff548fcdbf8>)}
class discord.audit_logs.AuditLogEntry(*, users, data, guild)

Bases: object

Represents an Audit Log entry.

You retrieve these via Guild.audit_logs().

action

AuditLogAction – The action that was done.

user

abc.User – The user who initiated this action. Usually a Member, unless gone then it’s a User.

id

int – The entry ID.

target

Any – The target that got changed. The exact type of this depends on the action being done.

reason

Optional[str] – The reason this action was done.

extra

Any – 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.

created_at

Returns the entry’s creation time in UTC.

target
category

Optional[AuditLogActionCategory] – The category of the action, if applicable.

changes

AuditLogChanges – The list of changes this entry has.

before

AuditLogDiff – The target’s prior state.

after

AuditLogDiff – The target’s subsequent state.

discord.backoff module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.backoff.ExponentialBackoff(base=1, *, integral=False)

Bases: object

An implementation of the exponential backoff algorithm

Provides a convenient interface to implement an exponential backoff for reconnecting or retrying transmissions in a distributed network.

Once instantiated, the delay method will return the next interval to wait for when retrying a connection or transmission. The maximum delay increases exponentially with each retry up to a maximum of 2^10 * base, and is reset if no more attempts are needed in a period of 2^11 * base seconds.

Parameters
  • base (int) – The base delay in seconds. The first retry-delay will be up to this many seconds.

  • integral (bool) – Set to True if whole periods of base is desirable, otherwise any number in between may be returned.

delay()

Compute the next delay

Returns the next delay to wait according to the exponential backoff algorithm. This is a value between 0 and base * 2^exp where exponent starts off at 1 and is incremented at every invocation of this method up to a maximum of 10.

If a period of more than base * 2^11 has passed since the last retry, the exponent is reset to 1.

discord.calls module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.calls.CallMessage(message, **kwargs)

Bases: object

Represents a group call message from Discord.

This is only received in cases where the message type is equivalent to MessageType.call.

ended_timestamp

Optional[datetime.datetime] – A naive UTC datetime object that represents the time that the call has ended.

participants

List[User] – The list of users that are participating in this call.

message

Message – The message associated with this call message.

call_ended

bool – Indicates if the call has ended.

channel

GroupChannel– The private channel associated with this message.

duration

Queries the duration of the call.

If the call has not ended then the current duration will be returned.

Returns

The timedelta object representing the duration.

Return type

datetime.timedelta

class discord.calls.GroupCall(**kwargs)

Bases: object

Represents the actual group call from Discord.

This is accompanied with a CallMessage denoting the information.

call

CallMessage – The call message associated with this group call.

unavailable

bool – Denotes if this group call is unavailable.

ringing

List[User] – A list of users that are currently being rung to join the call.

region

VoiceRegion – The guild region the group call is being hosted on.

connected

A property that returns the list of User that are currently in this call.

channel

GroupChannel– Returns the channel the group call is in.

voice_state_for(user)

Retrieves the VoiceState for a specified User.

If the User has no voice state then this function returns None.

Parameters

user (User) – The user to retrieve the voice state for.

Returns

The voice state associated with this user.

Return type

Optional[VoiceState]

discord.channel module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.channel.TextChannel(*, state, guild, data)

Bases: discord.abc.Messageable, discord.abc.GuildChannel, discord.mixins.Hashable

Represents a Discord guild text channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns the channel’s name.

name

str – The channel name.

guild

Guild – The guild the channel belongs to.

id

int – The channel ID.

category_id

int – The category channel ID this channel belongs to.

topic

Optional[str] – The channel’s topic. None if it doesn’t exist.

position

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

last_message_id

Optional[int] – The last message ID of the message sent to this channel. It may not point to an existing or valid message.

slowmode_delay

int – 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.

id
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

members

Returns a list of Member that can see this channel.

is_nsfw()

Checks if the channel is NSFW.

is_news()

Checks if the channel is a news channel.

last_message

Fetches the last message from this channel in cache.

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

Reliable Fetching

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

Returns

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

Return type

Optional[Message]

category_id
coroutine clone(*, name=None, reason=None)

This function is a coroutine.

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

New in version 1.1.0.

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.

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

This function is a coroutine.

Creates a webhook for this channel.

Requires manage_webhooks permissions.

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

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

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

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

Raises
  • HTTPException – Creating the webhook failed.

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

Returns

The created webhook.

Return type

Webhook

coroutine delete_messages(messages)

This function is a coroutine.

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

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

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

You must have the manage_messages permission to use this.

Usable only by bot accounts.

Parameters

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

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

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

  • HTTPException – Deleting the messages failed.

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

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

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

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

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

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

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

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

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

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

Raises
  • InvalidArgument – If position is less than 0 or greater than the number of channels.

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

  • HTTPException – Editing the channel failed.

guild
last_message_id
name
nsfw
position
coroutine purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True)

This function is a coroutine.

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

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

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

Examples

Deleting bot’s messages

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

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

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

  • before – Same as before in history().

  • after – Same as after in history().

  • around – Same as around in history().

  • oldest_first – Same as oldest_first in history().

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

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

  • HTTPException – Purging the messages failed.

Returns

The list of messages that were deleted.

Return type

List[Message]

slowmode_delay
topic
coroutine webhooks()

This function is a coroutine.

Gets the list of webhooks from this channel.

Requires manage_webhooks permissions.

Raises

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

Returns

The webhooks for this channel.

Return type

List[Webhook]

class discord.channel.VoiceChannel(*, state, guild, data)

Bases: discord.abc.Connectable, discord.abc.GuildChannel, discord.mixins.Hashable

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

str – The channel name.

guild

Guild – The guild the channel belongs to.

id

int – The channel ID.

category_id

int – The category channel ID this channel belongs to.

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.

id
members

Returns a list of Member that are currently inside this voice channel.

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

bitrate
category_id
coroutine clone(*, name=None, reason=None)

This function is a coroutine.

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

New in version 1.1.0.

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.

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

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

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

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

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

  • HTTPException – Editing the channel failed.

guild
name
position
user_limit
class discord.channel.CategoryChannel(*, state, guild, data)

Bases: discord.abc.GuildChannel, discord.mixins.Hashable

Represents a Discord channel category.

These are useful to group channels to logical compartments.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the category’s hash.

str(x)

Returns the category’s name.

name

str – The category name.

guild

Guild – The guild the category belongs to.

id

int – The category channel ID.

position

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

id
is_nsfw()

Checks if the category is NSFW.

position
channels

List[abc.GuildChannel] – Returns the channels that are under this category.

These are sorted by the official Discord UI, which places voice channels below the text channels.

text_channels

List[TextChannel] – Returns the text channels that are under this category.

voice_channels

List[VoiceChannel] – Returns the voice channels that are under this category.

category_id
coroutine clone(*, name=None, reason=None)

This function is a coroutine.

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

New in version 1.1.0.

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.

coroutine create_text_channel(name, *, overwrites=None, reason=None, **options)

This function is a coroutine.

A shortcut method to Guild.create_text_channel() to create a TextChannel in the category.

coroutine create_voice_channel(name, *, overwrites=None, reason=None, **options)

This function is a coroutine.

A shortcut method to Guild.create_voice_channel() to create a VoiceChannel in the category.

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

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

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

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

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

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

Raises
  • InvalidArgument – If position is less than 0 or greater than the number of categories.

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

  • HTTPException – Editing the category failed.

guild
name
nsfw
class discord.channel.StoreChannel(*, state, guild, data)

Bases: discord.abc.GuildChannel, discord.mixins.Hashable

Represents a Discord guild store 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

str – The channel name.

guild

Guild – The guild the channel belongs to.

id

int – The channel ID.

category_id

int – The category channel ID this channel belongs to.

position

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

id
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

is_nsfw()

Checks if the channel is NSFW.

category_id
coroutine clone(*, name=None, reason=None)

This function is a coroutine.

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

New in version 1.1.0.

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.

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

This function is a coroutine.

Edits the channel.

You must have the manage_channels permission to use this.

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

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

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

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

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

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

Raises
  • InvalidArgument – If position is less than 0 or greater than the number of channels.

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

  • HTTPException – Editing the channel failed.

guild
name
nsfw
position
class discord.channel.DMChannel(*, me, state, data)

Bases: discord.abc.Messageable, discord.mixins.Hashable

Represents a Discord direct message channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns a string representation of the channel

recipient

User – The user you are participating with in the direct message channel.

me

ClientUser – The user presenting yourself.

id

int – The direct message channel ID.

recipient
me
id
created_at

Returns the direct message channel’s creation time in UTC.

permissions_for(user=None)

Handles permission resolution for a User.

This function is there for compatibility with other channel types.

Actual direct messages do not really have the concept of permissions.

This returns all the Text related permissions set to true except:

  • send_tts_messages: You cannot send TTS messages in a DM.

  • manage_messages: You cannot delete others messages in a DM.

Parameters

user (User) – The user to check permissions for. This parameter is ignored but kept for compatibility.

Returns

The resolved permissions.

Return type

Permissions

class discord.channel.GroupChannel(*, me, state, data)

Bases: discord.abc.Messageable, discord.mixins.Hashable

Represents a Discord group channel.

x == y

Checks if two channels are equal.

x != y

Checks if two channels are not equal.

hash(x)

Returns the channel’s hash.

str(x)

Returns a string representation of the channel

recipients

list of User – The users you are participating with in the group channel.

me

ClientUser – The user presenting yourself.

id

int – The group channel ID.

owner

User – The user that owns the group channel.

icon

Optional[str] – The group channel’s icon hash if provided.

name

Optional[str] – The group channel’s name if provided.

id
me
icon_url

Asset – Returns the channel’s icon asset if available.

coroutine add_recipients(*recipients)

This function is a coroutine.

Adds recipients to this group.

A group can only have a maximum of 10 members. Attempting to add more ends up in an exception. To add a recipient to the group, you must have a relationship with the user of type RelationshipType.friend.

Parameters

*recipients (User) – An argument list of users to add to this group.

Raises

HTTPException – Adding a recipient to this group failed.

created_at

Returns the channel’s creation time in UTC.

coroutine edit(**fields)

This function is a coroutine.

Edits the group.

Parameters
  • name (Optional[str]) – The new name to change the group to. Could be None to remove the name.

  • icon (Optional[bytes]) – A bytes-like object representing the new icon. Could be None to remove the icon.

Raises

HTTPException – Editing the group failed.

icon
coroutine leave()

This function is a coroutine.

Leave the group.

If you are the only one in the group, this deletes it as well.

Raises

HTTPException – Leaving the group failed.

name
owner
recipients
coroutine remove_recipients(*recipients)

This function is a coroutine.

Removes recipients from this group.

Parameters

*recipients (User) – An argument list of users to remove from this group.

Raises

HTTPException – Removing a recipient from this group failed.

permissions_for(user)

Handles permission resolution for a User.

This function is there for compatibility with other channel types.

Actual direct messages do not really have the concept of permissions.

This returns all the Text related permissions set to true except:

  • send_tts_messages: You cannot send TTS messages in a DM.

  • manage_messages: You cannot delete others messages in a DM.

This also checks the kick_members permission if the user is the owner.

Parameters

user (User) – The user to check permissions for.

Returns

The resolved permissions for the user.

Return type

Permissions

discord.client module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.client.Client(*, loop=None, **options)

Bases: object

Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

A number of options can be passed to the Client.

Parameters
  • max_messages (Optional[int]) – The maximum number of messages to store in the internal message cache. This defaults to 5000. Passing in None or a value less than 100 will use the default instead of the passed in value.

  • loop (Optional[asyncio.AbstractEventLoop]) – The asyncio.AbstractEventLoop to use for asynchronous operations. Defaults to None, in which case the default event loop is used via asyncio.get_event_loop().

  • connector (aiohttp.BaseConnector) – The connector to use for connection pooling.

  • proxy (Optional[str]) – Proxy URL.

  • proxy_auth (Optional[aiohttp.BasicAuth]) – An object that represents proxy HTTP Basic Authorization.

  • shard_id (Optional[int]) – Integer starting at 0 and less than shard_count.

  • shard_count (Optional[int]) – The total number of shards.

  • fetch_offline_members (bool) – Indicates if on_ready() should be delayed to fetch all offline members from the guilds the bot belongs to. If this is False, then no offline members are received and request_offline_members() must be used to fetch the offline members of the guild.

  • status (Optional[Status]) – A status to start your presence with upon logging on to Discord.

  • activity (Optional[Union[Activity, Game, Streaming]]) – An activity to start your presence with upon logging on to Discord.

  • heartbeat_timeout (float) – The maximum numbers of seconds before timing out and restarting the WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful if processing the initial packets take too long to the point of disconnecting you. The default timeout is 60 seconds.

ws

The websocket gateway the client is currently connected to. Could be None.

loop

asyncio.AbstractEventLoop – The event loop that the client uses for HTTP requests and websocket operations.

latency

float – Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.

guilds

List[Guild] – The guilds that the connected client is a member of.

emojis

List[Emoji] – The emojis that the connected client has.

cached_messages

Sequence[Message] – Read-only list of messages the connected client has cached.

New in version 1.1.0.

private_channels

List[abc.PrivateChannel] – The private channels that the connected client is participating on.

Note

This returns only up to 128 most recent private channels due to an internal working on how Discord deals with private channels.

voice_clients

List[VoiceClient] – Represents a list of voice connections.

is_ready()

bool: Specifies if the client’s internal cache is ready for use.

dispatch(event, *args, **kwargs)
clear()

Clears the internal state of the bot.

After this, the bot can be considered “re-opened”, i.e. is_closed() and is_ready() both return False along with the bot’s internal cache cleared.

run(*args, **kwargs)

A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use start() coroutine or connect() + login().

Roughly Equivalent to:

try:
    loop.run_until_complete(start(*args, **kwargs))
except KeyboardInterrupt:
    loop.run_until_complete(logout())
    # cancel all tasks lingering
finally:
    loop.close()

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.

is_closed()

bool: Indicates if the websocket connection is closed.

activity

Optional[Union[Activity, Game, Streaming]] – The activity being used upon logging in.

users

Returns a list of all the User the bot can see.

get_channel(id)

Returns a abc.GuildChannel or abc.PrivateChannel with the following ID.

If not found, returns None.

get_guild(id)

Returns a Guild with the given ID. If not found, returns None.

get_user(id)

Returns a User with the given ID. If not found, returns None.

get_emoji(id)

Returns a Emoji with the given ID. If not found, returns None.

get_all_channels()

A generator that retrieves every abc.GuildChannel the client can ‘access’.

This is equivalent to:

for guild in client.guilds:
    for channel in guild.channels:
        yield channel

Note

Just because you receive a abc.GuildChannel does not mean that you can communicate in said channel. abc.GuildChannel.permissions_for() should be used for that.

get_all_members()

Returns a generator with every Member the client can see.

This is equivalent to:

for guild in client.guilds:
    for member in guild.members:
        yield member
wait_for(event, *, check=None, timeout=None)

This function is a coroutine.

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The timeout parameter is passed onto asyncio.wait_for(). By default, it does not timeout. Note that this does propagate the asyncio.TimeoutError for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a tuple containing those arguments is returned instead. Please check the documentation for a list of events and their parameters.

This function returns the first event that meets the requirements.

Examples

Waiting for a user reply:

@client.event
async def on_message(message):
    if message.content.startswith('$greet'):
        channel = message.channel
        await channel.send('Say hello!')

        def check(m):
            return m.content == 'hello' and m.channel == channel

        msg = await client.wait_for('message', check=check)
        await channel.send('Hello {.author}!'.format(msg))

Waiting for a thumbs up reaction from the message author:

@client.event
async def on_message(message):
    if message.content.startswith('$thumb'):
        channel = message.channel
        await channel.send('Send me that 👍 reaction, mate')

        def check(reaction, user):
            return user == message.author and str(reaction.emoji) == '👍'

        try:
            reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
        except asyncio.TimeoutError:
            await channel.send('👎')
        else:
            await channel.send('👍')
Parameters
  • event (str) – The event name, similar to the event reference, but without the on_ prefix, to wait for.

  • check (Optional[predicate]) – A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for.

  • timeout (Optional[float]) – The number of seconds to wait before timing out and raising asyncio.TimeoutError.

Raises

asyncio.TimeoutError – If a timeout is provided and it was reached.

Returns

Returns no arguments, a single argument, or a tuple of multiple arguments that mirrors the parameters passed in the event reference.

Return type

Any

event(coro)

A decorator that registers an event to listen to.

You can find more info about the events on the documentation below.

The events must be a coroutine, if not, TypeError is raised.

Example

@client.event
async def on_ready():
    print('Ready!')
Raises

TypeError – The coroutine passed is not actually a coroutine.

fetch_guilds(*, limit=100, before=None, after=None)

This function is a coroutine.

Retrieves an AsyncIterator that enables receiving your guilds.

Note

Using this, you will only receive Guild.owner, Guild.icon, Guild.id, and Guild.name per Guild.

Note

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

All parameters are optional.

Parameters
  • limit (Optional[int]) – The number of guilds to retrieve. If None, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to 100.

  • before (abc.Snowflake or datetime.datetime) – Retrieves guilds before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.

  • after (abc.Snowflake or datetime.datetime) – Retrieve guilds after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.

Raises

HTTPException – Getting the guilds failed.

Yields

Guild – The guild with the guild data parsed.

Examples

Usage

async for guild in client.fetch_guilds(limit=150):
    print(guild.name)

Flattening into a list

guilds = await client.fetch_guilds(limit=150).flatten()
# guilds is now a list of Guild...
coroutine application_info()

This function is a coroutine.

Retrieve’s the bot’s application information.

Raises

HTTPException – Retrieving the information failed somehow.

Returns

A namedtuple representing the application info.

Return type

AppInfo

coroutine change_presence(*, activity=None, status=None, afk=False)

This function is a coroutine.

Changes the client’s presence.

The activity parameter is a Activity object (not a string) that represents the activity being done currently. This could also be the slimmed down versions, Game and Streaming.

Example

game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
Parameters
  • activity (Optional[Union[Game, Streaming, Activity]]) – The activity being done. None if no currently active activity is done.

  • status (Optional[Status]) – Indicates what status to change to. If None, then Status.online is used.

  • afk (bool) – Indicates if you are going AFK. This allows the discord client to know how to handle push notifications better for you in case you are actually idle and not lying.

Raises

InvalidArgument – If the activity parameter is not the proper type.

coroutine close()

This function is a coroutine.

Closes the connection to discord.

coroutine connect(*, reconnect=True)

This function is a coroutine.

Creates a websocket connection and lets the websocket listen to messages from discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated.

Parameters

reconnect (bool) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).

Raises
  • GatewayNotFound – If the gateway to connect to discord is not found. Usually if this is thrown then there is a discord API outage.

  • ConnectionClosed – The websocket connection has been terminated.

coroutine create_guild(name, region=None, icon=None)

This function is a coroutine.

Creates a Guild.

Bot accounts in more than 10 guilds are not allowed to create guilds.

Parameters
Raises
  • HTTPException – Guild creation failed.

  • InvalidArgument – Invalid icon image format given. Must be PNG or JPG.

Returns

The guild created. This is not the same guild that is added to cache.

Return type

Guild

coroutine delete_invite(invite)

This function is a coroutine.

Revokes an Invite, URL, or ID to an invite.

You must have the manage_channels permission in the associated guild to do this.

Parameters

invite (Union[Invite, str]) – The invite to revoke.

Raises
  • Forbidden – You do not have permissions to revoke invites.

  • NotFound – The invite is invalid or expired.

  • HTTPException – Revoking the invite failed.

coroutine fetch_guild(guild_id)

This function is a coroutine.

Retrieves a Guild from an ID.

Note

Using this, you will not receive Guild.channels, Guild.members, Member.activity and Member.voice per Member.

Note

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

Parameters

guild_id (int) – The guild’s ID to fetch from.

Raises
  • Forbidden – You do not have access to the guild.

  • HTTPException – Getting the guild failed.

Returns

The guild from the ID.

Return type

Guild

coroutine fetch_invite(url, *, with_counts=True)

This function is a coroutine.

Gets an Invite from a discord.gg URL or ID.

Note

If the invite is for a guild you have not joined, the guild and channel attributes of the returned Invite will be PartialInviteGuild and PartialInviteChannel respectively.

Parameters
Raises
  • NotFound – The invite has expired or is invalid.

  • HTTPException – Getting the invite failed.

Returns

The invite from the URL/ID.

Return type

Invite

coroutine fetch_user(user_id)

This function is a coroutine.

Retrieves a User based on their ID. This can only be used by bot accounts. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

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

Parameters

user_id (int) – The user’s ID to fetch from.

Raises
  • NotFound – A user with this ID does not exist.

  • HTTPException – Fetching the user failed.

Returns

The user you requested.

Return type

User

coroutine fetch_user_profile(user_id)

This function is a coroutine.

Gets an arbitrary user’s profile. This can only be used by non-bot accounts.

Parameters

user_id (int) – The ID of the user to fetch their profile for.

Raises
  • Forbidden – Not allowed to fetch profiles.

  • HTTPException – Fetching the profile failed.

Returns

The profile of the user.

Return type

Profile

coroutine fetch_webhook(webhook_id)

This function is a coroutine.

Retrieves a Webhook with the specified ID.

Raises
  • HTTPException – Retrieving the webhook failed.

  • NotFound – Invalid webhook ID.

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

Returns

The webhook you requested.

Return type

Webhook

coroutine fetch_widget(guild_id)

This function is a coroutine.

Gets a Widget from a guild ID.

Note

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

Parameters

guild_id (int) – The ID of the guild.

Raises
  • Forbidden – The widget for this guild is disabled.

  • HTTPException – Retrieving the widget failed.

Returns

The guild’s widget.

Return type

Widget

coroutine login(token, *, bot=True)

This function is a coroutine.

Logs in the client with the specified credentials.

This function can be used in two different ways.

Warning

Logging on with a user token is against the Discord Terms of Service and doing so might potentially get your account banned. Use this at your own risk.

Parameters
  • token (str) – The authentication token. Do not prefix this token with anything as the library will do it for you.

  • bot (bool) – Keyword argument that specifies if the account logging on is a bot token or not.

Raises
  • LoginFailure – The wrong credentials are passed.

  • HTTPException – An unknown HTTP related error occurred, usually when it isn’t 200 or the known incorrect credentials passing status code.

coroutine logout()

This function is a coroutine.

Logs out of Discord and closes all connections.

Note

This is just an alias to close(). If you want to do extraneous cleanup when subclassing, it is suggested to override close() instead.

coroutine on_error(event_method, *args, **kwargs)

This function is a coroutine.

The default error handler provided by the client.

By default this prints to sys.stderr however it could be overridden to have a different implementation. Check discord.on_error() for more details.

coroutine request_offline_members(*guilds)

This function is a coroutine.

Requests previously offline members from the guild to be filled up into the Guild.members cache. This function is usually not called. It should only be used if you have the fetch_offline_members parameter set to False.

When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if Guild.large is True.

Parameters

*guilds (Guild) – An argument list of guilds to request offline members for.

Raises

InvalidArgument – If any guild is unavailable or not large in the collection.

coroutine start(*args, **kwargs)

This function is a coroutine.

A shorthand coroutine for login() + connect().

coroutine wait_until_ready()

This function is a coroutine.

Waits until the client’s internal cache is all ready.

user

Optional[ClientUser] – Represents the connected client. None if not logged in.

discord.colour module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.colour.Colour(value)

Bases: object

Represents a Discord role colour. This class is similar to an (red, green, blue) tuple.

There is an alias for this called Color.

x == y

Checks if two colours are equal.

x != y

Checks if two colours are not equal.

hash(x)

Return the colour’s hash.

str(x)

Returns the hex format for the colour.

value

int – The raw integer colour value.

value
r

Returns the red component of the colour.

g

Returns the green component of the colour.

b

Returns the blue component of the colour.

to_rgb()

Returns an (r, g, b) tuple representing the colour.

classmethod from_rgb(r, g, b)

Constructs a Colour from an RGB tuple.

classmethod from_hsv(h, s, v)

Constructs a Colour from an HSV tuple.

classmethod default()

A factory method that returns a Colour with a value of 0.

classmethod teal()

A factory method that returns a Colour with a value of 0x1abc9c.

classmethod dark_teal()

A factory method that returns a Colour with a value of 0x11806a.

classmethod green()

A factory method that returns a Colour with a value of 0x2ecc71.

classmethod dark_green()

A factory method that returns a Colour with a value of 0x1f8b4c.

classmethod blue()

A factory method that returns a Colour with a value of 0x3498db.

classmethod dark_blue()

A factory method that returns a Colour with a value of 0x206694.

classmethod purple()

A factory method that returns a Colour with a value of 0x9b59b6.

classmethod dark_purple()

A factory method that returns a Colour with a value of 0x71368a.

classmethod magenta()

A factory method that returns a Colour with a value of 0xe91e63.

classmethod dark_magenta()

A factory method that returns a Colour with a value of 0xad1457.

classmethod gold()

A factory method that returns a Colour with a value of 0xf1c40f.

classmethod dark_gold()

A factory method that returns a Colour with a value of 0xc27c0e.

classmethod orange()

A factory method that returns a Colour with a value of 0xe67e22.

classmethod dark_orange()

A factory method that returns a Colour with a value of 0xa84300.

classmethod red()

A factory method that returns a Colour with a value of 0xe74c3c.

classmethod dark_red()

A factory method that returns a Colour with a value of 0x992d22.

classmethod lighter_grey()

A factory method that returns a Colour with a value of 0x95a5a6.

classmethod dark_grey()

A factory method that returns a Colour with a value of 0x607d8b.

classmethod light_grey()

A factory method that returns a Colour with a value of 0x979c9f.

classmethod darker_grey()

A factory method that returns a Colour with a value of 0x546e7a.

classmethod blurple()

A factory method that returns a Colour with a value of 0x7289da.

classmethod greyple()

A factory method that returns a Colour with a value of 0x99aab5.

discord.colour.Color

alias of discord.colour.Colour

discord.context_managers module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.context_managers.Typing(messageable)

Bases: object

coroutine do_typing()

discord.embeds module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.embeds.EmbedProxy(layer)

Bases: object

class discord.embeds.Embed(**kwargs)

Bases: object

Represents a Discord embed.

len(x)

Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

Certain properties return an EmbedProxy. Which is a type that acts similar to a regular dict except access the attributes via dotted access, e.g. embed.author.icon_url. If the attribute is invalid or empty, then a special sentinel value is returned, Embed.Empty.

For ease of use, all parameters that expect a str are implicitly casted to str for you.

title

str – The title of the embed. This can be set during initialisation.

type

str – The type of embed. Usually “rich”. This can be set during initialisation.

description

str – The description of the embed. This can be set during initialisation.

url

str – The URL of the embed. This can be set during initialisation.

timestamp

datetime.datetime – The timestamp of the embed content. This could be a naive or aware datetime. This can be set during initialisation.

colour

Colour or int – The colour code of the embed. Aliased to color as well. This can be set during initialisation.

Empty

A special sentinel value used by EmbedProxy and this class to denote that the value or attribute is empty.

Empty = Embed.Empty
title
type
url
description
classmethod from_dict(data)

Converts a dict to a Embed provided it is in the format that Discord expects it to be in.

You can find out about this format in the official Discord documentation.

Parameters

data (dict) – The dictionary to convert into an embed.

copy()

Returns a shallow copy of the embed.

colour
color
timestamp
footer

Returns an EmbedProxy denoting the footer contents.

See set_footer() for possible values you can access.

If the attribute has no value then Empty is returned.

Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Parameters
  • text (str) – The footer text.

  • icon_url (str) – The URL of the footer icon. Only HTTP(S) is supported.

image

Returns an EmbedProxy denoting the image contents.

Possible attributes you can access are:

  • url

  • proxy_url

  • width

  • height

If the attribute has no value then Empty is returned.

set_image(*, url)

Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Parameters

url (str) – The source URL for the image. Only HTTP(S) is supported.

thumbnail

Returns an EmbedProxy denoting the thumbnail contents.

Possible attributes you can access are:

  • url

  • proxy_url

  • width

  • height

If the attribute has no value then Empty is returned.

set_thumbnail(*, url)

Sets the thumbnail for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Parameters

url (str) – The source URL for the thumbnail. Only HTTP(S) is supported.

video

Returns an EmbedProxy denoting the video contents.

Possible attributes include:

  • url for the video URL.

  • height for the video height.

  • width for the video width.

If the attribute has no value then Empty is returned.

provider

Returns an EmbedProxy denoting the provider contents.

The only attributes that might be accessed are name and url.

If the attribute has no value then Empty is returned.

author

Returns an EmbedProxy denoting the author contents.

See set_author() for possible values you can access.

If the attribute has no value then Empty is returned.

set_author(*, name, url=Embed.Empty, icon_url=Embed.Empty)

Sets the author for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Parameters
  • name (str) – The name of the author.

  • url (str) – The URL for the author.

  • icon_url (str) – The URL of the author icon. Only HTTP(S) is supported.

fields

Returns a list of EmbedProxy denoting the field contents.

See add_field() for possible values you can access.

If the attribute has no value then Empty is returned.

add_field(*, name, value, inline=True)

Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining.

Parameters
  • name (str) – The name of the field.

  • value (str) – The value of the field.

  • inline (bool) – Whether the field should be displayed inline.

clear_fields()

Removes all fields from this embed.

remove_field(index)

Removes a field at a specified index.

If the index is invalid or out of bounds then the error is silently swallowed.

Note

When deleting a field by index, the index of the other fields shift to fill the gap just like a regular list.

Parameters

index (int) – The index of the field to remove.

set_field_at(index, *, name, value, inline=True)

Modifies a field to the embed object.

The index must point to a valid pre-existing field.

This function returns the class instance to allow for fluent-style chaining.

Parameters
  • index (int) – The index of the field to modify.

  • name (str) – The name of the field.

  • value (str) – The value of the field.

  • inline (bool) – Whether the field should be displayed inline.

Raises

IndexError – An invalid index was provided.

to_dict()

Converts this embed object into a dict.

discord.emoji module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.emoji.PartialEmoji(*, animated, name, id=None)

Bases: object

Represents a “partial” emoji.

This model will be given in two scenarios:

  • “Raw” data events such as on_raw_reaction_add()

  • Custom emoji that the bot cannot see from e.g. Message.reactions

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

str – The custom emoji name, if applicable, or the unicode codepoint of the non-custom emoji.

animated

bool – Whether the emoji is animated or not.

id

Optional[int] – The ID of the custom emoji, if applicable.

animated
name
id
classmethod with_state(state, *, animated, name, id=None)
is_custom_emoji()

Checks if this is a custom non-Unicode emoji.

is_unicode_emoji()

Checks if this is a Unicode emoji.

url

Asset – Returns an asset of the emoji, if it is custom.

class discord.emoji.Emoji(*, guild, state, data)

Bases: object

Represents a custom emoji.

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

x == y

Checks if two emoji are the same.

x != y

Checks if two emoji are not the same.

hash(x)

Return the emoji’s hash.

iter(x)

Returns an iterator of (field, value) pairs. This allows this class to be used as an iterable in list/dict/etc constructions.

str(x)

Returns the emoji rendered for discord.

name

str – The name of the emoji.

id

int – The emoji’s ID.

require_colons

bool – If colons are required to use this emoji in the client (:PJSalt: vs PJSalt).

animated

bool – Whether an emoji is animated or not.

managed

bool – If this emoji is managed by a Twitch integration.

guild_id

int – The guild ID the emoji belongs to.

user

Optional[User] – The user that created the emoji. This can only be retrieved using Guild.fetch_emoji().

guild_id
created_at

Returns the emoji’s creation time in UTC.

url

Returns a URL version of the emoji.

guild

Guild – The guild this emoji belongs to.

animated
coroutine delete(*, reason=None)

This function is a coroutine.

Deletes the custom emoji.

You must have manage_emojis permission to do this.

Parameters

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

Raises
  • Forbidden – You are not allowed to delete emojis.

  • HTTPException – An error occurred deleting the emoji.

coroutine edit(*, name, roles=None, reason=None)

This function is a coroutine.

Edits the custom emoji.

You must have manage_emojis permission to do this.

Parameters
  • name (str) – The new emoji name.

  • roles (Optional[list[Role]]) – A list of Roles that can use this emoji. Leave empty to make it available to everyone.

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

Raises
  • Forbidden – You are not allowed to edit emojis.

  • HTTPException – An error occurred editing the emoji.

id
managed
name
require_colons
roles

List[Role] – A list of roles that is allowed to use this emoji.

If roles is empty, the emoji is unrestricted.

user

discord.enums module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.enums.ChannelType

Bases: enum.Enum

An enumeration.

text = 0
private = 1
voice = 2
group = 3
category = 4
news = 5
store = 6
class discord.enums.MessageType

Bases: enum.Enum

An enumeration.

default = 0
recipient_add = 1
recipient_remove = 2
call = 3
channel_name_change = 4
channel_icon_change = 5
pins_add = 6
new_member = 7
class discord.enums.VoiceRegion

Bases: enum.Enum

An enumeration.

us_west = 'us-west'
us_east = 'us-east'
us_south = 'us-south'
us_central = 'us-central'
eu_west = 'eu-west'
eu_central = 'eu-central'
singapore = 'singapore'
london = 'london'
sydney = 'sydney'
amsterdam = 'amsterdam'
frankfurt = 'frankfurt'
brazil = 'brazil'
hongkong = 'hongkong'
russia = 'russia'
japan = 'japan'
southafrica = 'southafrica'
vip_us_east = 'vip-us-east'
vip_us_west = 'vip-us-west'
vip_amsterdam = 'vip-amsterdam'
class discord.enums.SpeakingState

Bases: enum.Enum

An enumeration.

none = 0
voice = 1
soundshare = 2
priority = 4
class discord.enums.VerificationLevel

Bases: enum.Enum

An enumeration.

none = 0
low = 1
medium = 2
high = 3
extreme = 4
class discord.enums.ContentFilter

Bases: enum.Enum

An enumeration.

disabled = 0
no_role = 1
all_members = 2
class discord.enums.UserContentFilter

Bases: enum.Enum

An enumeration.

disabled = 0
friends = 1
all_messages = 2
class discord.enums.FriendFlags

Bases: enum.Enum

An enumeration.

noone = 0
mutual_guilds = 1
mutual_friends = 2
guild_and_friends = 3
everyone = 4
class discord.enums.Theme

Bases: enum.Enum

An enumeration.

light = 'light'
dark = 'dark'
class discord.enums.Status

Bases: enum.Enum

An enumeration.

online = 'online'
offline = 'offline'
idle = 'idle'
dnd = 'dnd'
invisible = 'invisible'
class discord.enums.DefaultAvatar

Bases: enum.Enum

An enumeration.

blurple = 0
grey = 1
green = 2
orange = 3
red = 4
class discord.enums.RelationshipType

Bases: enum.Enum

An enumeration.

friend = 1
blocked = 2
incoming_request = 3
outgoing_request = 4
class discord.enums.NotificationLevel

Bases: enum.Enum

An enumeration.

all_messages = 0
only_mentions = 1
class discord.enums.AuditLogActionCategory

Bases: enum.Enum

An enumeration.

create = 1
delete = 2
update = 3
class discord.enums.AuditLogAction

Bases: enum.Enum

An enumeration.

guild_update = 1
channel_create = 10
channel_update = 11
channel_delete = 12
overwrite_create = 13
overwrite_update = 14
overwrite_delete = 15
kick = 20
member_prune = 21
ban = 22
unban = 23
member_update = 24
member_role_update = 25
role_create = 30
role_update = 31
role_delete = 32
invite_create = 40
invite_update = 41
invite_delete = 42
webhook_create = 50
webhook_update = 51
webhook_delete = 52
emoji_create = 60
emoji_update = 61
emoji_delete = 62
message_delete = 72
class discord.enums.UserFlags

Bases: enum.Enum

An enumeration.

staff = 1
partner = 2
hypesquad = 4
bug_hunter = 8
hypesquad_bravery = 64
hypesquad_brilliance = 128
hypesquad_balance = 256
early_supporter = 512
class discord.enums.ActivityType

Bases: enum.Enum

An enumeration.

unknown = -1
playing = 0
streaming = 1
listening = 2
watching = 3
class discord.enums.HypeSquadHouse

Bases: enum.Enum

An enumeration.

bravery = 1
brilliance = 2
balance = 3
class discord.enums.PremiumType

Bases: enum.Enum

An enumeration.

nitro_classic = 1
nitro = 2

discord.errors module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

exception discord.errors.DiscordException

Bases: Exception

Base exception class for discord.py

Ideally speaking, this could be caught to handle any exceptions thrown from this library.

exception discord.errors.ClientException

Bases: discord.errors.DiscordException

Exception that’s thrown when an operation in the Client fails.

These are usually for exceptions that happened due to user input.

exception discord.errors.NoMoreItems

Bases: discord.errors.DiscordException

Exception that is thrown when an async iteration operation has no more items.

exception discord.errors.GatewayNotFound

Bases: discord.errors.DiscordException

An exception that is usually thrown when the gateway hub for the Client websocket is not found.

discord.errors.flatten_error_dict(d, key='')
exception discord.errors.HTTPException(response, message)

Bases: discord.errors.DiscordException

Exception that’s thrown when an HTTP request operation fails.

response

aiohttp.ClientResponse – The response of the failed HTTP request. This is an instance of aiohttp.ClientResponse. In some cases this could also be a requests.Response.

text

str – The text of the error. Could be an empty string.

status

int – The status code of the HTTP request.

code

int – The Discord specific error code for the failure.

exception discord.errors.Forbidden(response, message)

Bases: discord.errors.HTTPException

Exception that’s thrown for when status code 403 occurs.

Subclass of HTTPException

exception discord.errors.NotFound(response, message)

Bases: discord.errors.HTTPException

Exception that’s thrown for when status code 404 occurs.

Subclass of HTTPException

exception discord.errors.InvalidArgument

Bases: discord.errors.ClientException

Exception that’s thrown when an argument to a function is invalid some way (e.g. wrong value or wrong type).

This could be considered the analogous of ValueError and TypeError except inherited from ClientException and thus DiscordException.

exception discord.errors.LoginFailure

Bases: discord.errors.ClientException

Exception that’s thrown when the Client.login() function fails to log you in from improper credentials or some other misc. failure.

exception discord.errors.ConnectionClosed(original, *, shard_id)

Bases: discord.errors.ClientException

Exception that’s thrown when the gateway connection is closed for reasons that could not be handled internally.

code

int – The close code of the websocket.

reason

str – The reason provided for the closure.

shard_id

Optional[int] – The shard ID that got closed if applicable.

discord.file module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.file.File(fp, filename=None, *, spoiler=False)

Bases: object

A parameter object used for abc.Messageable.send() for sending file objects.

fp

Union[str, BinaryIO] – A file-like object opened in binary mode and read mode or a filename representing a file in the hard drive to open.

Note

If the file-like object passed is opened via open then the modes ‘rb’ should be used.

To pass binary data, consider usage of io.BytesIO.

filename

Optional[str] – The filename to display when uploading to Discord. If this is not given then it defaults to fp.name or if fp is a string then the filename will default to the string given.

spoiler

bool – Whether the attachment is a spoiler.

fp
filename
reset(*, seek=True)
close()

discord.gateway module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

exception discord.gateway.ResumeWebSocket(shard_id)

Bases: Exception

Signals to initialise via RESUME opcode instead of IDENTIFY.

class discord.gateway.KeepAliveHandler(*args, **kwargs)

Bases: threading.Thread

run()

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

get_payload()
stop()
ack()
class discord.gateway.VoiceKeepAliveHandler(*args, **kwargs)

Bases: discord.gateway.KeepAliveHandler

get_payload()
class discord.gateway.DiscordWebSocket(*args, **kwargs)

Bases: websockets.client.WebSocketClientProtocol

Implements a WebSocket for Discord’s gateway v6.

This is created through create_main_websocket(). Library users should never create this manually.

DISPATCH

Receive only. Denotes an event to be sent to Discord, such as READY.

HEARTBEAT

When received tells Discord to keep the connection alive. When sent asks if your connection is currently alive.

IDENTIFY

Send only. Starts a new session.

PRESENCE

Send only. Updates your presence.

VOICE_STATE

Send only. Starts a new connection to a voice guild.

VOICE_PING

Send only. Checks ping time to a voice guild, do not use.

RESUME

Send only. Resumes an existing connection.

RECONNECT

Receive only. Tells the client to reconnect to a new gateway.

REQUEST_MEMBERS

Send only. Asks for the full member list of a guild.

INVALIDATE_SESSION

Receive only. Tells the client to optionally invalidate the session and IDENTIFY again.

HELLO

Receive only. Tells the client the heartbeat interval.

HEARTBEAT_ACK

Receive only. Confirms receiving of a heartbeat. Not having it implies a connection issue.

GUILD_SYNC

Send only. Requests a guild sync.

gateway

The gateway we are currently connected to.

token

The authentication token for discord.

DISPATCH = 0
HEARTBEAT = 1
IDENTIFY = 2
PRESENCE = 3
VOICE_STATE = 4
VOICE_PING = 5
RESUME = 6
RECONNECT = 7
REQUEST_MEMBERS = 8
INVALIDATE_SESSION = 9
HELLO = 10
HEARTBEAT_ACK = 11
GUILD_SYNC = 12
wait_for(event, predicate, result=None)

Waits for a DISPATCH’d event that meets the predicate.

Parameters
  • event (str) – The event name in all upper case to wait for.

  • predicate – A function that takes a data parameter to check for event properties. The data parameter is the ‘d’ key in the JSON message.

  • result – A function that takes the same data parameter and executes to send the result to the future. If None, returns the data.

Returns

A future to wait for.

Return type

asyncio.Future

latency

float – Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

coroutine change_presence(*, activity=None, status=None, afk=False, since=0.0)
coroutine close(code=1000, reason='')

This coroutine performs the closing handshake.

It waits for the other end to complete the handshake and for the TCP connection to terminate.

It doesn’t do anything once the connection is closed. In other words it’s idemptotent.

It’s safe to wrap this coroutine in ensure_future() since errors during connection termination aren’t particularly useful.

code must be an int and reason a str.

coroutine close_connection(*args, **kwargs)

7.1.1. Close the WebSocket Connection

When the opening handshake succeeds, connection_open() starts this coroutine in a task. It waits for the data transfer phase to complete then it closes the TCP connection cleanly.

When the opening handshake fails, fail_connection() does the same. There’s no data transfer phase in that case.

coroutine from_client(client, *, shard_id=None, session=None, sequence=None, resume=False)

Creates a main websocket for Discord from a Client.

This is for internal use only.

coroutine identify()

Sends the IDENTIFY packet.

coroutine poll_event()

Polls for a DISPATCH event and handles the general gateway loop.

Raises

ConnectionClosed – The websocket connection was terminated for unhandled reasons.

coroutine received_message(msg)
coroutine request_sync(guild_ids)
coroutine resume()

Sends the RESUME packet.

coroutine send(data)

This coroutine sends a message.

It sends str as a text frame and bytes as a binary frame. It raises a TypeError for other inputs.

coroutine send_as_json(data)
coroutine voice_state(guild_id, channel_id, self_mute=False, self_deaf=False)
class discord.gateway.DiscordVoiceWebSocket(*args, **kwargs)

Bases: websockets.client.WebSocketClientProtocol

Implements the websocket protocol for handling voice connections.

IDENTIFY

Send only. Starts a new voice session.

SELECT_PROTOCOL

Send only. Tells discord what encryption mode and how to connect for voice.

READY

Receive only. Tells the websocket that the initial connection has completed.

HEARTBEAT

Send only. Keeps your websocket connection alive.

SESSION_DESCRIPTION

Receive only. Gives you the secret key required for voice.

SPEAKING

Send only. Notifies the client if you are currently speaking.

HEARTBEAT_ACK

Receive only. Tells you your heartbeat has been acknowledged.

RESUME

Sent only. Tells the client to resume its session.

HELLO

Receive only. Tells you that your websocket connection was acknowledged.

INVALIDATE_SESSION

Sent only. Tells you that your RESUME request has failed and to re-IDENTIFY.

CLIENT_CONNECT

Indicates a user has connected to voice.

CLIENT_DISCONNECT

Receive only. Indicates a user has disconnected from voice.

IDENTIFY = 0
SELECT_PROTOCOL = 1
READY = 2
HEARTBEAT = 3
SESSION_DESCRIPTION = 4
SPEAKING = 5
HEARTBEAT_ACK = 6
RESUME = 7
HELLO = 8
INVALIDATE_SESSION = 9
CLIENT_CONNECT = 12
CLIENT_DISCONNECT = 13
coroutine client_connect()
coroutine close_connection(*args, **kwargs)

7.1.1. Close the WebSocket Connection

When the opening handshake succeeds, connection_open() starts this coroutine in a task. It waits for the data transfer phase to complete then it closes the TCP connection cleanly.

When the opening handshake fails, fail_connection() does the same. There’s no data transfer phase in that case.

coroutine from_client(client, *, resume=False)

Creates a voice websocket for the VoiceClient.

coroutine identify()
coroutine initial_connection(data)
coroutine load_secret_key(data)
coroutine poll_event()
coroutine received_message(msg)
coroutine resume()
coroutine select_protocol(ip, port, mode)
coroutine send_as_json(data)
coroutine speak(state=<SpeakingState.voice: 1>)

discord.guild module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.guild.BanEntry(reason, user)

Bases: tuple

reason

Alias for field number 0

user

Alias for field number 1

class discord.guild.Guild(*, data, state)

Bases: discord.mixins.Hashable

Represents a Discord guild.

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

x == y

Checks if two guilds are equal.

x != y

Checks if two guilds are not equal.

hash(x)

Returns the guild’s hash.

str(x)

Returns the guild’s name.

name

str – The guild name.

emojis

A tuple of Emoji that the guild owns.

region

VoiceRegion – The region the guild belongs on. There is a chance that the region will be a str if the value is not recognised by the enumerator.

afk_timeout

int – The timeout to get sent to the AFK channel.

afk_channel

Optional[VoiceChannel] – The channel that denotes the AFK channel. None if it doesn’t exist.

icon

Optional[str] – The guild’s icon.

id

int – The guild’s ID.

owner_id

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

unavailable

bool – 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.

max_presences

Optional[int] – The maximum amount of presences for the guild.

max_members

Optional[int] – The maximum amount of members for the guild.

banner

Optional[str] – The guild’s banner.

description

Optional[str] – The guild’s description.

mfa_level

int – 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.

verification_level

VerificationLevel – The guild’s verification level.

explicit_content_filter

ContentFilter – The guild’s explicit content filter.

default_notifications

NotificationLevel – The guild’s notification settings.

features

List[str] – A list of features that the guild has. They are currently as follows:

  • VIP_REGIONS: Guild has VIP voice regions

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

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

  • VERIFIED: Guild is a “verified” server.

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

splash

Optional[str] – The guild’s invite splash.

channels

List[abc.GuildChannel] – A list of channels that belongs to this guild.

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.

voice_channels

List[VoiceChannel] – A list of voice channels that belongs to this guild.

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

me

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

voice_client

Returns the VoiceClient associated with this guild, if any.

text_channels

List[TextChannel] – A list of text channels that belongs to this guild.

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

categories

List[CategoryChannel] – A list of categories that belongs to this guild.

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.

Returns

The categories and their associated channels.

Return type

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

get_channel(channel_id)

Returns a abc.GuildChannel with the given ID. If not found, returns None.

members

List[Member] – A list of members that belong to this guild.

get_member(user_id)

Returns a Member with the given ID. If not found, returns None.

get_role(role_id)

Returns a Role with the given ID. If not found, returns None.

default_role

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

owner

Member – The member that owns the guild.

icon_url

Returns the URL version of the guild’s icon. Returns an empty string if it has no icon.

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

Returns a friendly URL version of the guild’s icon. Returns an empty string if it has no icon.

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

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

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

Raises

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

Returns

The resulting CDN asset.

Return type

Asset

banner_url

Returns the URL version of the guild’s banner. Returns an empty string if it has no banner.

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

Returns a friendly URL version of the guild’s banner. Returns an empty string if it has no banner.

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

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

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

Raises

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

Returns

The resulting CDN asset.

Return type

Asset

splash_url

Returns the URL version of the guild’s invite splash. Returns an empty string if it has no splash.

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

Returns a friendly URL version of the guild’s invite splash. Returns an empty string if it has no splash.

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

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

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

Raises

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

Returns

The resulting CDN asset.

Return type

Asset

member_count

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

chunked

Returns a boolean indicating if the guild is “chunked”.

A chunked guild means that member_count is equal to the number of members stored in the internal members cache.

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

shard_id

Returns the shard ID for this guild if applicable.

created_at

Returns the guild’s creation time in UTC.

get_member_named(name)

Returns the first member found that matches the name provided.

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

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

If no member is found, None is returned.

Parameters

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

Returns

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

Return type

Member

coroutine create_category_channel(name, *, overwrites=None, reason=None)

This function is a coroutine.

Same as create_text_channel() except makes a CategoryChannel instead.

Note

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

icon
banner
splash
afk_channel
system_channel

Optional[TextChannel] – Returns the guild’s channel used for system messages.

Currently this is only for new member joins. If no channel is set, then this returns None.

afk_timeout
coroutine ban(user, *, reason=None, delete_message_days=1)

This function is a coroutine.

Bans a user from the guild.

The user must meet the abc.Snowflake abc.

You must have the ban_members permission to do this.

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

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

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

Raises
  • Forbidden – You do not have the proper permissions to ban.

  • HTTPException – Banning failed.

coroutine bans()

This function is a coroutine.

Retrieves all the users that are banned from the guild.

This coroutine returns a list of BanEntry objects, which is a namedtuple with a user field to denote the User that got banned along with a reason field specifying why the user was banned that could be set to None.

You must have the ban_members permission to get this information.

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

  • HTTPException – An error occurred while fetching the information.

Returns

A list of BanEntry objects.

Return type

List[BanEntry]

coroutine create_category(name, *, overwrites=None, reason=None)

This function is a coroutine.

Same as create_text_channel() except makes a CategoryChannel instead.

Note

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

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

This function is a coroutine.

Creates a custom Emoji for the guild.

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

You must have the manage_emojis permission to do this.

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

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

  • roles (Optional[List[Role]]) – A list of Roles that can use this emoji. Leave empty to make it available to everyone.

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

Raises
  • Forbidden – You are not allowed to create emojis.

  • HTTPException – An error occurred creating an emoji.

Returns

The created emoji.

Return type

Emoji

coroutine create_role(*, reason=None, **fields)

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.

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

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

  • colour (Colour) – 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 (Optional[str]) – The reason for creating this role. Shows up on the audit log.

Raises
  • Forbidden – You do not have permissions to create the role.

  • HTTPException – Creating the role failed.

  • InvalidArgument – An invalid keyword argument was given.

Returns

The newly created role.

Return type

Role

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

This function is a coroutine.

Creates a TextChannel for the guild.

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

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

Note

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

Examples

Creating a basic channel:

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

Creating a “secret” channel:

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

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

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

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

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

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

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

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

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

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

  • HTTPException – Creating the channel failed.

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

Returns

The channel that was just created.

Return type

TextChannel

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

This function is a coroutine.

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

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

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

default_notifications
coroutine delete()

This function is a coroutine.

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

Raises
  • HTTPException – Deleting the guild failed.

  • Forbidden – You do not have permissions to delete the guild.

description
coroutine edit(*, reason=None, **fields)

This function is a coroutine.

Edits the guild.

You must have the manage_guild permission to edit the guild.

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

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

  • icon (bytes) – A bytes-like object representing the icon. Only PNG/JPEG supported. Could be None to denote removal of the icon.

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

  • splash (bytes) – A bytes-like object representing the invite splash. Only PNG/JPEG supported. Could be None to denote removing the splash. Only available for partnered guilds with INVITE_SPLASH feature.

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

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

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

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

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

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

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

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

  • system_channel (Optional[TextChannel]) – The new channel that is used for the system channel. Could be None for no system channel.

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

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

  • HTTPException – Editing the guild failed.

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

emojis
coroutine estimate_pruned_members(*, days)

This function is a coroutine.

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

Parameters

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

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

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

  • InvalidArgument – An integer was not passed for days.

Returns

The number of members estimated to be pruned.

Return type

int

features
coroutine fetch_ban(user)

This function is a coroutine.

Retrieves the BanEntry for a user, which is a namedtuple with a user and reason field. See bans() for more information.

You must have the ban_members permission to get this information.

Parameters

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

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

  • NotFound – This user is not banned.

  • HTTPException – An error occurred while fetching the information.

Returns

The BanEntry object for the specified user.

Return type

BanEntry

coroutine fetch_emoji(emoji_id)

This function is a coroutine.

Retrieves a custom Emoji from the guild.

Note

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

Parameters

emoji_id (int) – The emoji’s ID.

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

  • HTTPException – An error occurred fetching the emoji.

Returns

The retrieved emoji.

Return type

Emoji

coroutine fetch_emojis()

This function is a coroutine.

Retrieves all custom Emojis from the guild.

Note

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

Raises

HTTPException – An error occurred fetching the emojis.

Returns

The retrieved emojis.

Return type

List[Emoji]

coroutine fetch_member(member_id)

This function is a coroutine.

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

Note

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

Parameters

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

Raises
  • Forbidden – You do not have access to the guild.

  • HTTPException – Getting the guild failed.

Returns

The member from the member ID.

Return type

Member

id
coroutine invites()

This function is a coroutine.

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

You must have the manage_guild permission to get this information.

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

  • HTTPException – An error occurred while fetching the information.

Returns

The list of invites that are currently active.

Return type

List[Invite]

coroutine kick(user, *, reason=None)

This function is a coroutine.

Kicks a user from the guild.

The user must meet the abc.Snowflake abc.

You must have the kick_members permission to do this.

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

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

Raises
  • Forbidden – You do not have the proper permissions to kick.

  • HTTPException – Kicking failed.

coroutine leave()

This function is a coroutine.

Leaves the guild.

Note

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

Raises

HTTPException – Leaving the guild failed.

max_members
max_presences
mfa_level
name
owner_id
premium_tier
coroutine prune_members(*, days, compute_prune_count=True, reason=None)

This function is a coroutine.

Prunes the guild from its inactive members.

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

You must have the kick_members permission to use this.

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

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

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

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

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

  • HTTPException – An error occurred while pruning members.

  • InvalidArgument – An integer was not passed for days.

Returns

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

Return type

Optional[int]

region
unavailable
coroutine unban(user, *, reason=None)

This function is a coroutine.

Unbans a user from the guild.

The user must meet the abc.Snowflake abc.

You must have the ban_members permission to do this.

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

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

Raises
  • Forbidden – You do not have the proper permissions to unban.

  • HTTPException – Unbanning failed.

coroutine vanity_invite()

This function is a coroutine.

Returns the guild’s special vanity invite.

The guild must be partnered, i.e. have ‘VANITY_URL’ in features.

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

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

  • HTTPException – Retrieving the vanity invite failed.

Returns

The special vanity invite.

Return type

Invite

verification_level
coroutine webhooks()

This function is a coroutine.

Gets the list of webhooks from this guild.

Requires manage_webhooks permissions.

Raises

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

Returns

The webhooks for this guild.

Return type

List[Webhook]

coroutine widget()

This function is a coroutine.

Returns the widget of the guild.

Note

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

Raises
  • Forbidden – The widget for this guild is disabled.

  • HTTPException – Retrieving the widget failed.

Returns

The guild’s widget.

Return type

Widget

explicit_content_filter
roles

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

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

ack()

This function is a coroutine.

Marks every message in this guild as read.

The user must not be a bot user.

Raises
  • HTTPException – Acking failed.

  • ClientException – You must not be a bot user.

audit_logs(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)

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

You must have the view_audit_log permission to use this.

Examples

Getting the first 100 entries:

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

Getting entries for a specific action:

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

Getting entries made by a specific user:

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

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

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

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

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

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

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

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

Yields

AuditLogEntry – The audit log entry.

discord.http module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.http.Route(method, path, **parameters)

Bases: object

BASE = 'https://discordapp.com/api/v7'
bucket
class discord.http.MaybeUnlock(lock)

Bases: object

defer()
class discord.http.HTTPClient(connector=None, *, proxy=None, proxy_auth=None, loop=None)

Bases: object

Represents an HTTP client sending HTTP requests to the Discord API.

SUCCESS_LOG = '{method} {url} has received {text}'
REQUEST_LOG = '{method} {url} with {json} has returned {status}'
recreate()
logout()
start_group(user_id, recipients)
leave_group(channel_id)
add_group_recipient(channel_id, user_id)
remove_group_recipient(channel_id, user_id)
edit_group(channel_id, **options)
convert_group(channel_id)
start_private_message(user_id)
send_message(channel_id, content, *, tts=False, embed=None, nonce=None)
send_typing(channel_id)
send_files(channel_id, *, files, content=None, tts=False, embed=None, nonce=None)
ack_guild(guild_id)
delete_message(channel_id, message_id, *, reason=None)
delete_messages(channel_id, message_ids, *, reason=None)
edit_message(channel_id, message_id, **fields)
add_reaction(channel_id, message_id, emoji)
remove_reaction(channel_id, message_id, emoji, member_id)
remove_own_reaction(channel_id, message_id, emoji)
get_reaction_users(channel_id, message_id, emoji, limit, after=None)
clear_reactions(channel_id, message_id)
get_message(channel_id, message_id)
logs_from(channel_id, limit, before=None, after=None, around=None)
pin_message(channel_id, message_id)
unpin_message(channel_id, message_id)
pins_from(channel_id)
kick(user_id, guild_id, reason=None)
ban(user_id, guild_id, delete_message_days=1, reason=None)
unban(user_id, guild_id, *, reason=None)
guild_voice_state(user_id, guild_id, *, mute=None, deafen=None, reason=None)
edit_profile(password, username, avatar, **fields)
change_my_nickname(guild_id, nickname, *, reason=None)
change_nickname(guild_id, user_id, nickname, *, reason=None)
edit_member(guild_id, user_id, *, reason=None, **fields)
edit_channel(channel_id, *, reason=None, **options)
bulk_channel_update(guild_id, data, *, reason=None)
create_channel(guild_id, channel_type, *, reason=None, **options)
delete_channel(channel_id, *, reason=None)
create_webhook(channel_id, *, name, avatar=None, reason=None)
channel_webhooks(channel_id)
guild_webhooks(guild_id)
get_webhook(webhook_id)
get_guilds(limit, before=None, after=None)
leave_guild(guild_id)
get_guild(guild_id)
delete_guild(guild_id)
create_guild(name, region, icon)
edit_guild(guild_id, *, reason=None, **fields)
get_bans(guild_id)
get_ban(user_id, guild_id)
get_vanity_code(guild_id)
change_vanity_code(guild_id, code, *, reason=None)
get_member(guild_id, member_id)
prune_members(guild_id, days, compute_prune_count, *, reason=None)
estimate_pruned_members(guild_id, days)
get_all_custom_emojis(guild_id)
get_custom_emoji(guild_id, emoji_id)
create_custom_emoji(guild_id, name, image, *, roles=None, reason=None)
delete_custom_emoji(guild_id, emoji_id, *, reason=None)
edit_custom_emoji(guild_id, emoji_id, *, name, roles=None, reason=None)
get_audit_logs(guild_id, limit=100, before=None, after=None, user_id=None, action_type=None)
get_widget(guild_id)
create_invite(channel_id, *, reason=None, **options)
get_invite(invite_id, *, with_counts=True)
invites_from(guild_id)
invites_from_channel(channel_id)
delete_invite(invite_id, *, reason=None)
edit_role(guild_id, role_id, *, reason=None, **fields)
delete_role(guild_id, role_id, *, reason=None)
replace_roles(user_id, guild_id, role_ids, *, reason=None)
create_role(guild_id, *, reason=None, **fields)
move_role_position(guild_id, positions, *, reason=None)
add_role(guild_id, user_id, role_id, *, reason=None)
remove_role(guild_id, user_id, role_id, *, reason=None)
edit_channel_permissions(channel_id, target, allow, deny, type, *, reason=None)
delete_channel_permissions(channel_id, target, *, reason=None)
move_member(user_id, guild_id, channel_id, *, reason=None)
remove_relationship(user_id)
add_relationship(user_id, type=None)
send_friend_request(username, discriminator)
application_info()
coroutine ack_message(channel_id, message_id)
coroutine close()
coroutine get_bot_gateway(*, encoding='json', v=6, zlib=True)
coroutine get_from_cdn(url)
coroutine get_gateway(*, encoding='json', v=6, zlib=True)
coroutine request(route, *, files=None, header_bypass_delay=None, **kwargs)
coroutine static_login(token, *, bot)
get_user(user_id)
get_user_profile(user_id)
get_mutual_friends(user_id)
change_hypesquad_house(house_id)
leave_hypesquad_house()
edit_settings(**payload)
coroutine discord.http.json_or_text(response)

discord.invite module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.invite.PartialInviteChannel

Bases: discord.invite.PartialInviteChannel

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

str – The partial channel’s name.

id

int – The partial channel’s ID.

type

ChannelType – The partial channel’s type.

mention

str – The string that allows you to mention the channel.

created_at

Returns the channel’s creation time in UTC.

class discord.invite.PartialInviteGuild(state, data, id)

Bases: object

Represents a “partial” invite guild.

This model will be given when the user is not part of the guild the Invite resolves to.

x == y

Checks if two partial guilds are the same.

x != y

Checks if two partial guilds are not the same.

hash(x)

Return the partial guild’s hash.

str(x)

Returns the partial guild’s name.

name

str – The partial guild’s name.

id

int – The partial guild’s ID.

verification_level

VerificationLevel – The partial guild’s verification level.

features

List[str] – A list of features the guild has. See Guild.features for more information.

icon

Optional[str] – The partial guild’s icon.

banner

Optional[str] – The partial guild’s banner.

splash

Optional[str] – The partial guild’s invite splash.

description

Optional[str] – The partial guild’s description.

id
name
features
icon
banner
splash
verification_level
description
created_at

Returns the guild’s creation time in UTC.

icon_url

Returns the URL version of the guild’s icon. Returns an empty string if it has no icon.

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

Asset: The same operation as Guild.icon_url_as().

banner_url

Returns the URL version of the guild’s banner. Returns an empty string if it has no banner.

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

Asset: The same operation as Guild.banner_url_as().

splash_url

Returns the URL version of the guild’s invite splash. Returns an empty string if it has no splash.

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

Asset: The same operation as Guild.splash_url_as().

class discord.invite.Invite(*, state, data)

Bases: discord.mixins.Hashable

Represents a Discord Guild or abc.GuildChannel invite.

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

x == y

Checks if two invites are equal.

x != y

Checks if two invites are not equal.

hash(x)

Returns the invite hash.

str(x)

Returns the invite URL.

max_age

int – How long the before the invite expires in seconds. A value of 0 indicates that it doesn’t expire.

code

str – The URL fragment used for the invite.

guild

Union[Guild, PartialInviteGuild] – The guild the invite is for.

revoked

bool – Indicates if the invite has been revoked.

created_at

datetime.datetime – A datetime object denoting the time the invite was created.

temporary

bool – Indicates that the invite grants temporary membership. If True, members who joined via this invite will be kicked upon disconnect.

uses

int – How many times the invite has been used.

max_uses

int – How many times the invite can be used.

inviter

User – The user who created the invite.

approximate_member_count

Optional[int] – The approximate number of members in the guild.

approximate_presence_count

Optional[int] – The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded.

channel

Union[abc.GuildChannel, PartialInviteChannel] – The channel the invite is for.

max_age
code
guild
revoked
created_at
temporary
uses
max_uses
approximate_presence_count
approximate_member_count
inviter
channel
classmethod from_incomplete(*, state, data)
id

Returns the proper code portion of the invite.

url

A property that retrieves the invite URL.

coroutine delete(*, reason=None)

This function is a coroutine.

Revokes the instant invite.

You must have the manage_channels permission to do this.

Parameters

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

Raises
  • Forbidden – You do not have permissions to revoke invites.

  • NotFound – The invite is invalid or expired.

  • HTTPException – Revoking the invite failed.

discord.iterators module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.iterators.ReactionIterator(message, emoji, limit=100, after=None)

Bases: discord.iterators._AsyncIterator

coroutine fill_users()
coroutine next()
class discord.iterators.HistoryIterator(messageable, limit, before=None, after=None, around=None, oldest_first=None)

Bases: discord.iterators._AsyncIterator

Iterator for receiving a channel’s message history.

The messages endpoint has two behaviours we care about here: If before is specified, the messages endpoint returns the limit newest messages before before, sorted with newest first. For filling over 100 messages, update the before parameter to the oldest message received. Messages will be returned in order by time. If after is specified, it returns the limit oldest messages after after, sorted with newest first. For filling over 100 messages, update the after parameter to the newest message received. If messages are not reversed, they will be out of order (99-0, 199-100, so on)

A note that if both before and after are specified, before is ignored by the messages endpoint.

Parameters
  • messageable (abc.Messageable) – Messageable class to retrieve message history from.

  • limit (int) – Maximum number of messages to retrieve

  • before (abc.Snowflake) – Message before which all messages must be.

  • after (abc.Snowflake) – Message after which all messages must be.

  • around (abc.Snowflake) – Message around which all messages must be. Limit max 101. Note that if limit is an even number, this will return at most limit+1 messages.

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

coroutine fill_messages()
coroutine flatten()
coroutine next()
class discord.iterators.AuditLogIterator(guild, limit=None, before=None, after=None, oldest_first=None, user_id=None, action_type=None)

Bases: discord.iterators._AsyncIterator

coroutine next()
class discord.iterators.GuildIterator(bot, limit, before=None, after=None)

Bases: discord.iterators._AsyncIterator

Iterator for receiving the client’s guilds.

The guilds endpoint has the same two behaviours as described in HistoryIterator: If before is specified, the guilds endpoint returns the limit newest guilds before before, sorted with newest first. For filling over 100 guilds, update the before parameter to the oldest guild received. Guilds will be returned in order by time. If after is specified, it returns the limit oldest guilds after after, sorted with newest first. For filling over 100 guilds, update the after parameter to the newest guild received, If guilds are not reversed, they will be out of order (99-0, 199-100, so on)

Not that if both before and after are specified, before is ignored by the guilds endpoint.

Parameters
  • bot (discord.Client) – The client to retrieve the guilds from.

  • limit (int) – Maximum number of guilds to retrieve.

  • before (Snowflake) – Object before which all guilds must be.

  • after (Snowflake) – Object after which all guilds must be.

coroutine fill_guilds()
coroutine flatten()
coroutine next()
create_guild(data)

discord.member module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.member.VoiceState(*, data, channel=None)

Bases: object

Represents a Discord user’s voice state.

deaf

bool – Indicates if the user is currently deafened by the guild.

mute

bool – Indicates if the user is currently muted by the guild.

self_mute

bool – Indicates if the user is currently muted by their own accord.

self_deaf

bool – Indicates if the user is currently deafened by their own accord.

self_video

bool – Indicates if the user is currently broadcasting video.

afk

bool – Indicates if the user is currently in the AFK channel in the guild.

channel

VoiceChannel – The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.

session_id
afk
channel
deaf
mute
self_deaf
self_mute
self_video
discord.member.flatten_user(cls)
class discord.member.Member(*, data, guild, state)

Bases: discord.abc.Messageable, discord.abc.User

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.

joined_at

Optional[datetime.datetime] – A datetime object that specifies the date and time in UTC that the member joined the guild for the first time. In certain cases, this can be None.

activities

Tuple[Union[Game, Streaming, Spotify, Activity]] – The activities that the user is currently doing.

guild

Guild – The guild that the member belongs to.

nick

Optional[str] – The guild specific nickname of the user.

guild
joined_at
activities
status

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

mobile_status

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

desktop_status

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

web_status

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

is_on_mobile()

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

colour

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

There is an alias for this under color.

color

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

There is an alias for this under color.

mention

Returns a string that mentions the member.

display_name

Returns the user’s display name.

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

activity

Returns a class Union[Game, Streaming, Spotify, Activity] for the primary activity the user is currently doing. Could be None if no activity is being done.

Note

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.

Parameters

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

permissions_in(channel)

An alias for abc.GuildChannel.permissions_for().

Basically equivalent to:

channel.permissions_for(self)
Parameters

channel (Channel) – The channel to check your permissions for.

top_role

Returns the member’s highest role.

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

guild_permissions

Returns the member’s guild permissions.

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

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

voice

Optional[VoiceState] – Returns the member’s current voice state.

nick
coroutine 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.

Parameters
  • *roles (Snowflake) – An argument list of abc.Snowflake representing a Role to give to the member.

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

  • atomic (bool) – Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.

Raises
  • Forbidden – You do not have permissions to add these roles.

  • HTTPException – Adding roles failed.

avatar

Equivalent to User.avatar

avatar_url

Equivalent to User.avatar_url

avatar_url_as(*args, **kwargs)

Returns a friendly URL version of the avatar the user has.

If the user does not have a traditional avatar, their default avatar URL is returned instead.

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

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

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

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

Raises

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

Returns

The resulting CDN asset.

Return type

Asset

coroutine ban(**kwargs)

This function is a coroutine.

Bans this member. Equivalent to Guild.ban()

block(*args, **kwargs)

This function is a coroutine.

Blocks the user.

Note

This only applies to non-bot accounts.

Raises
  • Forbidden – Not allowed to block this user.

  • HTTPException – Blocking the user failed.

bot

Equivalent to User.bot

create_dm(*args, **kwargs)

Creates a DMChannel with this user.

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

created_at

Equivalent to User.created_at

default_avatar

Equivalent to User.default_avatar

default_avatar_url

Equivalent to User.default_avatar_url

discriminator

Equivalent to User.discriminator

dm_channel

Equivalent to User.dm_channel

coroutine edit(*, reason=None, **fields)

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

All parameters are optional.

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

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

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

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

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

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

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

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

  • HTTPException – The operation failed.

id

Equivalent to User.id

is_avatar_animated(*args, **kwargs)

bool: Returns True if the user has an animated avatar.

is_blocked(*args, **kwargs)

bool: Checks if the user is blocked.

Note

This only applies to non-bot accounts.

is_friend(*args, **kwargs)

bool: Checks if the user is your friend.

Note

This only applies to non-bot accounts.

coroutine kick(*, reason=None)

This function is a coroutine.

Kicks this member. Equivalent to Guild.kick()

coroutine move_to(channel, *, reason=None)

This function is a coroutine.

Moves a member to a new voice channel (they must be connected first).

You must have the move_members permission to use this.

This raises the same exceptions as edit().

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

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

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

mutual_friends(*args, **kwargs)

This function is a coroutine.

Gets all mutual friends of this user.

Note

This only applies to non-bot accounts.

Raises
  • Forbidden – Not allowed to get mutual friends of this user.

  • HTTPException – Getting mutual friends failed.

Returns

The users that are mutual friends.

Return type

List[User]

name

Equivalent to User.name

profile(*args, **kwargs)

This function is a coroutine.

Gets the user’s profile.

Note

This only applies to non-bot accounts.

Raises
  • Forbidden – Not allowed to fetch profiles.

  • HTTPException – Fetching the profile failed.

Returns

The profile of the user.

Return type

Profile

relationship

Equivalent to User.relationship

remove_friend(*args, **kwargs)

This function is a coroutine.

Removes the user as a friend.

Note

This only applies to non-bot accounts.

Raises
  • Forbidden – Not allowed to remove this user as a friend.

  • HTTPException – Removing the user as a friend failed.

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

Parameters
  • *roles (Snowflake) – An argument list of abc.Snowflake representing a Role to remove from the member.

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

  • atomic (bool) – Whether to atomically remove roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.

Raises
  • Forbidden – You do not have permissions to remove these roles.

  • HTTPException – Removing the roles failed.

roles

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

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

send_friend_request(*args, **kwargs)

This function is a coroutine.

Sends the user a friend request.

Note

This only applies to non-bot accounts.

Raises
  • Forbidden – Not allowed to send a friend request to the user.

  • HTTPException – Sending the friend request failed.

coroutine unban(*, reason=None)

This function is a coroutine.

Unbans this member. Equivalent to Guild.unban()

unblock(*args, **kwargs)

This function is a coroutine.

Unblocks the user.

Note

This only applies to non-bot accounts.

Raises
  • Forbidden – Not allowed to unblock this user.

  • HTTPException – Unblocking the user failed.

discord.message module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.message.Attachment(*, data, state)

Bases: object

Represents an attachment from Discord.

id

int – The attachment ID.

size

int – The attachment size in bytes.

height

Optional[int] – The attachment’s height, in pixels. Only applicable to images.

width

Optional[int] – The attachment’s width, in pixels. Only applicable to images.

filename

str – The attachment’s filename.

url

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

proxy_url

str – 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.

id
size
height
width
filename
proxy_url
is_spoiler()

bool: Whether this attachment contains a spoiler.

url
coroutine read(*, use_cached=False)

This function is a coroutine.

Retrieves the content of this attachment as a bytes object.

New in version 1.1.0.

Parameters

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

Raises
  • HTTPException – Downloading the attachment failed.

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

  • NotFound – The attachment was deleted.

Returns

The contents of the attachment.

Return type

bytes

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

This function is a coroutine.

Saves this attachment into a file-like object.

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

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

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

Raises
  • HTTPException – Saving the attachment failed.

  • NotFound – The attachment was deleted.

Returns

The number of bytes written.

Return type

int

class discord.message.Message(*, state, channel, data)

Bases: object

Represents a message from Discord.

There should be no need to create one of these manually.

tts

bool – Specifies if the message was done with text-to-speech.

type

MessageType – 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.

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.

content

str – The actual contents of the message.

nonce

The value used by the discord guild and the client to verify that the message is successfully sent. This is typically non-important.

embeds

List[Embed] – A list of embeds the message has.

channel

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

call

Optional[CallMessage] – The call that the message refers to. This is only applicable to messages of type MessageType.call.

mention_everyone

bool – Specifies if the message mentions everyone.

Note

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

mentions

list – A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a discord limitation, not one with the library.

channel_mentions

list – A list of abc.GuildChannel that were mentioned. If the message is in a private message then the list is always empty.

role_mentions

list – A list of Role that were mentioned. If the message is in a private message then the list is always empty.

id

int – The message ID.

webhook_id

Optional[int] – If this message was sent by a webhook, then this is the webhook ID’s that sent this message.

attachments

List[Attachment] – A list of attachments given to a message.

pinned

bool – Specifies if the message is currently pinned.

reactions

List[Reaction] – Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.

activity

Optional[dict] – 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.

application

Optional[dict] – 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.

id
webhook_id
reactions
application
activity
guild

Optional[Guild] – The guild that the message belongs to, if applicable.

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.

channel_mentions
clean_content

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

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

Note

This does not escape markdown. If you want to escape markdown then use utils.escape_markdown() along with this function.

created_at

datetime.datetime – The message’s creation time in UTC.

edited_at

Optional[datetime.datetime] – A naive UTC datetime object containing the edited time of the message.

jump_url

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

system_content

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

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

content
coroutine ack()

This function is a coroutine.

Marks this message as read.

The user must not be a bot user.

Raises
  • HTTPException – Acking failed.

  • ClientException – You must not be a bot user.

coroutine add_reaction(emoji)

This function is a coroutine.

Add a reaction to the message.

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

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

Parameters

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

Raises
  • HTTPException – Adding the reaction failed.

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

  • NotFound – The emoji you specified was not found.

  • InvalidArgument – The emoji parameter is invalid.

attachments
author
call
channel
coroutine clear_reactions()

This function is a coroutine.

Removes all the reactions from the message.

You need the manage_messages permission to use this.

Raises
  • HTTPException – Removing the reactions failed.

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

coroutine delete(*, delay=None)

This function is a coroutine.

Deletes the message.

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

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

Parameters

delay (Optional[float]) – If provided, the number of seconds to wait in the background before deleting the message.

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

  • HTTPException – Deleting the message failed.

coroutine edit(**fields)

This function is a coroutine.

Edits the message.

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

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

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

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

Raises

HTTPException – Editing the message failed.

embeds
mention_everyone
mentions
nonce
coroutine pin()

This function is a coroutine.

Pins the message.

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

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

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

  • HTTPException – Pinning the message failed, probably due to the channel having more than 50 pinned messages.

pinned
coroutine remove_reaction(emoji, member)

This function is a coroutine.

Remove a reaction by the member from the message.

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

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

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

Parameters
  • emoji (Union[Emoji, Reaction, PartialEmoji, str]) – The emoji to remove.

  • member (abc.Snowflake) – The member for which to remove the reaction.

Raises
  • HTTPException – Removing the reaction failed.

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

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

  • InvalidArgument – The emoji parameter is invalid.

role_mentions
tts
type
coroutine unpin()

This function is a coroutine.

Unpins the message.

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

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

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

  • HTTPException – Unpinning the message failed.

discord.mixins module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.mixins.EqualityComparable

Bases: object

class discord.mixins.Hashable

Bases: discord.mixins.EqualityComparable

discord.object module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.object.Object(id)

Bases: discord.mixins.Hashable

Represents a generic Discord object.

The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.

There are also some cases where some websocket events are received in strange order and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.

x == y

Checks if two objects are equal.

x != y

Checks if two objects are not equal.

hash(x)

Returns the object’s hash.

id

str – The ID of the object.

created_at

Returns the snowflake’s creation time in UTC.

discord.opus module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

discord.opus.c_int_ptr

alias of discord.opus.LP_c_int

discord.opus.c_int16_ptr

alias of discord.opus.LP_c_short

discord.opus.c_float_ptr

alias of discord.opus.LP_c_float

class discord.opus.EncoderStruct

Bases: _ctypes.Structure

discord.opus.EncoderStructPtr

alias of discord.opus.LP_EncoderStruct

discord.opus.libopus_loader(name)
discord.opus.load_opus(name)

Loads the libopus shared library for use with voice.

If this function is not called then the library uses the function ctypes.util.find_library and then loads that one if available.

Not loading a library leads to voice not working.

This function propagates the exceptions thrown.

Note

On Windows, this function should not need to be called as the binaries are automatically loaded.

Warning

The bitness of the library must match the bitness of your python interpreter. If the library is 64-bit then your python interpreter must be 64-bit as well. Usually if there’s a mismatch in bitness then the load will throw an exception.

Note

On Windows, the .dll extension is not necessary. However, on Linux the full extension is required to load the library, e.g. libopus.so.1. On Linux however, find library will usually find the library automatically without you having to call this.

Parameters

name (str) – The filename of the shared library.

discord.opus.is_loaded()

Function to check if opus lib is successfully loaded either via the ctypes.util.find_library call of load_opus().

This must return True for voice to work.

Returns

Indicates if the opus library has been loaded.

Return type

bool

exception discord.opus.OpusError(code)

Bases: discord.errors.DiscordException

An exception that is thrown for libopus related errors.

code

int – The error code returned.

exception discord.opus.OpusNotLoaded

Bases: discord.errors.DiscordException

An exception that is thrown for when libopus is not loaded.

class discord.opus.Encoder(application=2049)

Bases: object

SAMPLING_RATE = 48000
CHANNELS = 2
FRAME_LENGTH = 20
SAMPLE_SIZE = 4
SAMPLES_PER_FRAME = 960
FRAME_SIZE = 3840
set_bitrate(kbps)
set_bandwidth(req)
set_signal_type(req)
set_fec(enabled=True)
set_expected_packet_loss_percent(percentage)
encode(pcm, frame_size)

discord.permissions module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.permissions.Permissions(permissions=0)

Bases: object

Wraps up the Discord permission value.

The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.

x == y

Checks if two permissions are equal.

x != y

Checks if two permissions are not equal.

x <= y

Checks if a permission is a subset of another permission.

x >= y

Checks if a permission is a superset of another permission.

x < y

Checks if a permission is a strict subset of another permission.

x > y

Checks if a permission is a strict superset of another permission.

hash(x)

Return the permission’s hash.

iter(x)

Returns an iterator of (perm, value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs.

value

The raw value. This value is a bit array field of a 53-bit integer representing the currently available permissions. You should query permissions via the properties rather than using this raw value.

value
is_subset(other)

Returns True if self has the same or fewer permissions as other.

is_superset(other)

Returns True if self has the same or more permissions as other.

is_strict_subset(other)

Returns True if the permissions on other are a strict subset of those on self.

is_strict_superset(other)

Returns True if the permissions on other are a strict superset of those on self.

classmethod none()

A factory method that creates a Permissions with all permissions set to False.

classmethod all()

A factory method that creates a Permissions with all permissions set to True.

classmethod all_channel()

A Permissions with all channel-specific permissions set to True and the guild-specific ones set to False. The guild-specific permissions are currently:

  • manage_guild

  • kick_members

  • ban_members

  • administrator

  • change_nickname

  • manage_nicknames

classmethod general()

A factory method that creates a Permissions with all “General” permissions from the official Discord UI set to True.

classmethod text()

A factory method that creates a Permissions with all “Text” permissions from the official Discord UI set to True.

classmethod voice()

A factory method that creates a Permissions with all “Voice” permissions from the official Discord UI set to True.

update(**kwargs)

Bulk updates this permission object.

Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored.

Parameters

**kwargs – A list of key/value pairs to bulk update permissions with.

handle_overwrite(allow, deny)
create_instant_invite

Returns True if the user can create instant invites.

kick_members

Returns True if the user can kick users from the guild.

ban_members

Returns True if a user can ban users from the guild.

administrator

Returns True if a user is an administrator. This role overrides all other permissions.

This also bypasses all channel-specific overrides.

manage_channels

Returns True if a user can edit, delete, or create channels in the guild.

This also corresponds to the “Manage Channel” channel-specific override.

manage_guild

Returns True if a user can edit guild properties.

add_reactions

Returns True if a user can add reactions to messages.

view_audit_log

Returns True if a user can view the guild’s audit log.

priority_speaker

Returns True if a user can be more easily heard while talking.

stream

Returns True if a user can stream in a voice channel.

read_messages

Returns True if a user can read messages from all or specific text channels.

send_messages

Returns True if a user can send messages from all or specific text channels.

send_tts_messages

Returns True if a user can send TTS messages from all or specific text channels.

manage_messages

Returns True if a user can delete or pin messages in a text channel. Note that there are currently no ways to edit other people’s messages.

Returns True if a user’s messages will automatically be embedded by Discord.

attach_files

Returns True if a user can send files in their messages.

read_message_history

Returns True if a user can read a text channel’s previous messages.

mention_everyone

Returns True if a user’s @everyone or @here will mention everyone in the text channel.

external_emojis

Returns True if a user can use emojis from other guilds.

connect

Returns True if a user can connect to a voice channel.

speak

Returns True if a user can speak in a voice channel.

mute_members

Returns True if a user can mute other users.

deafen_members

Returns True if a user can deafen other users.

move_members

Returns True if a user can move users between other voice channels.

use_voice_activation

Returns True if a user can use voice activation in voice channels.

change_nickname

Returns True if a user can change their nickname in the guild.

manage_nicknames

Returns True if a user can change other user’s nickname in the guild.

manage_roles

Returns True if a user can create or edit roles less than their role’s position.

This also corresponds to the “Manage Permissions” channel-specific override.

manage_webhooks

Returns True if a user can create, edit, or delete webhooks.

manage_emojis

Returns True if a user can create, edit, or delete emojis.

discord.permissions.augment_from_permissions(cls)
class discord.permissions.PermissionOverwrite(**kwargs)

Bases: object

A type that is used to represent a channel specific permission.

Unlike a regular Permissions, the default value of a permission is equivalent to None and not False. Setting a value to False is explicitly denying that permission, while setting a value to True is explicitly allowing that permission.

The values supported by this are the same as Permissions with the added possibility of it being set to None.

Supported operations:

Operation

Description

x == y

Checks if two overwrites are equal.

x != y

Checks if two overwrites are not equal.

iter(x)

Returns an iterator of (perm, value) pairs. This allows this class to be used as an iterable in e.g. set/list/dict constructions.

Parameters

**kwargs – Set the value of permissions by their name.

VALID_NAMES = {'manage_messages', 'add_reactions', 'manage_nicknames', 'change_nickname', 'external_emojis', 'read_message_history', 'connect', 'manage_webhooks', 'administrator', 'mute_members', 'create_instant_invite', 'mention_everyone', 'move_members', 'manage_emojis', 'kick_members', 'speak', 'attach_files', 'priority_speaker', 'manage_roles', 'send_messages', 'read_messages', 'send_tts_messages', 'deafen_members', 'view_audit_log', 'manage_guild', 'manage_channels', 'ban_members', 'stream', 'embed_links', 'use_voice_activation'}
add_reactions
administrator
attach_files
ban_members
change_nickname
connect
create_instant_invite
deafen_members
external_emojis
kick_members
manage_channels
manage_emojis
manage_guild
manage_messages
manage_nicknames
manage_roles
manage_webhooks
mention_everyone
move_members
mute_members
priority_speaker
read_message_history
read_messages
send_messages
send_tts_messages
speak
stream
use_voice_activation
view_audit_log
pair()

Returns the (allow, deny) pair from this overwrite.

The value of these pairs is Permissions.

classmethod from_pair(allow, deny)

Creates an overwrite from an allow/deny pair of Permissions.

is_empty()

Checks if the permission overwrite is currently empty.

An empty permission overwrite is one that has no overwrites set to True or False.

update(**kwargs)

Bulk updates this permission overwrite object.

Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored.

Parameters

**kwargs – A list of key/value pairs to bulk update with.

discord.player module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.player.AudioSource

Bases: object

Represents an audio stream.

The audio stream can be Opus encoded or not, however if the audio stream is not Opus encoded then the audio format must be 16-bit 48KHz stereo PCM.

Warning

The audio source reads are done in a separate thread.

read()

Reads 20ms worth of audio.

Subclasses must implement this.

If the audio is complete, then returning an empty bytes-like object to signal this is the way to do so.

If is_opus() method returns True, then it must return 20ms worth of Opus encoded audio. Otherwise, it must be 20ms worth of 16-bit 48KHz stereo PCM, which is about 3,840 bytes per frame (20ms worth of audio).

Returns

A bytes like object that represents the PCM or Opus data.

Return type

bytes

is_opus()

Checks if the audio source is already encoded in Opus.

Defaults to False.

cleanup()

Called when clean-up is needed to be done.

Useful for clearing buffer data or processes after it is done playing audio.

class discord.player.PCMAudio(stream)

Bases: discord.player.AudioSource

Represents raw 16-bit 48KHz stereo PCM audio source.

stream

file-like object – A file-like object that reads byte data representing raw PCM.

read()

Reads 20ms worth of audio.

Subclasses must implement this.

If the audio is complete, then returning an empty bytes-like object to signal this is the way to do so.

If is_opus() method returns True, then it must return 20ms worth of Opus encoded audio. Otherwise, it must be 20ms worth of 16-bit 48KHz stereo PCM, which is about 3,840 bytes per frame (20ms worth of audio).

Returns

A bytes like object that represents the PCM or Opus data.

Return type

bytes

class discord.player.FFmpegPCMAudio(source, *, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None)

Bases: discord.player.AudioSource

An audio source from FFmpeg (or AVConv).

This launches a sub-process to a specific input file given.

Warning

You must have the ffmpeg or avconv executable in your path environment variable in order for this to work.

Parameters
  • source (Union[str, BinaryIO]) – The input that ffmpeg will take and convert to PCM bytes. If pipe is True then this is a file-like object that is passed to the stdin of ffmpeg.

  • executable (str) – The executable name (and path) to use. Defaults to ffmpeg.

  • pipe (bool) – If true, denotes that source parameter will be passed to the stdin of ffmpeg. Defaults to False.

  • stderr (Optional[BinaryIO]) – A file-like object to pass to the Popen constructor. Could also be an instance of subprocess.PIPE.

  • options (Optional[str]) – Extra command line arguments to pass to ffmpeg after the -i flag.

  • before_options (Optional[str]) – Extra command line arguments to pass to ffmpeg before the -i flag.

Raises

ClientException – The subprocess failed to be created.

read()

Reads 20ms worth of audio.

Subclasses must implement this.

If the audio is complete, then returning an empty bytes-like object to signal this is the way to do so.

If is_opus() method returns True, then it must return 20ms worth of Opus encoded audio. Otherwise, it must be 20ms worth of 16-bit 48KHz stereo PCM, which is about 3,840 bytes per frame (20ms worth of audio).

Returns

A bytes like object that represents the PCM or Opus data.

Return type

bytes

cleanup()

Called when clean-up is needed to be done.

Useful for clearing buffer data or processes after it is done playing audio.

class discord.player.PCMVolumeTransformer(original, volume=1.0)

Bases: discord.player.AudioSource

Transforms a previous AudioSource to have volume controls.

This does not work on audio sources that have AudioSource.is_opus() set to True.

Parameters
  • original (AudioSource) – The original AudioSource to transform.

  • volume (float) – The initial volume to set it to. See volume for more info.

Raises
  • TypeError – Not an audio source.

  • ClientException – The audio source is opus encoded.

volume

Retrieves or sets the volume as a floating point percentage (e.g. 1.0 for 100%).

cleanup()

Called when clean-up is needed to be done.

Useful for clearing buffer data or processes after it is done playing audio.

read()

Reads 20ms worth of audio.

Subclasses must implement this.

If the audio is complete, then returning an empty bytes-like object to signal this is the way to do so.

If is_opus() method returns True, then it must return 20ms worth of Opus encoded audio. Otherwise, it must be 20ms worth of 16-bit 48KHz stereo PCM, which is about 3,840 bytes per frame (20ms worth of audio).

Returns

A bytes like object that represents the PCM or Opus data.

Return type

bytes

discord.raw_models module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.raw_models.RawMessageDeleteEvent(data)

Bases: object

Represents the event payload for a on_raw_message_delete() event.

channel_id

int – The channel ID where the deletion took place.

guild_id

Optional[int] – The guild ID where the deletion took place, if applicable.

message_id

int – The message ID that got deleted.

cached_message

Optional[Message] – The cached message, if found in the internal message cache.

message_id
channel_id
cached_message
guild_id
class discord.raw_models.RawBulkMessageDeleteEvent(data)

Bases: object

Represents the event payload for a on_raw_bulk_message_delete() event.

message_ids

Set[int] – A set of the message IDs that were deleted.

channel_id

int – The channel ID where the message got deleted.

guild_id

Optional[int] – The guild ID where the message got deleted, if applicable.

cached_messages

List[Message] – The cached messages, if found in the internal message cache.

message_ids
channel_id
cached_messages
guild_id
class discord.raw_models.RawMessageUpdateEvent(data)

Bases: object

Represents the payload for a on_raw_message_edit() event.

message_id

int – The message ID that got updated.

data

dict – The raw data given by the gateway <https://discordapp.com/developers/docs/topics/gateway#message-update>

cached_message

Optional[Message] – The cached message, if found in the internal message cache.

message_id
data
cached_message
class discord.raw_models.RawReactionActionEvent(data, emoji)

Bases: object

Represents the payload for a on_raw_reaction_add() or on_raw_reaction_remove() event.

message_id

int – The message ID that got or lost a reaction.

user_id

int – The user ID who added the reaction or whose reaction was removed.

channel_id

int – The channel ID where the reaction got added or removed.

guild_id

Optional[int] – The guild ID where the reaction got added or removed, if applicable.

emoji

PartialEmoji – The custom or unicode emoji being used.

message_id
channel_id
user_id
emoji
guild_id
class discord.raw_models.RawReactionClearEvent(data)

Bases: object

Represents the payload for a on_raw_reaction_clear() event.

message_id

int – The message ID that got its reactions cleared.

channel_id

int – The channel ID where the reactions got cleared.

guild_id

Optional[int] – The guild ID where the reactions got cleared.

message_id
channel_id
guild_id

discord.reaction module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.reaction.Reaction(*, message, data, emoji=None)

Bases: object

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

Emoji or str – The reaction emoji. May be a custom emoji, or a unicode emoji.

count

int – Number of times this reaction was made

me

bool – If the user sent this reaction.

message

Message – Message this reaction is for.

message
emoji
count
me
custom_emoji

bool – If this is a custom emoji.

users(limit=None, after=None)

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

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

Examples

Usage

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

Flattening into a list:

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

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

Raises

HTTPException – Getting the users for the reaction failed.

Yields

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

coroutine 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 discord.permissions.Permissions.manage_messages permission is needed.

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

Parameters

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

Raises
  • HTTPException – Removing the reaction failed.

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

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

discord.relationship module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.relationship.Relationship(*, state, data)

Bases: object

Represents a relationship in Discord.

A relationship is like a friendship, a person who is blocked, etc. Only non-bot accounts can have relationships.

user

User – The user you have the relationship with.

type

RelationshipType – The type of relationship you have.

type
user
coroutine accept()

This function is a coroutine.

Accepts the relationship request. e.g. accepting a friend request.

Raises

HTTPException – Accepting the relationship failed.

coroutine delete()

This function is a coroutine.

Deletes the relationship.

Raises

HTTPException – Deleting the relationship failed.

discord.role module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.role.Role(*, guild, state, data)

Bases: discord.mixins.Hashable

Represents a Discord role in a Guild.

x == y

Checks if two roles are equal.

x != y

Checks if two roles are not equal.

x > y

Checks if a role is higher than another in the hierarchy.

x < y

Checks if a role is lower than another in the hierarchy.

x >= y

Checks if a role is higher or equal to another in the hierarchy.

x <= y

Checks if a role is lower or equal to another in the hierarchy.

hash(x)

Return the role’s hash.

str(x)

Returns the role’s name.

id

int – The ID for the role.

name

str – The name of the role.

permissions

Permissions – Represents the role’s permissions.

guild

Guild – The guild the role belongs to.

colour

Colour – Represents the role colour. An alias exists under color.

hoist

bool – Indicates if the role will be displayed separately from other members.

position

int – The position of the role. This number is usually positive. The bottom role has a position of 0.

managed

bool – Indicates if the role is managed by the guild through some form of integrations such as Twitch.

mentionable

bool – Indicates if the role can be mentioned by users.

guild
id
is_default()

Checks if the role is the default role.

created_at

Returns the role’s creation time in UTC.

mention

Returns a string that allows you to mention a role.

members

Returns a list of Member with this role.

position
colour
color
coroutine delete(*, reason=None)

This function is a coroutine.

Deletes the role.

You must have the manage_roles permission to use this.

Parameters

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

Raises
  • Forbidden – You do not have permissions to delete the role.

  • HTTPException – Deleting the role failed.

coroutine edit(*, reason=None, **fields)

This function is a coroutine.

Edits the role.

You must have the manage_roles permission to use this.

All fields are optional.

Parameters
  • name (str) – The new role name to change to.

  • permissions (Permissions) – The new permissions to change to.

  • colour (Colour) – The new colour to change to. (aliased to color as well)

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

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

  • position (int) – The new role’s position. This must be below your top role’s position or it will fail.

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

Raises
  • Forbidden – You do not have permissions to change the role.

  • HTTPException – Editing the role failed.

  • InvalidArgument – An invalid position was given or the default role was asked to be moved.

hoist
managed
mentionable
name
permissions

discord.shard module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.shard.Shard(ws, client)

Bases: object

id
is_pending()
complete_pending_reads()
launch_pending_reads()
wait()
get_future()
coroutine poll()
class discord.shard.AutoShardedClient(*args, loop=None, **kwargs)

Bases: discord.client.Client

A client similar to Client except it handles the complications of sharding for the user into a more manageable and transparent single process bot.

When using this client, you will be able to use it as-if it was a regular Client with a single shard when implementation wise internally it is split up into multiple shards. This allows you to not have to deal with IPC or other complicated infrastructure.

It is recommended to use this client only if you have surpassed at least 1000 guilds.

If no shard_count is provided, then the library will use the Bot Gateway endpoint call to figure out how many shards to use.

If a shard_ids parameter is given, then those shard IDs will be used to launch the internal shards. Note that shard_count must be provided if this is used. By default, when omitted, the client will launch shards from 0 to shard_count - 1.

shard_ids

Optional[List[int]] – An optional list of shard_ids to launch the shards with.

latency

float – Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

This operates similarly to Client.latency() except it uses the average latency of every shard’s latency. To get a list of shard latency, check the latencies property. Returns nan if there are no shards ready.

latencies

List[Tuple[int, float]] – A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

This returns a list of tuples with elements (shard_id, latency).

coroutine change_presence(*, activity=None, status=None, afk=False, shard_id=None)

This function is a coroutine.

Changes the client’s presence.

The activity parameter is a Activity object (not a string) that represents the activity being done currently. This could also be the slimmed down versions, Game and Streaming.

Example:

game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
Parameters
  • activity (Optional[Union[Game, Streaming, Activity]]) – The activity being done. None if no currently active activity is done.

  • status (Optional[Status]) – Indicates what status to change to. If None, then Status.online is used.

  • afk (bool) – Indicates if you are going AFK. This allows the discord client to know how to handle push notifications better for you in case you are actually idle and not lying.

  • shard_id (Optional[int]) – The shard_id to change the presence to. If not specified or None, then it will change the presence of every shard the bot can see.

Raises

InvalidArgument – If the activity parameter is not of proper type.

coroutine close()

This function is a coroutine.

Closes the connection to discord.

coroutine launch_shard(gateway, shard_id)
coroutine launch_shards()
coroutine request_offline_members(*guilds)

This function is a coroutine.

Requests previously offline members from the guild to be filled up into the Guild.members cache. This function is usually not called. It should only be used if you have the fetch_offline_members parameter set to False.

When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if Guild.large is True.

Parameters

*guilds (Guild) – An argument list of guilds to request offline members for.

Raises

InvalidArgument – If any guild is unavailable or not large in the collection.

discord.state module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.state.ListenerType

Bases: enum.Enum

An enumeration.

chunk = 0
class discord.state.Listener(type, future, predicate)

Bases: tuple

future

Alias for field number 1

predicate

Alias for field number 2

type

Alias for field number 0

class discord.state.ReadyState(launch, guilds)

Bases: tuple

guilds

Alias for field number 1

launch

Alias for field number 0

class discord.state.ConnectionState(*, dispatch, chunker, handlers, syncer, http, loop, **options)

Bases: object

clear()
process_listeners(listener_type, argument, result)
call_handlers(key, *args, **kwargs)
self_id
voice_clients
store_user(data)
get_user(id)
store_emoji(guild, data)
emojis
get_emoji(emoji_id)
private_channels
add_dm_channel(data)
chunks_needed(guild)
guilds
parse_ready(data)
parse_resumed(data)
parse_message_create(data)
parse_message_delete(data)
parse_message_delete_bulk(data)
parse_message_update(data)
parse_message_reaction_add(data)
parse_message_reaction_remove_all(data)
parse_message_reaction_remove(data)
parse_presence_update(data)
parse_user_update(data)
parse_channel_delete(data)
parse_channel_update(data)
parse_channel_create(data)
parse_channel_pins_update(data)
parse_channel_recipient_add(data)
parse_channel_recipient_remove(data)
parse_guild_member_add(data)
parse_guild_member_remove(data)
parse_guild_member_update(data)
parse_guild_emojis_update(data)
parse_guild_create(data)
parse_guild_sync(data)
parse_guild_update(data)
parse_guild_delete(data)
parse_guild_ban_add(data)
parse_guild_ban_remove(data)
parse_guild_role_create(data)
parse_guild_role_delete(data)
parse_guild_role_update(data)
parse_guild_members_chunk(data)
parse_guild_integrations_update(data)
parse_webhooks_update(data)
parse_voice_state_update(data)
parse_voice_server_update(data)
parse_typing_start(data)
parse_relationship_add(data)
parse_relationship_remove(data)
get_reaction_emoji(data)
get_channel(id)
create_message(*, channel, data)
receive_chunk(guild_id)
coroutine request_offline_members(guilds)
class discord.state.AutoShardedConnectionState(*args, **kwargs)

Bases: discord.state.ConnectionState

coroutine request_offline_members(guilds, *, shard_id)
parse_ready(data)

discord.user module

The MIT License (MIT)

Copyright (c) 2015-2017 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.user.Profile

Bases: discord.user.Profile

nitro
premium
staff
partner
bug_hunter
early_supporter
hypesquad
hypesquad_houses
class discord.user.BaseUser(*, state, data)

Bases: discord.abc.User

avatar_url

Returns a friendly URL version of the avatar the user has.

If the user does not have a traditional avatar, their default avatar URL is returned instead.

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

is_avatar_animated()

bool: Returns True if the user has an animated avatar.

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

Returns a friendly URL version of the avatar the user has.

If the user does not have a traditional avatar, their default avatar URL is returned instead.

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

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

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

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

Raises

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

Returns

The resulting CDN asset.

Return type

Asset

default_avatar

Returns the default avatar for a given user. This is calculated by the user’s discriminator

default_avatar_url

Returns a URL for a user’s default avatar.

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 under color.

color

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

There is an alias for this under color.

mention

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

permissions_in(channel)

An alias for abc.GuildChannel.permissions_for().

Basically equivalent to:

channel.permissions_for(self)
Parameters

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

created_at

Returns the user’s creation time in UTC.

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

display_name

Returns the user’s display name.

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

mentioned_in(message)

Checks if the user is mentioned in the specified message.

Parameters

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

avatar
bot
discriminator
id
name
class discord.user.ClientUser(*, state, data)

Bases: discord.user.BaseUser

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.

name

str – The user’s username.

id

int – The user’s unique ID.

discriminator

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

avatar

Optional[str] – The avatar hash the user has. Could be None.

bot

bool – Specifies if the user is a bot account.

verified

bool – Specifies if the user is a verified account.

email

Optional[str] – The email the user used when registering.

locale

Optional[str] – The IETF language tag used to identify the user is using.

mfa_enabled

bool – Specifies if the user has MFA turned on and working.

premium

bool – Specifies if the user is a premium user (e.g. has Discord Nitro).

premium_type

PremiumType – Specifies the type of premium a user has (e.g. Nitro or Nitro Classic). Could be None if the user is not premium.

get_relationship(user_id)

Retrieves the Relationship if applicable.

Note

This only applies to non-bot accounts.

Parameters

user_id (int) – The user ID to check if we have a relationship with them.

Returns

The relationship if available or None

Return type

Optional[Relationship]

relationships

Returns a list of Relationship that the user has.

Note

This only applies to non-bot accounts.

friends

Returns a list of Users that the user is friends with.

Note

This only applies to non-bot accounts.

blocked

Returns a list of Users that the user has blocked.

Note

This only applies to non-bot accounts.

coroutine create_group(*recipients)

This function is a coroutine.

Creates a group direct message with the recipients provided. These recipients must be have a relationship of type RelationshipType.friend.

Note

This only applies to non-bot accounts.

Parameters

*recipients (User) – An argument list of User to have in your group.

Raises
  • HTTPException – Failed to create the group direct message.

  • ClientException – Attempted to create a group with only one recipient. This does not include yourself.

Returns

The new group channel.

Return type

GroupChannel

coroutine edit(**fields)

This function is a coroutine.

Edits the current profile of the client.

If a bot account is used then a password field is optional, otherwise it is required.

Note

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

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

Parameters
  • password (str) – The current password for the client’s account. Only applicable to user accounts.

  • new_password (str) – The new password you wish to change to. Only applicable to user accounts.

  • email (str) – The new email you wish to change to. Only applicable to user accounts.

  • house (Optional[HypeSquadHouse]) – The hypesquad house you wish to change to. Could be None to leave the current house. Only applicable to user accounts.

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

Raises
  • HTTPException – Editing your profile failed.

  • InvalidArgument – Wrong image format passed for avatar.

  • ClientException – Password is required for non-bot accounts. House field was not a HypeSquadHouse.

coroutine edit_settings(**kwargs)

This function is a coroutine.

Edits the client user’s settings.

Note

This only applies to non-bot accounts.

Parameters
  • afk_timeout (int) – How long (in seconds) the user needs to be AFK until Discord sends push notifications to your mobile device.

  • animate_emojis (bool) – Whether or not to animate emojis in the chat.

  • convert_emoticons (bool) – Whether or not to automatically convert emoticons into emojis. e.g. :-) -> 😃

  • default_guilds_restricted (bool) – Whether or not to automatically disable DMs between you and members of new guilds you join.

  • detect_platform_accounts (bool) – Whether or not to automatically detect accounts from services like Steam and Blizzard when you open the Discord client.

  • developer_mode (bool) – Whether or not to enable developer mode.

  • disable_games_tab (bool) – Whether or not to disable the showing of the Games tab.

  • enable_tts_command (bool) – Whether or not to allow tts messages to be played/sent.

  • explicit_content_filter (UserContentFilter) – The filter for explicit content in all messages.

  • friend_source_flags (FriendFlags) – Who can add you as a friend.

  • gif_auto_play (bool) – Whether or not to automatically play gifs that are in the chat.

  • guild_positions (List[abc.Snowflake]) – A list of guilds in order of the guild/guild icons that are on the left hand side of the UI.

  • inline_attachment_media (bool) – Whether or not to display attachments when they are uploaded in chat.

  • inline_embed_media (bool) – Whether or not to display videos and images from links posted in chat.

  • locale (str) – The RFC 3066 language identifier of the locale to use for the language of the Discord client.

  • message_display_compact (bool) – Whether or not to use the compact Discord display mode.

  • render_embeds (bool) – Whether or not to render embeds that are sent in the chat.

  • render_reactions (bool) – Whether or not to render reactions that are added to messages.

  • restricted_guilds (List[abc.Snowflake]) – A list of guilds that you will not receive DMs from.

  • show_current_game (bool) – Whether or not to display the game that you are currently playing.

  • status (Status) – The clients status that is shown to others.

  • theme (Theme) – The theme of the Discord UI.

  • timezone_offset (int) – The timezone offset to use.

Raises
  • HTTPException – Editing the settings failed.

  • Forbidden – The client is a bot user and not a user account.

Returns

The client user’s updated settings.

Return type

dict

email
locale
mfa_enabled
premium
premium_type
verified
class discord.user.User(*, state, data)

Bases: discord.user.BaseUser, discord.abc.Messageable

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.

name

str – The user’s username.

id

int – The user’s unique ID.

discriminator

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

avatar

Optional[str] – The avatar hash the user has. Could be None.

bot

bool – Specifies if the user is a bot account.

dm_channel

Returns the DMChannel associated with this user if it exists.

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

relationship

Returns the Relationship with this user if applicable, None otherwise.

Note

This only applies to non-bot accounts.

coroutine block()

This function is a coroutine.

Blocks the user.

Note

This only applies to non-bot accounts.

Raises
  • Forbidden – Not allowed to block this user.

  • HTTPException – Blocking the user failed.

coroutine create_dm()

Creates a DMChannel with this user.

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

coroutine mutual_friends()

This function is a coroutine.

Gets all mutual friends of this user.

Note

This only applies to non-bot accounts.

Raises
  • Forbidden – Not allowed to get mutual friends of this user.

  • HTTPException – Getting mutual friends failed.

Returns

The users that are mutual friends.

Return type

List[User]

coroutine profile()

This function is a coroutine.

Gets the user’s profile.

Note

This only applies to non-bot accounts.

Raises
  • Forbidden – Not allowed to fetch profiles.

  • HTTPException – Fetching the profile failed.

Returns

The profile of the user.

Return type

Profile

coroutine remove_friend()

This function is a coroutine.

Removes the user as a friend.

Note

This only applies to non-bot accounts.

Raises
  • Forbidden – Not allowed to remove this user as a friend.

  • HTTPException – Removing the user as a friend failed.

coroutine send_friend_request()

This function is a coroutine.

Sends the user a friend request.

Note

This only applies to non-bot accounts.

Raises
  • Forbidden – Not allowed to send a friend request to the user.

  • HTTPException – Sending the friend request failed.

coroutine unblock()

This function is a coroutine.

Unblocks the user.

Note

This only applies to non-bot accounts.

Raises
  • Forbidden – Not allowed to unblock this user.

  • HTTPException – Unblocking the user failed.

is_friend()

bool: Checks if the user is your friend.

Note

This only applies to non-bot accounts.

is_blocked()

bool: Checks if the user is blocked.

Note

This only applies to non-bot accounts.

discord.utils module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.utils.cached_property(function)

Bases: object

class discord.utils.CachedSlotProperty(name, function)

Bases: object

discord.utils.cached_slot_property(name)
class discord.utils.SequenceProxy(proxied)

Bases: collections.abc.Sequence

Read-only proxy of a Sequence.

index(value[, start[, stop]]) → integer -- return first index of value.

Raises ValueError if the value is not present.

count(value) → integer -- return number of occurrences of value
discord.utils.parse_time(timestamp)
discord.utils.deprecated(instead=None)
discord.utils.oauth_url(client_id, permissions=None, guild=None, redirect_uri=None)

A helper function that returns the OAuth2 URL for inviting the bot into guilds.

Parameters
  • client_id (str) – The client ID for your bot.

  • permissions (Permissions) – The permissions you’re requesting. If not given then you won’t be requesting any permissions.

  • guild (Guild) – The guild to pre-select in the authorization screen, if available.

  • redirect_uri (str) – An optional valid redirect URI.

discord.utils.snowflake_time(id)

Returns the creation date in UTC of a discord id.

discord.utils.time_snowflake(datetime_obj, high=False)

Returns a numeric snowflake pretending to be created at the given date.

When using as the lower end of a range, use time_snowflake(high=False) - 1 to be inclusive, high=True to be exclusive When using as the higher end of a range, use time_snowflake(high=True) + 1 to be inclusive, high=False to be exclusive

Parameters
  • datetime_obj – A timezone-naive datetime object representing UTC time.

  • high (bool) – Whether or not to set the lower 22 bit to high or low.

discord.utils.find(predicate, seq)

A helper to return the first element found in the sequence that meets the predicate. For example:

member = find(lambda m: m.name == 'Mighty', channel.guild.members)

would find the first Member whose name is ‘Mighty’ and return it. If an entry is not found, then None is returned.

This is different from filter due to the fact it stops the moment it finds a valid entry.

Parameters
  • predicate – A function that returns a boolean-like result.

  • seq (iterable) – The iterable to search through.

discord.utils.get(iterable, **attrs)

A helper that returns the first element in the iterable that meets all the traits passed in attrs. This is an alternative for discord.utils.find().

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by x.y) then pass in x__y as the keyword argument.

If nothing is found that matches the attributes passed, then None is returned.

Examples

Basic usage:

member = discord.utils.get(message.guild.members, name='Foo')

Multiple attribute matching:

channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)

Nested attribute matching:

channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')
Parameters
  • iterable – An iterable to search through.

  • **attrs – Keyword arguments that denote attributes to search with.

discord.utils.to_json(obj)
discord.utils.valid_icon_size(size)

Icons must be power of 2 within [16, 4096].

class discord.utils.SnowflakeList

Bases: array.array

Internal data storage class to efficiently store a list of snowflakes.

This should have the following characteristics:

  • Low memory usage

  • O(n) iteration (obviously)

  • O(n log n) initial creation if data is unsorted

  • O(log n) search and indexing

  • O(n) insertion

add(element)
get(element)
has(element)
discord.utils.resolve_invite(invite)

Resolves an invite from a Invite, URL or ID

Parameters

invite (Union[Invite, Object, str]) – The invite.

Returns

The invite code.

Return type

str

discord.utils.escape_markdown(text, *, as_needed=False, ignore_links=True)

A helper function that escapes Discord’s markdown.

Parameters
  • text (str) – The text to escape markdown from.

  • as_needed (bool) – Whether to escape the markdown characters as needed. This means that it does not escape extraneous characters if it’s not necessary, e.g. **hello** is escaped into \*\*hello** instead of \*\*hello\*\*. Note however that this can open you up to some clever syntax abuse. Defaults to False.

  • ignore_links (bool) – Whether to leave links alone when escaping markdown. For example, if a URL in the text contains characters such as _ then it will be left alone. This option is not supported with as_needed. Defaults to True.

Returns

The text with the markdown special characters escaped with a slash.

Return type

str

discord.utils.escape_mentions(text)

A helper function that escapes everyone, here, role, and user mentions.

Note

This does not include channel mentions.

Parameters

text (str) – The text to escape mentions from.

Returns

The text with the mentions removed.

Return type

str

coroutine discord.utils.async_all(gen, *, check=<function isawaitable>)
coroutine discord.utils.maybe_coroutine(f, *args, **kwargs)
coroutine discord.utils.sane_wait_for(futures, *, timeout, loop)

discord.voice_client module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.voice_client.VoiceClient(state, timeout, channel)

Bases: object

Represents a Discord voice connection.

You do not create these, you typically get them from e.g. VoiceChannel.connect().

Warning

In order to play audio, you must have loaded the opus library through opus.load_opus().

If you don’t do this then the library will not be able to transmit audio.

session_id

str – The voice connection session ID.

token

str – The voice connection token.

endpoint

str – The endpoint we are connecting to.

channel

abc.Connectable – The voice channel connected to.

loop

The event loop that the voice client is running on.

warn_nacl = True
supported_modes = ('xsalsa20_poly1305_suffix', 'xsalsa20_poly1305')
guild

Optional[Guild] – The guild we’re connected to, if applicable.

user

ClientUser – The user connected to voice (i.e. ourselves).

checked_add(attr, value, limit)
is_connected()

bool: Indicates if the voice client is connected to voice.

play(source, *, after=None)

Plays an AudioSource.

The finalizer, after is called after the source has been exhausted or an error occurred.

If an error happens while the audio player is running, the exception is caught and the audio player is then stopped.

Parameters
  • source (AudioSource) – The audio source we’re reading from.

  • after – The finalizer that is called after the stream is exhausted. All exceptions it throws are silently discarded. This function must have a single parameter, error, that denotes an optional exception that was raised during playing.

Raises
  • ClientException – Already playing audio or not connected.

  • TypeError – source is not a AudioSource or after is not a callable.

is_playing()

Indicates if we’re currently playing audio.

is_paused()

Indicates if we’re playing audio, but if we’re paused.

coroutine connect(*, reconnect=True, _tries=0, do_handshake=True)
coroutine disconnect(*, force=False)

This function is a coroutine.

Disconnects this voice client from voice.

coroutine move_to(channel)

This function is a coroutine.

Moves you to a different voice channel.

Parameters

channel (abc.Snowflake) – The channel to move to. Must be a voice channel.

coroutine poll_voice_ws(reconnect)
coroutine start_handshake()
stop()

Stops playing audio.

coroutine terminate_handshake(*, remove=False)
pause()

Pauses the audio playing.

resume()

Resumes the audio playing.

source

Optional[AudioSource] – The audio source being played, if playing.

This property can also be used to change the audio source currently being played.

send_audio_packet(data, *, encode=True)

Sends an audio packet composed of the data.

You must be connected to play audio.

Parameters
  • data (bytes) – The bytes-like object denoting PCM or Opus voice data.

  • encode (bool) – Indicates if data should be encoded into Opus.

Raises
  • ClientException – You are not connected.

  • OpusError – Encoding the data failed.

discord.webhook module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.webhook.WebhookAdapter

Bases: object

Base class for all webhook adapters.

webhook

Webhook – The webhook that owns this adapter.

BASE = 'https://discordapp.com/api/v7'
request(verb, url, payload=None, multipart=None)

Actually does the request.

Subclasses must implement this.

Parameters
  • verb (str) – The HTTP verb to use for the request.

  • url (str) – The URL to send the request to. This will have the query parameters already added to it, if any.

  • multipart (Optional[dict]) – A dict containing multipart form data to send with the request. If a filename is being uploaded, then it will be under a file key which will have a 3-element tuple denoting (filename, file, content_type).

  • payload (Optional[dict]) – The JSON to send with the request, if any.

delete_webhook()
edit_webhook(**payload)
handle_execution_response(data, *, wait)

Transforms the webhook execution response into something more meaningful.

This is mainly used to convert the data into a Message if necessary.

Subclasses must implement this.

Parameters
  • data – The data that was returned from the request.

  • wait (bool) – Whether the webhook execution was asked to wait or not.

execute_webhook(*, payload, wait=False, file=None, files=None)
class discord.webhook.AsyncWebhookAdapter(session)

Bases: discord.webhook.WebhookAdapter

A webhook adapter suited for use with aiohttp.

Note

You are responsible for cleaning up the client session.

Parameters

session (aiohttp.ClientSession) – The session to use to send requests.

coroutine handle_execution_response(response, *, wait)

Transforms the webhook execution response into something more meaningful.

This is mainly used to convert the data into a Message if necessary.

Subclasses must implement this.

Parameters
  • data – The data that was returned from the request.

  • wait (bool) – Whether the webhook execution was asked to wait or not.

coroutine request(verb, url, payload=None, multipart=None, *, files=None)

Actually does the request.

Subclasses must implement this.

Parameters
  • verb (str) – The HTTP verb to use for the request.

  • url (str) – The URL to send the request to. This will have the query parameters already added to it, if any.

  • multipart (Optional[dict]) – A dict containing multipart form data to send with the request. If a filename is being uploaded, then it will be under a file key which will have a 3-element tuple denoting (filename, file, content_type).

  • payload (Optional[dict]) – The JSON to send with the request, if any.

class discord.webhook.RequestsWebhookAdapter(session=None, *, sleep=True)

Bases: discord.webhook.WebhookAdapter

A webhook adapter suited for use with requests.

Only versions of requests higher than 2.13.0 are supported.

Parameters
  • session (Optional[requests.Session]) – The requests session to use for sending requests. If not given then each request will create a new session. Note if a session is given, the webhook adapter will not clean it up for you. You must close the session yourself.

  • sleep (bool) – Whether to sleep the thread when encountering a 429 or pre-emptive rate limit or a 5xx status code. Defaults to True. If set to False then this will raise an HTTPException instead.

request(verb, url, payload=None, multipart=None, *, files=None)

Actually does the request.

Subclasses must implement this.

Parameters
  • verb (str) – The HTTP verb to use for the request.

  • url (str) – The URL to send the request to. This will have the query parameters already added to it, if any.

  • multipart (Optional[dict]) – A dict containing multipart form data to send with the request. If a filename is being uploaded, then it will be under a file key which will have a 3-element tuple denoting (filename, file, content_type).

  • payload (Optional[dict]) – The JSON to send with the request, if any.

handle_execution_response(response, *, wait)

Transforms the webhook execution response into something more meaningful.

This is mainly used to convert the data into a Message if necessary.

Subclasses must implement this.

Parameters
  • data – The data that was returned from the request.

  • wait (bool) – Whether the webhook execution was asked to wait or not.

class discord.webhook.Webhook(data, *, adapter, state=None)

Bases: object

Represents a Discord webhook.

Webhooks are a form to send messages to channels in Discord without a bot user or authentication.

There are two main ways to use Webhooks. The first is through the ones received by the library such as Guild.webhooks() and TextChannel.webhooks(). The ones received by the library will automatically have an adapter bound using the library’s HTTP session. Those webhooks will have send(), delete() and edit() as coroutines.

The second form involves creating a webhook object manually without having it bound to a websocket connection using the from_url() or partial() classmethods. This form allows finer grained control over how requests are done, allowing you to mix async and sync code using either aiohttp or requests.

For example, creating a webhook from a URL and using aiohttp:

from discord import Webhook, AsyncWebhookAdapter
import aiohttp

async def foo():
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('url-here', adapter=AsyncWebhookAdapter(session))
        await webhook.send('Hello World', username='Foo')

Or creating a webhook from an ID and token and using requests:

import requests
from discord import Webhook, RequestsWebhookAdapter

webhook = Webhook.partial(123456, 'abcdefg', adapter=RequestsWebhookAdapter())
webhook.send('Hello World', username='Foo')
id

int – The webhook’s ID

token

str – The authentication token of the webhook.

guild_id

Optional[int] – The guild ID this webhook is for.

channel_id

Optional[int] – The channel ID this webhook is for.

user

Optional[abc.User] – The user this webhook was created by. If the webhook was received without authentication then this will be None.

name

Optional[str] – The default name of the webhook.

avatar

Optional[str] – The default avatar of the webhook.

id
channel_id
guild_id
name
avatar
token
user
url

Returns the webhook’s url.

classmethod partial(id, token, *, adapter)

Creates a partial Webhook.

A partial webhook is just a webhook object with an ID and a token.

Parameters
classmethod from_url(url, *, adapter)

Creates a partial Webhook from a webhook URL.

Parameters
Raises

InvalidArgument – The URL is invalid.

classmethod from_state(data, state)
guild

Optional[Guild] – The guild this webhook belongs to.

If this is a partial webhook, then this will always return None.

channel

Optional[TextChannel] – The text channel this webhook belongs to.

If this is a partial webhook, then this will always return None.

created_at

Returns the webhook’s creation time in UTC.

avatar_url

Returns a friendly URL version of the avatar the webhook has.

If the webhook does not have a traditional avatar, their default avatar URL is returned instead.

This is equivalent to calling avatar_url_as() with the default parameters.

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

Returns a friendly URL version of the avatar the webhook has.

If the webhook does not have a traditional avatar, their default avatar URL is returned instead.

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

Parameters
  • format (Optional[str]) – The format to attempt to convert the avatar to. If the format is None, then it is equivalent to png.

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

Raises

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

Returns

The resulting CDN asset.

Return type

Asset

delete()

This function could be a coroutine.

Deletes this Webhook.

If the webhook is constructed with a RequestsWebhookAdapter then this is not a coroutine.

Raises
  • HTTPException – Deleting the webhook failed.

  • NotFound – This webhook does not exist.

  • Forbidden – You do not have permissions to delete this webhook.

edit(**kwargs)

This function could be a coroutine.

Edits this Webhook.

If the webhook is constructed with a RequestsWebhookAdapter then this is not a coroutine.

Parameters
  • name (Optional[str]) – The webhook’s new default name.

  • avatar (Optional[bytes]) – A bytes-like object representing the webhook’s new default avatar.

Raises
  • HTTPException – Editing the webhook failed.

  • NotFound – This webhook does not exist.

  • Forbidden – You do not have permissions to edit this webhook.

send(content=None, *, wait=False, username=None, avatar_url=None, tts=False, file=None, files=None, embed=None, embeds=None)

This function could be a coroutine.

Sends a message using the webhook.

If the webhook is constructed with a RequestsWebhookAdapter then this is not a coroutine.

The content must be a type that can convert to a string through str(content).

To upload a single file, the file parameter should be used with a single File object.

If the embed parameter is provided, it must be of type Embed and it must be a rich embed type. You cannot mix the embed parameter with the embeds parameter, which must be a list of Embed objects to send.

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

  • wait (bool) – Whether the server should wait before sending a response. This essentially means that the return type of this function changes from None to a Message if set to True.

  • username (str) – The username to send with this message. If no username is provided then the default username for the webhook is used.

  • avatar_url (Union[str, Asset]) – The avatar URL to send with this message. If no avatar URL is provided then the default avatar for the webhook is used.

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

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

  • embed (Embed) – The rich embed for the content to send. This cannot be mixed with embeds parameter.

  • embeds (List[Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the embed parameter.

Raises
  • HTTPException – Sending the message failed.

  • NotFound – This webhook was not found.

  • Forbidden – The authorization token for the webhook is incorrect.

  • InvalidArgument – You specified both embed and embeds or the length of embeds was invalid.

Returns

The message that was sent.

Return type

Optional[Message]

execute(*args, **kwargs)

An alias for send().

discord.widget module

The MIT License (MIT)

Copyright (c) 2015-2019 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class discord.widget.WidgetChannel

Bases: discord.widget.WidgetChannel

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

int – The channel’s ID.

name

str – The channel’s name.

position

int – The channel’s position

mention

str – The string that allows you to mention the channel.

created_at

Returns the channel’s creation time in UTC.

class discord.widget.WidgetMember(*, state, data, connected_channel=None)

Bases: discord.user.BaseUser

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

int – The member’s ID.

name

str – The member’s username.

discriminator

str – The member’s discriminator.

bot

bool – Whether the member is a bot.

status

Status – The member’s status.

nick

Optional[str] – The member’s nickname.

avatar

Optional[str] – The member’s avatar hash.

activity

Optional[Union[Activity, Game, Streaming, Spotify]] – The member’s activity.

deafened

Optional[bool] – Whether the member is currently deafened.

muted

Optional[bool] – Whether the member is currently muted.

suppress

Optional[bool] – Whether the member is currently being suppressed.

connected_channel

Optional[VoiceChannel] – Which channel the member is connected to.

nick
status
deafened
muted
suppress
activity
connected_channel
display_name

str – Returns the member’s display name.

avatar
bot
discriminator
id
name
class discord.widget.Widget(*, state, data)

Bases: object

Represents a Guild widget.

x == y

Checks if two widgets are the same.

x != y

Checks if two widgets are not the same.

str(x)

Returns the widget’s JSON URL.

id

int – The guild’s ID.

name

str – The guild’s name.

channels

Optional[List[WidgetChannel]] – The accessible voice channels in the guild.

members

Optional[List[Member]] – The online members in the server. Offline members do not appear in the widget.

name
id
channels
members
created_at

datetime.datetime – Returns the member’s creation time in UTC.

json_url

str – The JSON URL of the widget.

invite_url

Optiona[str] – The invite URL for the guild, if available.

coroutine fetch_invite(*, with_counts=True)

This function is a coroutine.

Retrieves an Invite from a invite URL or ID. This is the same as Client.get_invite(); the invite code is abstracted away.

Parameters

with_counts (bool) – Whether to include count information in the invite. This fills the Invite.approximate_member_count and Invite.approximate_presence_count fields.

Returns

The invite from the URL/ID.

Return type

Invite

Module contents

Discord API Wrapper

A basic wrapper for the Discord API.

copyright
  1. 2015-2019 Rapptz

license

MIT, see LICENSE for more details.

class discord.VersionInfo(major, minor, micro, releaselevel, serial)

Bases: tuple

major

Alias for field number 0

micro

Alias for field number 2

minor

Alias for field number 1

releaselevel

Alias for field number 3

serial

Alias for field number 4