API Reference

The following section outlines the API of discord.py.

Note

This module uses the Python logging module to log diagnostic and errors in an output independent way. If the logging module is not configured, these logs will not be output anywhere. See Setting Up Logging for more information on how to set up and use the logging module with discord.py.

Client

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

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[event loop]) – The event loop 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

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.

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.

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, ClientException is raised.

Example

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

This function is a coroutine.

Retrieve’s the bot’s application information.

Returns

A namedtuple representing the application info.

Return type

AppInfo

Raises

HTTPException – Retrieving the information failed somehow.

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
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 – 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 get_invite(url)

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 Object with the names patched in.

Parameters

url (str) – The discord invite ID or URL (must be a discord.gg URL).

Raises
Returns

The invite from the URL/ID.

Return type

Invite

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

Parameters

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

Returns

The user you requested.

Return type

User

Raises
coroutine get_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
Returns

The profile of the user.

Return type

Profile

coroutine get_webhook_info(webhook_id)

This function is a coroutine.

Retrieves a Webhook with the specified ID.

Raises
Returns

The webhook you requested.

Return type

Webhook

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.

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

class discord.AutoShardedClient(*args, loop=None, **kwargs)

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 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 – An argument list of guilds to request offline members for.

Raises

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

Voice

class discord.VoiceClient(state, timeout, channel)

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.

guild

Optional[Guild] – The guild we’re connected to, if applicable.

user

ClientUser – The user connected to voice (i.e. ourselves).

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
is_playing()

Indicates if we’re currently playing audio.

is_paused()

Indicates if we’re playing audio, but if we’re paused.

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.

stop()

Stops playing audio.

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.

class discord.AudioSource

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.PCMAudio(stream)

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.FFmpegPCMAudio(source, *, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None)

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.PCMVolumeTransformer(original, volume=1.0)

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

Opus Library

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.

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

Event Reference

This page outlines the different types of events listened by Client.

There are two ways to register an event, the first way is through the use of Client.event(). The second way is through subclassing Client and overriding the specific events. For example:

import discord

class MyClient(discord.Client):
    async def on_message(self, message):
        if message.author != self.user:
            return

        if message.content.startswith('$hello'):
            await message.channel.send('Hello World!')

If an event handler raises an exception, on_error() will be called to handle it, which defaults to print a traceback and ignoring the exception.

Warning

All the events must be a coroutine. If they aren’t, then you might get unexpected errors. In order to turn a function into a coroutine they must be async def functions.

discord.on_connect()

Called when the client has successfully connected to Discord. This is not the same as the client being fully prepared, see on_ready() for that.

The warnings on on_ready() also apply.

discord.on_ready()

Called when the client is done preparing the data received from Discord. Usually after login is successful and the Client.guilds and co. are filled up.

Warning

This function is not guaranteed to be the first event called. Likewise, this function is not guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.

discord.on_shard_ready(shard_id)

Similar to on_ready() except used by AutoShardedClient to denote when a particular shard ID has become ready.

Parameters

shard_id – The shard ID that is ready.

discord.on_resumed()

Called when the client has resumed a session.

discord.on_error(event, *args, **kwargs)

Usually when an event raises an uncaught exception, a traceback is printed to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will supress the default action of printing the traceback.

The information of the exception rasied and the exception itself can be retreived with a standard call to sys.exc_info().

If you want exception to propogate out of the Client class you can define an on_error handler consisting of a single empty raise statement. Exceptions raised by on_error will not be handled in any way by Client.

Parameters
  • event – The name of the event that raised the exception.

  • args – The positional arguments for the event that raised the exception.

  • kwargs – The keyword arguments for the event that raised the execption.

discord.on_socket_raw_receive(msg)

Called whenever a message is received from the WebSocket, before it’s processed. This event is always dispatched when a message is received and the passed data is not processed in any way.

This is only really useful for grabbing the WebSocket stream and debugging purposes.

Note

This is only for the messages received from the client WebSocket. The voice WebSocket will not trigger this event.

Parameters

msg – The message passed in from the WebSocket library. Could be bytes for a binary message or str for a regular message.

discord.on_socket_raw_send(payload)

Called whenever a send operation is done on the WebSocket before the message is sent. The passed parameter is the message that is being sent to the WebSocket.

This is only really useful for grabbing the WebSocket stream and debugging purposes.

Note

This is only for the messages received from the client WebSocket. The voice WebSocket will not trigger this event.

Parameters

payload – The message that is about to be passed on to the WebSocket library. It can be bytes to denote a binary message or str to denote a regular text message.

discord.on_typing(channel, user, when)

Called when someone begins typing a message.

The channel parameter can be a abc.Messageable instance. Which could either be TextChannel, GroupChannel, or DMChannel.

If the channel is a TextChannel then the user parameter is a Member, otherwise it is a User.

Parameters
  • channel – The location where the typing originated from.

  • user – The user that started typing.

  • when – A datetime.datetime object representing when typing started.

discord.on_message(message)

Called when a Message is created and sent.

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that Bot does not have this problem.

Parameters

message – A Message of the current message.

discord.on_message_delete(message)

Called when a message is deleted. If the message is not found in the Client.messages cache, then these events will not be called. This happens if the message is too old or the client is participating in high traffic guilds. To fix this, increase the max_messages option of Client.

Parameters

message – A Message of the deleted message.

discord.on_raw_message_delete(payload)

Called when a message is deleted. Unlike on_message_delete(), this is called regardless of the message being in the internal message cache or not.

Parameters

payload (RawMessageDeleteEvent) – The raw event payload data.

discord.on_raw_bulk_message_delete(payload)

Called when a bulk delete is triggered. This event is called regardless of the message IDs being in the internal message cache or not.

Parameters

payload (RawBulkMessageDeleteEvent) – The raw event payload data.

discord.on_message_edit(before, after)

Called when a Message receives an update event. If the message is not found in the Client.messages cache, then these events will not be called. This happens if the message is too old or the client is participating in high traffic guilds. To fix this, increase the max_messages option of Client.

The following non-exhaustive cases trigger this event:

  • A message has been pinned or unpinned.

  • The message content has been changed.

  • The message has received an embed.

    • For performance reasons, the embed server does not do this in a “consistent” manner.

  • A call message has received an update to its participants or ending time.

Parameters
  • before – A Message of the previous version of the message.

  • after – A Message of the current version of the message.

discord.on_raw_message_edit(payload)

Called when a message is edited. Unlike on_message_edit(), this is called regardless of the state of the internal message cache.

Due to the inherently raw nature of this event, the data parameter coincides with the raw data given by the gateway

Since the data payload can be partial, care must be taken when accessing stuff in the dictionary. One example of a common case of partial data is when the 'content' key is inaccessible. This denotes an “embed” only edit, which is an edit in which only the embeds are updated by the Discord embed server.

Parameters

payload (RawMessageUpdateEvent) – The raw event payload data.

discord.on_reaction_add(reaction, user)

Called when a message has a reaction added to it. Similar to on_message_edit, if the message is not found in the Client.messages cache, then this event will not be called.

Note

To get the Message being reacted, access it via Reaction.message.

Parameters
  • reaction – A Reaction showing the current state of the reaction.

  • user – A User or Member of the user who added the reaction.

discord.on_raw_reaction_add(payload)

Called when a message has a reaction added. Unlike on_reaction_add(), this is called regardless of the state of the internal message cache.

Parameters

payload (RawReactionActionEvent) – The raw event payload data.

discord.on_reaction_remove(reaction, user)

Called when a message has a reaction removed from it. Similar to on_message_edit, if the message is not found in the Client.messages cache, then this event will not be called.

Note

To get the message being reacted, access it via Reaction.message.

Parameters
  • reaction – A Reaction showing the current state of the reaction.

  • user – A User or Member of the user who removed the reaction.

discord.on_raw_reaction_remove(payload)

Called when a reaction has a reaction removed. Unlike on_reaction_remove(), this is called regardless of the state of the internal message cache.

Parameters

payload (RawReactionActionEvent) – The raw event payload data.

discord.on_reaction_clear(message, reactions)

Called when a message has all its reactions removed from it. Similar to on_message_edit(), if the message is not found in the Client.messages cache, then this event will not be called.

Parameters
  • message – The Message that had its reactions cleared.

  • reactions – A list of Reactions that were removed.

discord.on_raw_reaction_clear(payload)

Called when a message has all its reactions removed. Unlike on_reaction_clear(), this is called regardless of the state of the internal message cache.

Parameters

payload (RawReactionClearEvent) – The raw event payload data.

discord.on_private_channel_delete(channel)
discord.on_private_channel_create(channel)

Called whenever a private channel is deleted or created.

Parameters

channel – The abc.PrivateChannel that got created or deleted.

discord.on_private_channel_update(before, after)

Called whenever a private group DM is updated. e.g. changed name or topic.

Parameters
  • before – The GroupChannel that got updated with the old info.

  • after – The GroupChannel that got updated with the updated info.

discord.on_private_channel_pins_update(channel, last_pin)

Called whenever a message is pinned or unpinned from a private channel.

Parameters
  • channel – The abc.PrivateChannel that had it’s pins updated.

  • last_pin – A datetime.datetime object representing when the latest message was pinned or None if there are no pins.

discord.on_guild_channel_delete(channel)
discord.on_guild_channel_create(channel)

Called whenever a guild channel is deleted or created.

Note that you can get the guild from guild.

Parameters

channel – The abc.GuildChannel that got created or deleted.

discord.on_guild_channel_update(before, after)

Called whenever a guild channel is updated. e.g. changed name, topic, permissions.

Parameters
discord.on_guild_channel_pins_update(channel, last_pin)

Called whenever a message is pinned or unpinned from a guild channel.

Parameters
  • channel – The abc.GuildChannel that had it’s pins updated.

  • last_pin – A datetime.datetime object representing when the latest message was pinned or None if there are no pins.

discord.on_webhooks_update(channel)

Called whenever a webhook is created, modified, or removed from a guild channel.

Parameters

channel – The abc.GuildChannel that had its webhooks updated.

discord.on_member_join(member)
discord.on_member_remove(member)

Called when a Member leaves or joins a Guild.

Parameters

member – The Member that joined or left.

discord.on_member_update(before, after)

Called when a Member updates their profile.

This is called when one or more of the following things change:

  • status

  • game playing

  • avatar

  • nickname

  • roles

Parameters
  • before – The Member that updated their profile with the old info.

  • after – The Member that updated their profile with the updated info.

discord.on_guild_join(guild)

Called when a Guild is either created by the Client or when the Client joins a guild.

Parameters

guild – The Guild that was joined.

discord.on_guild_remove(guild)

Called when a Guild is removed from the Client.

This happens through, but not limited to, these circumstances:

  • The client got banned.

  • The client got kicked.

  • The client left the guild.

  • The client or the guild owner deleted the guild.

In order for this event to be invoked then the Client must have been part of the guild to begin with. (i.e. it is part of Client.guilds)

Parameters

guild – The Guild that got removed.

discord.on_guild_update(before, after)

Called when a Guild updates, for example:

  • Changed name

  • Changed AFK channel

  • Changed AFK timeout

  • etc

Parameters
  • before – The Guild prior to being updated.

  • after – The Guild after being updated.

discord.on_guild_role_create(role)
discord.on_guild_role_delete(role)

Called when a Guild creates or deletes a new Role.

To get the guild it belongs to, use Role.guild.

Parameters

role – The Role that was created or deleted.

discord.on_guild_role_update(before, after)

Called when a Role is changed guild-wide.

Parameters
  • before – The Role that updated with the old info.

  • after – The Role that updated with the updated info.

discord.on_guild_emojis_update(guild, before, after)

Called when a Guild adds or removes Emoji.

Parameters
  • guild – The Guild who got their emojis updated.

  • before – A list of Emoji before the update.

  • after – A list of Emoji after the update.

discord.on_guild_available(guild)
discord.on_guild_unavailable(guild)

Called when a guild becomes available or unavailable. The guild must have existed in the Client.guilds cache.

Parameters

guild – The Guild that has changed availability.

discord.on_voice_state_update(member, before, after)

Called when a Member changes their VoiceState.

The following, but not limited to, examples illustrate when this event is called:

  • A member joins a voice room.

  • A member leaves a voice room.

  • A member is muted or deafened by their own accord.

  • A member is muted or deafened by a guild administrator.

Parameters
  • member – The Member whose voice states changed.

  • before – The VoiceState prior to the changes.

  • after – The VoiceState after to the changes.

discord.on_member_ban(guild, user)

Called when user gets banned from a Guild.

Parameters
  • guild – The Guild the user got banned from.

  • user – The user that got banned. Can be either User or Member depending if the user was in the guild or not at the time of removal.

discord.on_member_unban(guild, user)

Called when a User gets unbanned from a Guild.

Parameters
  • guild – The Guild the user got unbanned from.

  • user – The User that got unbanned.

discord.on_group_join(channel, user)
discord.on_group_remove(channel, user)

Called when someone joins or leaves a group, i.e. a PrivateChannel with a PrivateChannel.type of ChannelType.group.

Parameters
  • channel – The group that the user joined or left.

  • user – The user that joined or left.

discord.on_relationship_add(relationship)
discord.on_relationship_remove(relationship)

Called when a Relationship is added or removed from the ClientUser.

Parameters

relationship – The relationship that was added or removed.

discord.on_relationship_update(before, after)

Called when a Relationship is updated, e.g. when you block a friend or a friendship is accepted.

Parameters
  • before – The previous relationship status.

  • after – The updated relationship status.

Utility Functions

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.snowflake_time(id)

Returns the creation date in UTC of a discord id.

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.

Application Info

class discord.AppInfo

A namedtuple representing the bot’s application info.

id

The application’s client_id.

name

The application’s name.

description

The application’s description

icon

The application’s icon hash if it exists, None otherwise.

icon_url

A property that retrieves the application’s icon URL if it exists.

If it doesn’t exist an empty string is returned.

owner

The owner of the application. This is a User instance with the owner’s information at the time of the call.

bot_public

True if the bot is considered as public, else False. Determines if the bot can be invited by anyone or if it is locked to the token owner. Correspond to the “Public bot” box in the token settings.

bot_require_code_grant

True if the bot requires code grant, else False. Correspond to the “Bot requires code grant” box in the token settings.

rpc_origins

Returns an array of RPC origin URL strings, if RPC is enabled. If RPC isn’t enabled, returns None.

Profile

class discord.Profile

A namedtuple representing a user’s Discord public profile.

user

The User the profile belongs to.

premium

A boolean indicating if the user has premium (i.e. Discord Nitro).

nitro

An alias for premium.

premium_since

A naive UTC datetime indicating how long the user has been premium since. This could be None if not applicable.

staff

A boolean indicating if the user is Discord Staff.

partner

A boolean indicating if the user is a Discord Partner.

bug_hunter

A boolean indicating if the user is a Bug Hunter.

early_supporter

A boolean indicating if the user has had premium before 10 October, 2018.

hypesquad

A boolean indicating if the user is in Discord HypeSquad.

hypesquad_houses

A list of HypeSquadHouse that the user is in.

mutual_guilds

A list of Guild that the ClientUser shares with this user.

connected_accounts

A list of dict objects indicating the accounts the user has connected.

An example entry can be seen below:

{type: "twitch", id: "92473777", name: "discordapp"}

Enumerations

The API provides some enumerations for certain types of strings to avoid the API from being stringly typed in case the strings change in the future.

All enumerations are subclasses of enum.

class discord.ChannelType

Specifies the type of channel.

text

A text channel.

voice

A voice channel.

private

A private text channel. Also called a direct message.

group

A private group text channel.

class discord.MessageType

Specifies the type of Message. This is used to denote if a message is to be interpreted as a system message or a regular message.

default

The default message type. This is the same as regular messages.

recipient_add

The system message when a recipient is added to a group private message, i.e. a private channel of type ChannelType.group.

recipient_remove

The system message when a recipient is removed from a group private message, i.e. a private channel of type ChannelType.group.

call

The system message denoting call state, e.g. missed call, started call, etc.

channel_name_change

The system message denoting that a channel’s name has been changed.

channel_icon_change

The system message denoting that a channel’s icon has been changed.

pins_add

The system message denoting that a pinned message has been added to a channel.

new_member

The system message denoting that a new member has joined a Guild.

class discord.ActivityType

Specifies the type of Activity. This is used to check how to interpret the activity itself.

unknown

An unknown activity type. This should generally not happen.

playing

A “Playing” activity type.

streaming

A “Streaming” activity type.

listening

A “Listening” activity type.

watching

A “Watching” activity type.

class discord.HypeSquadHouse

Specifies the HypeSquad house a user belongs to.

bravery

The “Bravery” house.

brilliance

The “Brilliance” house.

balance

The “Balance” house.

class discord.VoiceRegion

Specifies the region a voice server belongs to.

amsterdam

The Amsterdam region.

brazil

The Brazil region.

eu_central

The EU Central region.

eu_west

The EU West region.

frankfurt

The Frankfurt region.

hongkong

The Hong Kong region.

japan

The Japan region.

london

The London region.

russia

The Russia region.

singapore

The Singapore region.

southafrica

The South Africa region.

sydney

The Sydney region.

us_central

The US Central region.

us_east

The US East region.

us_south

The US South region.

us_west

The US West region.

vip_amsterdam

The Amsterdam region for VIP guilds.

vip_us_east

The US East region for VIP guilds.

vip_us_west

The US West region for VIP guilds.

class discord.VerificationLevel

Specifies a Guild’s verification level, which is the criteria in which a member must meet before being able to send messages to the guild.

x == y

Checks if two verification levels are equal.

x != y

Checks if two verification levels are not equal.

x > y

Checks if a verification level is higher than another.

x < y

Checks if a verification level is lower than another.

x >= y

Checks if a verification level is higher or equal to another.

x <= y

Checks if a verification level is lower or equal to another.

none

No criteria set.

low

Member must have a verified email on their Discord account.

medium

Member must have a verified email and be registered on Discord for more than five minutes.

high

Member must have a verified email, be registered on Discord for more than five minutes, and be a member of the guild itself for more than ten minutes.

table_flip

An alias for high.

extreme

Member must have a verified phone on their Discord account.

double_table_flip

An alias for extreme.

class discord.NotificationLevel

Specifies whether a Guild has notifications on for all messages or mentions only by default.

all_messages

Members receive notifications for every message regardless of them being mentioned.

only_mentions

Members receive notifications for messages they are mentioned in.

class discord.ContentFilter

Specifies a Guild’s explicit content filter, which is the machine learning algorithms that Discord uses to detect if an image contains pornography or otherwise explicit content.

x == y

Checks if two content filter levels are equal.

x != y

Checks if two content filter levels are not equal.

x > y

Checks if a content filter level is higher than another.

x < y

Checks if a content filter level is lower than another.

x >= y

Checks if a content filter level is higher or equal to another.

x <= y

Checks if a content filter level is lower or equal to another.

disabled

The guild does not have the content filter enabled.

no_role

The guild has the content filter enabled for members without a role.

all_members

The guild has the content filter enabled for every member.

class discord.Status

Specifies a Member ‘s status.

online

The member is online.

offline

The member is offline.

idle

The member is idle.

dnd

The member is “Do Not Disturb”.

do_not_disturb

An alias for dnd.

invisible

The member is “invisible”. In reality, this is only used in sending a presence a la Client.change_presence(). When you receive a user’s presence this will be offline instead.

class discord.RelationshipType

Specifies the type of Relationship

friend

You are friends with this user.

blocked

You have blocked this user.

incoming_request

The user has sent you a friend request.

outgoing_request

You have sent a friend request to this user.

class discord.AuditLogAction

Represents the type of action being done for a AuditLogEntry, which is retrievable via Guild.audit_logs().

guild_update

The guild has updated. Things that trigger this include:

  • Changing the guild vanity URL

  • Changing the guild invite splash

  • Changing the guild AFK channel or timeout

  • Changing the guild voice server region

  • Changing the guild icon

  • Changing the guild moderation settings

  • Changing things related to the guild widget

When this is the action, the type of target is the Guild.

Possible attributes for AuditLogDiff:

channel_create

A new channel was created.

When this is the action, the type of target is either a abc.GuildChannel or Object with an ID.

A more filled out object in the Object case can be found by using after.

Possible attributes for AuditLogDiff:

channel_update

A channel was updated. Things that trigger this include:

  • The channel name or topic was changed

  • The channel bitrate was changed

When this is the action, the type of target is the abc.GuildChannel or Object with an ID.

A more filled out object in the Object case can be found by using after or before.

Possible attributes for AuditLogDiff:

channel_delete

A channel was deleted.

When this is the action, the type of target is an Object with an ID.

A more filled out object can be found by using the before object.

Possible attributes for AuditLogDiff:

overwrite_create

A channel permission overwrite was created.

When this is the action, the type of target is the abc.GuildChannel or Object with an ID.

When this is the action, the type of extra is either a Role or Member. If the object is not found then it is a Object with an ID being filled, a name, and a type attribute set to either 'role' or 'member' to help dictate what type of ID it is.

Possible attributes for AuditLogDiff:

overwrite_update

A channel permission overwrite was changed, this is typically when the permission values change.

See overwrite_create for more information on how the target and extra fields are set.

Possible attributes for AuditLogDiff:

overwrite_delete

A channel permission overwrite was deleted.

See overwrite_create for more information on how the target and extra fields are set.

Possible attributes for AuditLogDiff:

kick

A member was kicked.

When this is the action, the type of target is the User who got kicked.

When this is the action, changes is empty.

member_prune

A member prune was triggered.

When this is the action, the type of target is set to None.

When this is the action, the type of extra is set to an unspecified proxy object with two attributes:

  • delete_members_days: An integer specifying how far the prune was.

  • members_removed: An integer specifying how many members were removed.

When this is the action, changes is empty.

ban

A member was banned.

When this is the action, the type of target is the User who got banned.

When this is the action, changes is empty.

unban

A member was unbanned.

When this is the action, the type of target is the User who got unbanned.

When this is the action, changes is empty.

member_update

A member has updated. This triggers in the following situations:

  • A nickname was changed

  • They were server muted or deafened (or it was undo’d)

When this is the action, the type of target is the Member or User who got updated.

Possible attributes for AuditLogDiff:

member_role_update

A member’s role has been updated. This triggers when a member either gains a role or losses a role.

When this is the action, the type of target is the Member or User who got the role.

Possible attributes for AuditLogDiff:

role_create

A new role was created.

When this is the action, the type of target is the Role or a Object with the ID.

Possible attributes for AuditLogDiff:

role_update

A role was updated. This triggers in the following situations:

  • The name has changed

  • The permissions have changed

  • The colour has changed

  • Its hoist/mentionable state has changed

When this is the action, the type of target is the Role or a Object with the ID.

Possible attributes for AuditLogDiff:

role_delete

A role was deleted.

When this is the action, the type of target is the Role or a Object with the ID.

Possible attributes for AuditLogDiff:

invite_create

An invite was created.

When this is the action, the type of target is the Invite that was created.

Possible attributes for AuditLogDiff:

invite_update

An invite was updated.

When this is the action, the type of target is the Invite that was updated.

invite_delete

An invite was deleted.

When this is the action, the type of target is the Invite that was deleted.

Possible attributes for AuditLogDiff:

webhook_create

A webhook was created.

When this is the action, the type of target is the Object with the webhook ID.

Possible attributes for AuditLogDiff:

webhook_update

A webhook was updated. This trigger in the following situations:

  • The webhook name changed

  • The webhook channel changed

When this is the action, the type of target is the Object with the webhook ID.

Possible attributes for AuditLogDiff:

webhook_delete

A webhook was deleted.

When this is the action, the type of target is the Object with the webhook ID.

Possible attributes for AuditLogDiff:

emoji_create

An emoji was created.

When this is the action, the type of target is the Emoji or Object with the emoji ID.

Possible attributes for AuditLogDiff:

emoji_update

An emoji was updated. This triggers when the name has changed.

When this is the action, the type of target is the Emoji or Object with the emoji ID.

Possible attributes for AuditLogDiff:

emoji_delete

An emoji was deleted.

When this is the action, the type of target is the Object with the emoji ID.

Possible attributes for AuditLogDiff:

message_delete

A message was deleted by a moderator. Note that this only triggers if the message was deleted by either bulk delete or deletion by someone other than the author.

When this is the action, the type of target is the Member or User who had their message deleted.

When this is the action, the type of extra is set to an unspecified proxy object with two attributes:

  • count: An integer specifying how many messages were deleted.

  • channel: A TextChannel or Object with the channel ID where the message got deleted.

class discord.AuditLogActionCategory

Represents the category that the AuditLogAction belongs to.

This can be retrieved via AuditLogEntry.category.

create

The action is the creation of something.

delete

The action is the deletion of something.

update

The action is the update of something.

Async Iterator

Some API functions return an “async iterator”. An async iterator is something that is capable of being used in an async for statement.

These async iterators can be used as follows:

async for elem in channel.history():
    # do stuff with elem here

Certain utilities make working with async iterators easier, detailed below.

class discord.AsyncIterator

Represents the “AsyncIterator” concept. Note that no such class exists, it is purely abstract.

async for x in y

Iterates over the contents of the async iterator. Note that this is only available in Python 3.5 or higher.

coroutine next()

This function is a coroutine.

Advances the iterator by one, if possible. If no more items are found then this raises NoMoreItems.

coroutine get(**attrs)

This function is a coroutine.

Similar to utils.get() except run over the async iterator.

Getting the last message by a user named ‘Dave’ or None:

msg = await channel.history().get(author__name='Dave')
coroutine find(predicate)

This function is a coroutine.

Similar to utils.find() except run over the async iterator.

Unlike utils.find(), the predicate provided can be a coroutine.

Getting the last audit log with a reason or None:

def predicate(event):
    return event.reason is not None

event = await guild.audit_logs().find(predicate)
Parameters

predicate – The predicate to use. Can be a coroutine.

Returns

The first element that returns True for the predicate or None.

coroutine flatten()

This function is a coroutine.

Flattens the async iterator into a list with all the elements.

Returns

A list of every element in the async iterator.

Return type

list

map(func)

This is similar to the built-in map function. Another AsyncIterator is returned that executes the function on every element it is iterating over. This function can either be a regular function or a coroutine.

Creating a content iterator:

def transform(message):
    return message.content

async for content in channel.history().map(transform):
    message_length = len(content)
Parameters

func – The function to call on every element. Could be a coroutine.

Returns

An async iterator.

filter(predicate)

This is similar to the built-in filter function. Another AsyncIterator is returned that filters over the original async iterator. This predicate can be a regular function or a coroutine.

Getting messages by non-bot accounts:

def predicate(message):
    return not message.author.bot

async for elem in channel.history().filter(predicate):
    ...
Parameters

predicate – The predicate to call on every element. Could be a coroutine.

Returns

An async iterator.

Audit Log Data

Working with Guild.audit_logs() is a complicated process with a lot of machinery involved. The library attempts to make it easy to use and friendly. In order to accomplish this goal, it must make use of a couple of data classes that aid in this goal.

class discord.AuditLogEntry(*, users, data, guild)

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.

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.

class discord.AuditLogChanges

An audit log change set.

before

The old value. The attribute has the type of AuditLogDiff.

Depending on the AuditLogActionCategory retrieved by category, the data retrieved by this attribute differs:

Category

Description

create

All attributes are set to None.

delete

All attributes are set the value before deletion.

update

All attributes are set the value before updating.

None

No attributes are set.

after

The new value. The attribute has the type of AuditLogDiff.

Depending on the AuditLogActionCategory retrieved by category, the data retrieved by this attribute differs:

Category

Description

create

All attributes are set to the created value

delete

All attributes are set to None

update

All attributes are set the value after updating.

None

No attributes are set.

class discord.AuditLogDiff

Represents an audit log “change” object. A change object has dynamic attributes that depend on the type of action being done. Certain actions map to certain attributes being set.

Note that accessing an attribute that does not match the specified action will lead to an attribute error.

To get a list of attributes that have been set, you can iterate over them. To see a list of all possible attributes that could be set based on the action being done, check the documentation for AuditLogAction, otherwise check the documentation below for all attributes that are possible.

iter(diff)

Return an iterator over (attribute, value) tuple of this diff.

name

str – A name of something.

icon

str – A guild’s icon hash. See also Guild.icon.

splash

str – The guild’s invite splash hash. See also Guild.splash.

owner

Union[Member, User] – The guild’s owner. See also Guild.owner

region

GuildRegion – The guild’s voice region. See also Guild.region.

afk_channel

Union[VoiceChannel, Object] – The guild’s AFK channel.

If this could not be found, then it falls back to a Object with the ID being set.

See Guild.afk_channel.

system_channel

Union[TextChannel, Object] – The guild’s system channel.

If this could not be found, then it falls back to a Object with the ID being set.

See Guild.system_channel.

afk_timeout

int – The guild’s AFK timeout. See Guild.afk_timeout.

mfa_level

int - The guild’s MFA level. See Guild.mfa_level.

widget_enabled

bool – The guild’s widget has been enabled or disabled.

widget_channel

Union[TextChannel, Object] – The widget’s channel.

If this could not be found then it falls back to a Object with the ID being set.

verification_level

VerificationLevel – The guild’s verification level.

See also Guild.verification_level.

default_notifications

NotificationLevel – The guild’s default notification level.

See also Guild.default_notifications.

explicit_content_filter

ContentFilter – The guild’s content filter.

See also Guild.explicit_content_filter.

default_message_notifications

int – The guild’s default message notification setting.

vanity_url_code

str – The guild’s vanity URL.

See also Guild.vanity_invite() and Guild.change_vanity_invite().

position

int – The position of a Role or abc.GuildChannel.

type

Union[int, str] – The type of channel or channel permission overwrite.

If the type is an int, then it is a type of channel which can be either 0 to indicate a text channel or 1 to indicate a voice channel.

If the type is a str, then it is a type of permission overwrite which can be either 'role' or 'member'.

topic

str – The topic of a TextChannel.

See also TextChannel.topic.

bitrate

int – The bitrate of a VoiceChannel.

See also VoiceChannel.bitrate.

overwrites

List[Tuple[target, PermissionOverwrite]] – A list of permission overwrite tuples that represents a target and a PermissionOverwrite for said target.

The first element is the object being targeted, which can either be a Member or User or Role. If this object is not found then it is a Object with an ID being filled and a type attribute set to either 'role' or 'member' to help decide what type of ID it is.

roles

List[Union[Role, Object]] – A list of roles being added or removed from a member.

If a role is not found then it is a Object with the ID and name being filled in.

nick

Optional[str] – The nickname of a member.

See also Member.nick

deaf

bool – Whether the member is being server deafened.

See also VoiceState.deaf.

mute

bool – Whether the member is being server muted.

See also VoiceState.mute.

permissions

Permissions – The permissions of a role.

See also Role.permissions.

colour
color

Colour – The colour of a role.

See also Role.colour

hoist

bool – Whether the role is being hoisted or not.

See also Role.hoist

mentionable

bool – Whether the role is mentionable or not.

See also Role.mentionable

code

str – The invite’s code.

See also Invite.code

channel

Union[abc.GuildChannel, Object] – A guild channel.

If the channel is not found then it is a Object with the ID being set. In some cases the channel name is also set.

inviter

User – The user who created the invite.

See also Invite.inviter.

max_uses

int – The invite’s max uses.

See also Invite.max_uses.

uses

int – The invite’s current uses.

See also Invite.uses.

max_age

int – The invite’s max age in seconds.

See also Invite.max_age.

temporary

bool – If the invite is a temporary invite.

See also Invite.temporary.

allow
deny

Permissions – The permissions being allowed or denied.

id

int – The ID of the object being changed.

avatar

str – The avatar hash of a member.

See also User.avatar.

slowmode_delay

int – The number of seconds members have to wait before sending another message in the channel.

See also TextChannel.slowmode_delay.

Webhook Support

discord.py offers support for creating, editing, and executing webhooks through the Webhook class.

class discord.Webhook(data, *, adapter, state=None)

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.

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.

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.

Returns

The resulting CDN URL.

Return type

str

Raises

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

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 – 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 (str) – 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().

Adapters

Adapters allow you to change how the request should be handled. They all build on a single interface, WebhookAdapter.request().

class discord.WebhookAdapter

Base class for all webhook adapters.

webhook

Webhook – The webhook that owns this adapter.

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.

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.

class discord.AsyncWebhookAdapter(session)

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)

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.RequestsWebhookAdapter(session=None, *, sleep=True)

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)

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.

Abstract Base Classes

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

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

class discord.abc.Snowflake

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

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

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

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 list of two-element tuples containing the target, which can be either a Role or a Member and the overwrite as the second element as a PermissionOverwrite.

Returns

The channel’s permission overwrites.

Return type

List[Tuple[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 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 = 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

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.

async-for history(*, limit=100, before=None, after=None, around=None, reverse=None)

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

You must have read_message_history permissions to use this.

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

  • reverse (bool) – If set to true, return messages in oldest->newest order. If unspecified, this defaults to False for most cases. However if passing in a after parameter then this is set to True. This avoids getting messages out of order in the after case.

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.

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...
async-with typing()

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # do expensive stuff here
    await channel.send('done!')
coroutine get_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.

Returns

The message asked for.

Return type

Message

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.

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.

class discord.abc.Connectable

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

The following implement this ABC:

  • VoiceChannel

Discord Models

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

Danger

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

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

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

Note

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

More information about __slots__ can be found in the official python documentation.

ClientUser

class discord.ClientUser

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.

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

get_relationship(user_id)

Retrieves the Relationship if applicable.

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.

friends

Returns a list of Users that the user is friends with.

blocked

Returns a list of Users that the user has blocked.

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

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 ('str') – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’

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

Returns

The resulting CDN URL.

Return type

str

Raises

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

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.

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.

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.

Bot accounts cannot create a group.

Parameters

*recipients – An argument list of User to have in your group.

Returns

The new group channel.

Return type

GroupChannel

Raises
  • HTTPException – Failed to create the group direct message.

  • ClientException – Attempted to create a group with only one recipient. This does not include yourself.

created_at

Returns the user’s creation time in UTC.

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

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.

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.

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
is_avatar_animated()

bool: Returns True if the user has an animated avatar.

mention

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

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.

permissions_in(channel)

An alias for abc.GuildChannel.permissions_for().

Basically equivalent to:

channel.permissions_for(self)
Parameters

channel – The channel to check your permissions for.

Relationship

class discord.Relationship

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.

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.

User

class discord.User

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.

async-for history(*, limit=100, before=None, after=None, around=None, reverse=None)

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

You must have read_message_history permissions to use this.

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

  • reverse (bool) – If set to true, return messages in oldest->newest order. If unspecified, this defaults to False for most cases. However if passing in a after parameter then this is set to True. This avoids getting messages out of order in the after case.

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.

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...
async-with typing()

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # do expensive stuff here
    await channel.send('done!')
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.

is_friend()

bool: Checks if the user is your friend.

is_blocked()

bool: Checks if the user is blocked.

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

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 ('str') – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’

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

Returns

The resulting CDN URL.

Return type

str

Raises

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

coroutine block()

This function is a coroutine.

Blocks the user.

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

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.

coroutine create_dm()

Creates a DMChannel with this user.

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

created_at

Returns the user’s creation time in UTC.

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

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.

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.

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

Returns

The message asked for.

Return type

Message

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.

is_avatar_animated()

bool: Returns True if the user has an animated avatar.

mention

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

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.

permissions_in(channel)

An alias for abc.GuildChannel.permissions_for().

Basically equivalent to:

channel.permissions_for(self)
Parameters

channel – The channel to check your permissions for.

coroutine pins()

This function is a coroutine.

Returns a list of Message that are currently pinned.

Raises

HTTPException – Retrieving the pinned messages failed.

coroutine profile()

This function is a coroutine.

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

Raises
Returns

The profile of the user.

Return type

Profile

coroutine remove_friend()

This function is a coroutine.

Removes the user as a friend.

Raises
  • Forbidden – Not allowed to remove this user as a friend.

  • HTTPException – Removing the user as a friend 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 send_friend_request()

This function is a coroutine.

Sends the user a friend request.

Raises
  • Forbidden – Not allowed to send a friend request to the user.

  • HTTPException – Sending the friend request failed.

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.

coroutine unblock()

This function is a coroutine.

Unblocks the user.

Raises

Attachment

class discord.Attachment

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.

coroutine save(fp, *, seek_begin=True)

This function is a coroutine.

Saves this attachment into a file-like object.

Parameters
  • fp (Union[BinaryIO, str]) – 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.

Raises
Returns

The number of bytes written.

Return type

int

Message

class discord.Message

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 text is in the message itself. Rather this boolean indicates if the @everyone text is in the message and it did end up mentioning everyone.

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.

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.

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.

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.

ack()

This function is a coroutine.

Marks this message as read.

The user must not be a bot user.

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

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

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.

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.

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.

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

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.

Reaction

class discord.Reaction

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.

async-for 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.

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.

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

custom_emoji

bool – If this is a custom emoji.

CallMessage

class discord.CallMessage

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

GroupCall

class discord.GroupCall

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]

Guild

class discord.Guild

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

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.

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

str – The guild’s invite splash.

async-for audit_logs(*, limit=100, before=None, after=None, reverse=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.

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.

  • reverse (bool) – If set to true, return entries in oldest->newest order. If unspecified, this defaults to False for most cases. However if passing in a after parameter then this is set to True. This avoids getting entries out of order in the after case.

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

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

Yields

AuditLogEntry – The audit log entry.

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

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

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

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

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

Returns

The resulting CDN URL.

Return type

str

Raises

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

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

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

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

Returns

The resulting CDN URL.

Return type

str

Raises

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

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.

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.

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

Returns

The created emoji.

Return type

Emoji

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

Returns

The newly created role.

Return type

Role

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

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.

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.

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

This function is a coroutine.

Same as create_text_channel() except makes a VoiceChannel instead.

coroutine delete()

This function is a coroutine.

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

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

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

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

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

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

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

coroutine prune_members(*, days, 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.

Raises
Returns

The number of members pruned.

Return type

int

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

Returns

The special vanity invite.

Return type

Invite

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

  • HTTPException – Retrieving the vanity invite failed.

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]

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

Member

class discord.Member

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

datetime.datetime – A datetime object that specifies the date and time in UTC that the member joined the guild for the first time.

status

Status – The member’s status. There is a chance that the status will be a str if it is a value that is not recognised by the enumerator.

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.

async-for history(*, limit=100, before=None, after=None, around=None, reverse=None)

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

You must have read_message_history permissions to use this.

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

  • reverse (bool) – If set to true, return messages in oldest->newest order. If unspecified, this defaults to False for most cases. However if passing in a after parameter then this is set to True. This avoids getting messages out of order in the after case.

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.

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...
async-with typing()

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # do expensive stuff here
    await channel.send('done!')
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 – 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.

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.

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 – 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
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 ('str') – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’

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

Returns

The resulting CDN URL.

Return type

str

Raises

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

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.

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

Parameters
  • nick (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 (VoiceChannel) – The voice channel to move the member to.

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

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

Returns

The message asked for.

Return type

Message

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.

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.

is_friend(*args, **kwargs)

bool: Checks if the user is your friend.

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

Parameters
  • channel (VoiceChannel) – The new voice channel to move the member to.

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

name

Equivalent to User.name

coroutine pins()

This function is a coroutine.

Returns a list of Message that are currently pinned.

Raises

HTTPException – Retrieving the pinned messages failed.

profile(*args, **kwargs)

This function is a coroutine.

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

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

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

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

send_friend_request(*args, **kwargs)

This function is a coroutine.

Sends the user a friend request.

Raises
  • Forbidden – Not allowed to send a friend request to the user.

  • HTTPException – Sending the friend request failed.

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.

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.

Raises

Spotify

class discord.Spotify

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

x == y

Checks if two activities are equal.

x != y

Checks if two activities are not equal.

hash(x)

Returns the activity’s hash.

str(x)

Returns the string ‘Spotify’.

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

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.

VoiceState

class discord.VoiceState

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.

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.

Emoji

class discord.Emoji

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.

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.

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
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
roles

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

If roles is empty, the emoji is unrestricted.

PartialEmoji

class discord.PartialEmoji

Represents a “partial” emoji.

This model will be given in two scenarios:

x == y

Checks if two emoji are the same.

x != y

Checks if two emoji are not the same.

hash(x)

Return the emoji’s hash.

str(x)

Returns the emoji rendered for discord.

name

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.

is_custom_emoji()

Checks if this is a custom non-Unicode emoji.

is_unicode_emoji()

Checks if this is a Unicode emoji.

url

Returns a URL version of the emoji, if it is custom.

Role

class discord.Role

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.

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.

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

TextChannel

class discord.TextChannel

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.

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.

async-for history(*, limit=100, before=None, after=None, around=None, reverse=None)

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

You must have read_message_history permissions to use this.

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

  • reverse (bool) – If set to true, return messages in oldest->newest order. If unspecified, this defaults to False for most cases. However if passing in a after parameter then this is set to True. This avoids getting messages out of order in the after case.

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.

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...
async-with typing()

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # do expensive stuff here
    await channel.send('done!')
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.

category

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

If there is no category then this is None.

changed_roles

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

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 create_webhook(*, name, avatar=None)

This function is a coroutine.

Creates a webhook for this channel.

Requires manage_webhooks permissions.

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

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

Raises
  • HTTPException – Creating the webhook failed.

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

Returns

The created webhook.

Return type

Webhook

created_at

Returns the channel’s creation time in UTC.

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 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. A value of 0 disables slowmode. The maximum value possible is 120.

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

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

Returns

The message asked for.

Return type

Message

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.

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]

mention

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

overwrites

Returns all of the channel’s overwrites.

This is returned as a list of two-element tuples containing the target, which can be either a Role or a Member and the overwrite as the second element as a PermissionOverwrite.

Returns

The channel’s permission overwrites.

Return type

List[Tuple[Union[Role, Member], PermissionOverwrite]]

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

coroutine pins()

This function is a coroutine.

Returns a list of Message that are currently pinned.

Raises

HTTPException – Retrieving the pinned messages failed.

coroutine purge(*, limit=100, check=None, before=None, after=None, around=None, reverse=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.

Parameters
  • limit (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().

  • reverse – Same as reverse 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.

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

The list of messages that were deleted.

Return type

list

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

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.

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]

VoiceChannel

class discord.VoiceChannel

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.

members

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

category

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

If there is no category then this is None.

changed_roles

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

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

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

created_at

Returns the channel’s creation time in UTC.

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

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]

mention

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

overwrites

Returns all of the channel’s overwrites.

This is returned as a list of two-element tuples containing the target, which can be either a Role or a Member and the overwrite as the second element as a PermissionOverwrite.

Returns

The channel’s permission overwrites.

Return type

List[Tuple[Union[Role, Member], PermissionOverwrite]]

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

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

CategoryChannel

class discord.CategoryChannel

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.

is_nsfw()

Checks if the category is NSFW.

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.

category

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

If there is no category then this is None.

changed_roles

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

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

created_at

Returns the channel’s creation time in UTC.

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

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]

mention

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

overwrites

Returns all of the channel’s overwrites.

This is returned as a list of two-element tuples containing the target, which can be either a Role or a Member and the overwrite as the second element as a PermissionOverwrite.

Returns

The channel’s permission overwrites.

Return type

List[Tuple[Union[Role, Member], PermissionOverwrite]]

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

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

DMChannel

class discord.DMChannel

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.

async-for history(*, limit=100, before=None, after=None, around=None, reverse=None)

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

You must have read_message_history permissions to use this.

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

  • reverse (bool) – If set to true, return messages in oldest->newest order. If unspecified, this defaults to False for most cases. However if passing in a after parameter then this is set to True. This avoids getting messages out of order in the after case.

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.

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...
async-with typing()

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # do expensive stuff here
    await channel.send('done!')
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

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

Returns

The message asked for.

Return type

Message

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.

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.

GroupChannel

class discord.GroupChannel

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.

async-for history(*, limit=100, before=None, after=None, around=None, reverse=None)

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

You must have read_message_history permissions to use this.

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

  • reverse (bool) – If set to true, return messages in oldest->newest order. If unspecified, this defaults to False for most cases. However if passing in a after parameter then this is set to True. This avoids getting messages out of order in the after case.

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.

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...
async-with typing()

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

This is useful for denoting long computations in your bot.

Note

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

Example Usage:

async with channel.typing():
    # do expensive stuff here
    await channel.send('done!')
icon_url

Returns the channel’s icon URL if available or an empty string otherwise.

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.

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

Returns

The message asked for.

Return type

Message

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.

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.

coroutine pins()

This function is a coroutine.

Returns a list of Message that are currently pinned.

Raises

HTTPException – Retrieving the pinned messages failed.

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.

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.

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

Invite

class discord.Invite

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

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

channel

abc.GuildChannel – The channel the invite is for.

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.

RawMessageDeleteEvent

class discord.RawMessageDeleteEvent

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.

RawBulkMessageDeleteEvent

class discord.RawBulkMessageDeleteEvent

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.

RawMessageUpdateEvent

class discord.RawMessageUpdateEvent

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

RawReactionActionEvent

class discord.RawReactionActionEvent

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 or removed the reaction.

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.

RawReactionClearEvent

class discord.RawReactionClearEvent

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.

Data Classes

Some classes are just there to be data containers, this lists them.

Unlike models you are allowed to create these yourself, even if they can also be used to hold attributes.

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

The only exception to this rule is Object, which is made with dynamic attributes in mind.

More information about __slots__ can be found in the official python documentation.

Object

class discord.Object(id)

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.

Embed

class discord.Embed(**kwargs)

Represents a Discord embed.

The following attributes can be set during creation of the object:

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.

type

str – The type of embed. Usually “rich”.

description

str – The description of the embed.

url

str – The URL of the embed.

timestamp

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

colour

Colour or int – The colour code of the embed. Aliased to color as well.

Empty

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

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.

File

class discord.File(fp, filename=None)

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.

Colour

class discord.Colour(value)

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.

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.

Activity

class discord.Activity(**kwargs)

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

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

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.

Game

class discord.Game(name, **extra)

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.

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.

Streaming

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

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.

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.

Permissions

class discord.Permissions(permissions=0)

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.

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_nicknames

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

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.

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

PermissionOverwrite

class discord.PermissionOverwrite(**kwargs)

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

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.

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.

Exceptions

The following exceptions are thrown by the library.

exception discord.DiscordException

Base exception class for discord.py

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

exception discord.ClientException

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

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

exception discord.LoginFailure

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

exception discord.NoMoreItems

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

exception discord.HTTPException(response, message)

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.Forbidden(response, message)

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

Subclass of HTTPException

exception discord.NotFound(response, message)

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

Subclass of HTTPException

exception discord.InvalidArgument

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 derived from ClientException and thus DiscordException.

exception discord.GatewayNotFound

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

exception discord.ConnectionClosed(original, *, shard_id)

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.

exception discord.opus.OpusError(code)

An exception that is thrown for libopus related errors.

code

int – The error code returned.

exception discord.opus.OpusNotLoaded

An exception that is thrown for when libopus is not loaded.