API Reference
The following section outlines the API of discord.py-message-components.
Note
This module uses the Python logging
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-message-components.
Clients
Client
- asyncapplication_info
- asyncbefore_identify_hook
- asyncchange_presence
- defclear
- asyncclose
- asyncconnect
- asynccreate_guild
- asyncdelete_invite
- @event
- asyncfetch_all_nitro_stickers
- asyncfetch_channel
- asyncfetch_guild
- deffetch_guilds
- asyncfetch_invite
- asyncfetch_template
- asyncfetch_user
- asyncfetch_webhook
- asyncfetch_widget
- defget_all_channels
- defget_all_members
- defget_channel
- defget_emoji
- defget_guild
- defget_message
- defget_partial_messageable
- defget_user
- defis_closed
- defis_ready
- defis_ws_ratelimited
- asynclogin
- asynclogout
- @message_command
- asyncon_application_command_error
- @on_click
- asyncon_error
- @on_select
- @on_submit
- asyncrequest_offline_members
- defrun
- @slash_command
- asyncstart
- @user_command
- asyncwait_for
- asyncwait_until_ready
- 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
1000
. Passing inNone
disables the message cache.Changed in version 1.3: Allow disabling the message cache and change the default size to
1000
.loop (Optional[
asyncio.AbstractEventLoop
]) – Theasyncio.AbstractEventLoop
to use for asynchronous operations. Defaults toNone
, in which case the default event loop is used viaasyncio.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 at0
and less thanshard_count
.shard_count (Optional[
int
]) – The total number of shards.intents (
Intents
) – The intents that you want to enable for the _session. This is a way of disabling and enabling certain gateway events from triggering and being sent. If not given, defaults to a regularly constructedIntents
class.gateway_version (
int
) – The gateway and api version to use. Defaults tov10
.api_error_locale (
discord.Locale
) – The locale language to use for api errors. This will be applied to theX-Discord-Local
header in requests. Default toLocale.en_US
member_cache_flags (
MemberCacheFlags
) – Allows for finer control over how the library caches members. If not given, defaults to cache as much as possible with the currently selected intents.fetch_offline_members (
bool
) – A deprecated alias ofchunk_guilds_at_startup
.chunk_guilds_at_startup (
bool
) – Indicates ifon_ready()
should be delayed to chunk all guilds at start-up if necessary. This operation is incredibly slow for large amounts of guilds. The default isTrue
ifIntents.members
isTrue
.status (Optional[
Status
]) – A status to start your presence with upon logging on to Discord.activity (Optional[
BaseActivity
]) – An activity to start your presence with upon logging on to Discord.allowed_mentions (Optional[
AllowedMentions
]) – Control how the client handles mentions by default on every message sent.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.guild_ready_timeout (
float
) –The maximum number of seconds to wait for the GUILD_CREATE stream to end before preparing the member cache and firing READY. The default timeout is 2 seconds.
New in version 1.4.
guild_subscriptions (
bool
) –Whether to dispatch presence or typing events. Defaults to
True
.New in version 1.3.
Warning
If this is set to
False
then the following features will be disabled:No user related updates (
on_user_update()
will not dispatch)- All member related events will be disabled.
Typing events will be disabled (
on_typing()
).If
fetch_offline_members
is set toFalse
then the user cache will not exist. This makes it difficult or impossible to do many things, for example:Computing permissions
Querying members in a voice channel via
VoiceChannel.members
will be empty.Most forms of receiving
Member
will be receivingUser
instead, except for message events.Guild.owner
will usually resolve toNone
.Guild.get_member()
will usually be unavailable.Anything that involves using
Member
.users
will not be as populated.etc.
In short, this makes it so the only member you can reliably query is the message author. Useful for bots that do not require any state.
assume_unsync_clock (
bool
) –Whether to assume the system clock is unsynced. This applies to the ratelimit handling code. If this is set to
True
, the default, then the library uses the time to reset a rate limit bucket given by Discord. If this isFalse
then your system clock is used to calculate how long to sleep for. If this is set toFalse
it is recommended to sync your system clock to Google’s NTP server.New in version 1.3.
sync_commands (
bool
) –Whether to sync application-commands on startup, default
False
.This will register global and guild application-commands(slash-, user- and message-commands) that are not registered yet, update changes and remove application-commands that could not be found in the code anymore if
delete_not_existing_commands
is set toTrue
what it is by default.delete_not_existing_commands (
bool
) – Whether to remove global and guild-only application-commands that are not in the code anymore, defaultTrue
.auto_check_for_updates (
bool
) –Whether to check for available updates automatically, default
False
for legal reasons. For more info seediscord.on_update_available
.Note
For now, this may only work on the original repository, not in forks how. This is because it uses an internal API that only listen to a webhook from the original repo.
In the future this API might be open-sourced, or it will be possible to add your forks URL as a valid source.
- async for ... in fetch_guilds(*, limit=100, before=None, after=None)
Retrieves an
AsyncIterator
that enables receiving your guilds.Note
Using this, you will only receive
Guild.owner
,Guild.icon
,Guild.id
, andGuild.name
perGuild
.Note
This method is an API call. For general usage, consider
guilds
instead.Examples
Usage
async for guild in client.fetch_guilds(limit=150): print(guild.name)
Flattening into a list
guilds = await client.fetch_guilds(limit=150).flatten() # guilds is now a list of Guild...
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of guilds to retrieve. IfNone
, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to100
.before (Union[
abc.Snowflake
,datetime.datetime
]) – Retrieves guilds before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Union[
abc.Snowflake
,datetime.datetime
]) – Retrieve guilds after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.
- Raises:
.HTTPException – Getting the guilds failed.
- Yields:
Guild
– The guild with the guild data parsed.
- property latency
Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
- Type:
- is_ws_ratelimited()
bool
: Whether the websocket is currently rate limited.This can be useful to know when deciding whether you should query members using HTTP or via the gateway.
New in version 1.6.
- property user
Represents the connected client.
None
if not logged in.- Type:
Optional[
ClientUser
]
- property guilds
The guilds that the connected client is a member of.
- Type:
List[
Guild
]
- property emojis
The emojis that the connected client has.
- Type:
List[
Emoji
]
- property stickers
The stickers that the connected client has.
- Type:
List[
Sticker
]
- property cached_messages
Read-only list of messages the connected client has cached.
New in version 1.1.
- Type:
Sequence[
Message
]
- property private_channels
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.
- Type:
List[
abc.PrivateChannel
]
- property voice_clients
Represents a list of voice connections.
These are usually
VoiceClient
instances.- Type:
List[
VoiceProtocol
]
- is_ready()
bool
: Specifies if the client’s internal cache is ready for use.
- await 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. Checkon_error()
for more details.
- await on_application_command_error(cmd, interaction, exception)
This function is a coroutine.
The default error handler when an Exception was raised when invoking an application-command.
By default, this prints to
sys.stderr
however it could be overridden to have a different implementation. Checkon_application_command_error()
for more details.
- await 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 thefetch_offline_members
parameter set toFalse
.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
isTrue
.Warning
This method is deprecated. Use
Guild.chunk()
instead.- Parameters:
*guilds (
Guild
) – An argument list of guilds to request offline members for.- Raises:
.InvalidArgument – If any guild is unavailable in the collection.
- await before_identify_hook(shard_id, *, initial=False)
This function is a coroutine.
A hook that is called before IDENTIFYing a _session. This is useful if you wish to have more control over the synchronization of multiple IDENTIFYing clients.
The default implementation sleeps for 5 seconds.
New in version 1.4.
- await login(token)
This function is a coroutine.
Logs in the client with the specified credentials.
This function can be used in two different ways.
- Parameters:
token (
str
) – The authentication token. Do not prefix this token with anything as the library will do it for you.- 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.
- await logout()
This function is a coroutine.
Logs out of Discord and closes all connections.
Deprecated since version 1.7.
- await 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.
- await close()
This function is a coroutine.
Closes the connection to Discord.
- clear()
Clears the internal state of the bot.
After this, the bot can be considered “re-opened”, i.e.
is_closed()
andis_ready()
both returnFalse
along with the bot’s internal cache cleared.
- await start(token, reconnect=True)
This function is a coroutine.
A shorthand coroutine for
login()
+connect()
.- Raises:
TypeError – An unexpected keyword argument was received.
- run(token, reconnect=True, *, log_handler=MISSING, log_formatter=MISSING, log_level=MISSING, root_logger=False)
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 orconnect()
+login()
.Roughly Equivalent to:
try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(close()) # cancel all tasks lingering finally: loop.close()
This function also sets up the :mod:`logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing
None
to thelog_handler
parameter.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.
- Parameters:
token (
str
) – The authentication token. Do not prefix this token with anything as the library will do it for you.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).log_handler (Optional[
logging.Handler
]) – The log handler to use for the library’s logger. If this isNone
then the library will not set up anything logging related. Logging will still work ifNone
is passed, though it is your responsibility to set it up. The default log handler if not provided islogging.StreamHandler
.log_formatter (
logging.Formatter
) – The formatter to use with the given log handler. If not provided then it defaults to a colour based logging formatter (if available).log_level (
int
) – The default log level for the library’s logger. This is only applied if thelog_handler
parameter is notNone
. Defaults tologging.INFO
.root_logger (
bool
) – Whether to set up the root logger rather than the library logger. By default, only the library logger ('discord'
) is set up. If this is set toTrue
then the root logger is set up as well. Defaults toFalse
.
- is_closed()
bool
: Indicates if the websocket connection is closed.
- property activity
The activity being used upon logging in.
- Type:
Optional[
BaseActivity
]
- property allowed_mentions
The allowed mention configuration.
New in version 1.4.
- Type:
Optional[
AllowedMentions
]
- property users
Returns a list of all the users the bot can see.
- Type:
List[
User
]
- get_channel(id)
Returns a channel with the given ID.
- Parameters:
id (
int
) – The ID to search for.- Returns:
The returned channel or
None
if not found.- Return type:
Optional[Union[
abc.GuildChannel
,abc.PrivateChannel
]]
- get_partial_messageable(id, *, guild_id=None, type=None)
Returns a
PartialMessageable
with the given channel ID. This is useful if you have the ID of a channel but don’t want to do an API call to send messages to it.- Parameters:
id (
int
) – The channel ID to create aPartialMessageable
for.guild_id (Optional[
int
]) – The optional guild ID to create aPartialMessageable
for. This is not required to actually send messages, but it does allow thejump_url()
andguild
properties to function properly.type (Optional[
ChannelType
]) – The underlying channel type for thePartialMessageable
.
- Returns:
The partial messageable created
- Return type:
PartialMessageable
- for ... in 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.- Yields:
abc.GuildChannel
– A channel the client can ‘access’.
- for ... in 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
- Yields:
Member
– A member the client can see.
- await wait_until_ready()
This function is a coroutine.
Waits until the client’s internal cache is all ready.
- 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 ontoasyncio.wait_for()
. By default, it does not timeout. Note that this does propagate theasyncio.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 theon_
prefix, to wait for.check (Optional[Callable[…,
bool
]]) – 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 raisingasyncio.TimeoutError
.
- Raises:
asyncio.TimeoutError – If a timeout is provided, and it was reached.
- Returns:
Returns no arguments, a single argument, or a
tuple
of multiple arguments that mirrors the parameters passed in the event reference.- Return type:
Any
- event(coro)
A decorator that registers an event to listen to.
You can find more info about the events on the documentation below.
The events must be a coroutine, if not,
TypeError
is raised.Example
@client.event async def on_ready(): print('Ready!')
- Raises:
TypeError – The coroutine passed is not actually a coroutine.
- on_click(custom_id=None)
A decorator with wich you can assign a function to a specific
Button
(or its custom_id).Important
The function this is attached to must take the same parameters as a
on_raw_button_click()
event.Warning
The func must be a coroutine, if not,
TypeError
is raised.- Parameters:
custom_id (Optional[Union[Pattern[AnyStr], AnyStr]]) –
If the
custom_id
of theButton
could not be used as a function name, or you want to give the function a different name then the custom_id use this one to set the custom_id. You can also specify a regex and if the custom_id matches it, the function will be executed.Note
As the
custom_id
is converted to a Pattern put^
in front and$
at the end of thecustom_id
if you want that the custom_id must exactly match the specified value. Otherwise, something like ‘cool blue Button is blue’ will let the function bee invoked too.
Example
# the button Button(label='Hey im a cool blue Button', custom_id='cool blue Button', style=ButtonStyle.blurple) # function that's called when the button pressed @client.on_click(custom_id='^cool blue Button$') async def cool_blue_button(i: discord.ComponentInteraction, button: Button): await i.respond(f'Hey you pressed a {button.custom_id}!', hidden=True)
- Return type:
The decorator for the function called when the button clicked
- Raises:
TypeError – The coroutine passed is not actually a coroutine.
- on_select(custom_id=None)
A decorator with which you can assign a function to a specific
SelectMenu
(or its custom_id).Important
The function this is attached to must take the same parameters as a
on_raw_selection_select()
event.Warning
The func must be a coroutine, if not,
TypeError
is raised.- Parameters:
custom_id (Optional[Union[Pattern[AnyStr], AnyStr]] = None) –
If the custom_id of the
SelectMenu
could not be used as a function name, or you want to give the function a different name then the custom_id use this one to set the custom_id. You can also specify a regex and if the custom_id matches it, the function will be executed.Note
As the
custom_id
is converted to a Pattern put^
in front and$
at the end of thecustom_id
if you want that the custom_id must exactly match the specified value. Otherwise, something like ‘choose_your_gender later’ will let the function bee invoked too.
Example
# the SelectMenu SelectMenu(custom_id='choose_your_gender', options=[ SelectOption(label='Female', value='Female', emoji='♀️'), SelectOption(label='Male', value='Male', emoji='♂️'), SelectOption(label='Trans/Non Binary', value='Trans/Non Binary', emoji='⚧') ], placeholder='Choose your Gender') # function that's called when the SelectMenu is used @client.on_select() async def choose_your_gender(i: discord.Interaction, select_menu): await i.respond(f'You selected `{select_menu.values[0]}`!', hidden=True)
- Raises:
TypeError – The coroutine passed is not actually a coroutine.
- on_submit(custom_id=None)
A decorator with wich you can assign a function to a specific
Modal
(or its custom_id).Important
The function this is attached to must take the same parameters as a
on_modal_submit()
event.Warning
The func must be a coroutine, if not,
TypeError
is raised.- Parameters:
custom_id (Optional[Union[Pattern[AnyStr], AnyStr]]) –
If the custom_id of the
Modal
could not be used as a function name, or you want to give the function a different name then the custom_id use this one to set the custom_id. You can also specify a regex and if the custom_id matches it, the function will be executed.Note
As the
custom_id
is converted to a Pattern put^
in front and$
at the end of thecustom_id
if you want that the custom_id must exactly match the specified value. Otherwise, something like ‘suggestions_modal_submit_private’ will let the function bee invoked too.
Example
# the Modal Modal(title='Create a new suggestion', custom_id='suggestions_modal', components=[...]) # function that's called when the Modal is submitted @client.on_submit(custom_id='^suggestions_modal$') async def suggestions_modal_callback(i: discord.ModalSubmitInteraction): ...
- Raises:
TypeError – The coroutine passed is not actually a coroutine.
- slash_command(name=None, name_localizations=<Localizations: None>, description=None, description_localizations=<Localizations: None>, allow_dm=MISSING, is_nsfw=MISSING, default_required_permissions=None, options=[], guild_ids=None, connector={}, option_descriptions={}, option_descriptions_localizations={}, base_name=None, base_name_localizations=<Localizations: None>, base_desc=None, base_desc_localizations=<Localizations: None>, group_name=None, group_name_localizations=<Localizations: None>, group_desc=None, group_desc_localizations=<Localizations: None>)
A decorator that adds a slash-command to the client. The function this is attached to must be a coroutine.
Warning
sync_commands
of theClient
instance must be set toTrue
to register a command if it does not already exist and update it if changes where made.Note
Any of the following parameters are only needed when the corresponding target was not used before (e.g. there is already a command in the code that has these parameters set) - otherwise it will replace the previous value:
allow_dm
is_nsfw
base_name_localizations
base_desc
base_desc_localizations
group_name_localizations
group_desc
group_desc_localizations
- Parameters:
name (Optional[
str
]) – The name of the command. Must only contain a-z, _ and - and be 1-32 characters long. Default to the functions name.name_localizations (Optional[
Localizations
]) – Localizations object for name field. Values follow the same restrictions asname
description (Optional[
str
]) – The description of the command shows up in the client. Must be between 1-100 characters long. Default to the functions docstring or “No Description”.description_localizations (Optional[
Localizations
]) – Localizations object for description field. Values follow the same restrictions asdescription
allow_dm (Optional[
bool
]) – Indicates whether the command is available in DMs with the app, only for globally-scoped commands. By default, commands are visible.is_nsfw (
bool
) –Whether this command is an NSFW command, default
False
Note
Currently all sub-commands of a command that is marked as NSFW are NSFW too.
default_required_permissions (Optional[
Permissions
]) – Permissions that a Member needs by default to execute(see) the command.options (Optional[List[
SlashCommandOption
]]) – A list of max. 25 options for the command. If not provided the options will be generated usinggenerate_options()
that creates the options out of the function parameters. Required options must be listed before optional ones. Useoptions
to connect non-ascii option names with the parameter of the function.guild_ids (Optional[List[
int
]]) – ID’s of guilds this command should be registered in. If empty, the command will be global.connector (Optional[Dict[
str
,str
]]) – A dictionary containing the name of function-parameters as keys and the name of the option as values. Useful for using non-ascii Letters in your option names without getting ide-errors.option_descriptions (Optional[Dict[
str
,str
]]) –Descriptions the
generate_options()
should take for the Options that will be generated. The keys are thename
of the option and the value thedescription
.Note
This will only be used if
options
is not set.option_descriptions_localizations (Optional[Dict[
str
,Localizations
]]) – Localizeddescription
for the options. In the format{'option_name': Localizations(...)}
base_name (Optional[
str
]) – The name of the base-command(a-z, _ and -, 1-32 characters) if you want the command to be in a command-/sub-command-group. If the base-command does not exist yet, it will be added.base_name_localizations (Optional[
Localizations
]) – Localizedbase_name
’s for the command.base_desc (Optional[
str
]) – The description of the base-command(1-100 characters).base_desc_localizations (Optional[
Localizations
]) – Localizedbase_description
’s for the command.group_name (Optional[
str
]) – The name of the command-group(a-z, _ and -, 1-32 characters) if you want the command to be in a sub-command-group.group_name_localizations (Optional[
Localizations
]) – Localizedgroup_name
’s for the command.group_desc (Optional[
str
]) – The description of the sub-command-group(1-100 characters).group_desc_localizations (Optional[
Localizations
]) – Localizedgroup_desc
’s for the command.
- Raises:
TypeError – The function the decorator is attached to is not actual a coroutine or a parameter passed to
SlashCommandOption
is invalid for theoption_type
or theoption_type
itself is invalid.InvalidArgument – You passed
group_name
but nobase_name
.ValueError – Any of
name
,description
,options
,base_name
,base_desc
,group_name
orgroup_desc
is not valid.
- Returns:
If neither
guild_ids
norbase_name
passed: An instance ofSlashCommand
.If
guild_ids
and nobase_name
where passed: An instance ofGuildOnlySlashCommand
representing the guild-only slash-commands.If
base_name
and noguild_ids
where passed: An instance ofSubCommand
.If
base_name
andguild_ids
passed: instance ofGuildOnlySubCommand
representing the guild-only sub-commands.
- Return type:
Union[
SlashCommand
,GuildOnlySlashCommand
,SubCommand
,GuildOnlySubCommand
]
- message_command(name=None, name_localizations=<Localizations: None>, default_required_permissions=None, allow_dm=True, is_nsfw=False, guild_ids=None)
A decorator that registers a
MessageCommand
(shows up underApps
when right-clicking on a message) to the client. The function this is attached to must be a coroutine.Note
sync_commands
of theClient
instance must be set toTrue
to register a command if it does not already exit and update it if changes where made.- Parameters:
name (Optional[
str
]) – The name of the message-command, default to the functions name. Must be between 1-32 characters long.name_localizations (
Localizations
) – Localizedname
’s.default_required_permissions (Optional[
Permissions
]) – Permissions that a member needs by default to execute(see) the command.allow_dm (
bool
) – Indicates whether the command is available in DMs with the app, only for globally-scoped commands. By default, commands are visible.is_nsfw (
bool
) –Whether this command is an NSFW command, default
False
.guild_ids (Optional[List[
int
]]) – ID’s of guilds this command should be registered in. If empty, the command will be global.
- Returns:
The message-command registered.
- Return type:
- Raises:
TypeError – The function the decorator is attached to is not actual a coroutine.
- user_command(name=None, name_localizations=<Localizations: None>, default_required_permissions=None, allow_dm=True, is_nsfw=False, guild_ids=None)
A decorator that registers a
UserCommand
(shows up underApps
when right-clicking on a user) to the client. The function this is attached to must be a coroutine.Note
sync_commands
of theClient
instance must be set toTrue
to register a command if it does not already exist and update it if changes where made.- Parameters:
name (Optional[
str
]) – The name of the user-command, default to the functions name. Must be between 1-32 characters long.name_localizations (
Localizations
) – Localizedname
’s.default_required_permissions (Optional[
Permissions
]) – Permissions that a member needs by default to execute(see) the command.allow_dm (
bool
) – Indicates whether the command is available in DMs with the app, only for globally-scoped commands. By default, commands are visible.is_nsfw (
bool
) –Whether this command is an NSFW command, default
False
.guild_ids (Optional[List[
int
]]) – ID’s of guilds this command should be registered in. If empty, the command will be global.
- Returns:
The user-command registered.
- Return type:
- Raises:
TypeError – The function the decorator is attached to is not actual a coroutine.
- property application_commands
Returns a list of any application command that is registered for the bot`
- Type:
List[
ApplicationCommand
]
- property global_application_commands
Returns a list of all global application commands that are registered for the bot
Note
This requires the bot running and all commands cached, otherwise the list will be empty
- Returns:
A list of registered global application commands for the bot
- Return type:
List[
ApplicationCommand
]
- await change_presence(*, activity=None, status='online')
This function is a coroutine.
Changes the client’s presence.
Changed in version 2.0: Removed the
afk
parameterExample
game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game)
- Parameters:
activity (Optional[
BaseActivity
]) – The activity being done.None
if no currently active activity is done.status (Optional[
Status
]) – Indicates what status to change to. IfNone
, thenStatus.online
is used.
- Raises:
.InvalidArgument – If the
activity
parameter is not the proper type.
- await fetch_template(code)
This function is a coroutine.
Gets a
Template
from a discord.new URL or code.
- await fetch_guild(guild_id)
This function is a coroutine.
Retrieves a
Guild
from an ID.Note
Using this, you will not receive
Guild.channels
,Guild.members
,Member.activity
andMember.voice
perMember
.Note
This method is an API call. For general usage, consider
get_guild()
instead.
- await create_guild(name, region=None, icon=None, *, code=None)
This function is a coroutine.
Creates a
Guild
.Bot accounts in more than 10 guilds are not allowed to create guilds.
- Parameters:
name (
str
) – The name of the guild.region (
VoiceRegion
) – The region for the voice communication server. Defaults toVoiceRegion.us_west
.icon (
bytes
) – The bytes-like object representing the icon. SeeClientUser.edit()
for more details on what is expected.code (Optional[
str
]) –The code for a template to create the guild with.
New in version 1.4.
- Raises:
.HTTPException – Guild creation failed.
.InvalidArgument – Invalid icon image format given. Must be PNG or JPG.
- Returns:
The guild created. This is not the same guild that is added to cache.
- Return type:
- await fetch_invite(url, *, with_counts=True)
This function is a coroutine.
Gets an
Invite
from a discord.gg URL or ID.Note
If the invite is for a guild you have not joined, the guild and channel attributes of the returned
Invite
will bePartialInviteGuild
andPartialInviteChannel
respectively.- Parameters:
url (Union[
Invite
,str
]) – The Discord invite ID or URL (must be a discord.gg URL).with_counts (
bool
) – Whether to include count information in the invite. This fills theInvite.approximate_member_count
andInvite.approximate_presence_count
fields.
- Raises:
.NotFound – The invite has expired or is invalid.
.HTTPException – Getting the invite failed.
- Returns:
The invite from the URL/ID.
- Return type:
- await 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.
- await fetch_widget(guild_id)
This function is a coroutine.
Gets a
Widget
from a guild ID.Note
The guild must have the widget enabled to get this information.
- await application_info()
This function is a coroutine.
Retrieves the bot’s application information.
- Raises:
.HTTPException – Retrieving the information failed somehow.
- Returns:
The bot’s application information.
- Return type:
- await fetch_user(user_id)
This function is a coroutine.
Retrieves a
User
based on their ID. This can only be used by bot accounts. You do not have to share any guilds with the user to get this information, however many operations do require that you do.Note
This method is an API call. If you have
Intents.members
and member cache enabled, considerget_user()
instead.
- await fetch_channel(channel_id)
This function is a coroutine.
Retrieves a
abc.GuildChannel
orabc.PrivateChannel
with the specified ID.Note
This method is an API call. For general usage, consider
get_channel()
instead.New in version 1.2.
- Raises:
.InvalidData – An unknown channel type was received from Discord.
.HTTPException – Retrieving the channel failed.
.NotFound – Invalid Channel ID.
.Forbidden – You do not have permission to fetch this channel.
- Returns:
The channel from the ID.
- Return type:
Union[
abc.GuildChannel
,abc.PrivateChannel
]
- await fetch_webhook(webhook_id)
This function is a coroutine.
Retrieves a
Webhook
with the specified ID.- Raises:
.HTTPException – Retrieving the webhook failed.
.NotFound – Invalid webhook ID.
.Forbidden – You do not have permission to fetch this webhook.
- Returns:
The webhook you requested.
- Return type:
- await fetch_all_nitro_stickers()
Retrieves a
list
with all build-inStickerPack
‘s.- Returns:
A list containing all build-in sticker-packs.
- Return type:
AutoShardedClient
- asyncchange_presence
- asyncclose
- asyncconnect
- defget_shard
- defis_ws_ratelimited
- asyncrequest_offline_members
- 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 thatshard_count
must be provided if this is used. By default, when omitted, the client will launch shards from 0 toshard_count - 1
.- shard_ids
An optional list of shard_ids to launch the shards with.
- Type:
Optional[List[
int
]]
- property latency
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 thelatencies
property. Returnsnan
if there are no shards ready.- Type:
- property latencies
A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
This returns a list of tuples with elements
(shard_id, latency)
.
- get_shard(shard_id)
Optional[
ShardInfo
]: Gets the shard information at a given shard ID orNone
if not found.
- property shards
Returns a mapping of shard IDs to their respective info object.
- Type:
Mapping[int,
ShardInfo
]
- await 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 thefetch_offline_members
parameter set toFalse
.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
isTrue
.Warning
This method is deprecated. Use
Guild.chunk()
instead.- Parameters:
*guilds (
Guild
) – An argument list of guilds to request offline members for.- Raises:
InvalidArgument – If any guild is unavailable in the collection.
- await 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.
- await close()
This function is a coroutine.
Closes the connection to Discord.
- await change_presence(*, activity=None, status=None, afk=False, shard_id=None)
This function is a coroutine.
Changes the client’s presence.
Example:
game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game)
- Parameters:
activity (Optional[
BaseActivity
]) – The activity being done.None
if no currently active activity is done.status (Optional[
Status
]) – Indicates what status to change to. IfNone
, thenStatus.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 orNone
, then it will change the presence of every shard the bot can see.
- Raises:
InvalidArgument – If the
activity
parameter is not of proper type.
- is_ws_ratelimited()
bool
: Whether the websocket is currently rate limited.This can be useful to know when deciding whether you should query members using HTTP or via the gateway.
This implementation checks if any of the shards are rate limited. For more granular control, consider
ShardInfo.is_ws_ratelimited()
.New in version 1.6.
Application Info
AppInfo
- class discord.AppInfo
Represents the application info for the bot provided by Discord.
- team
The application’s team.
New in version 1.3.
- Type:
Optional[
Team
]
- icon
The icon hash, if it exists.
- Type:
Optional[
str
]
- description
The application description.
- Type:
Optional[
str
]
- bot_public
Whether the bot can be invited by anyone or if it is locked to the application owner.
- Type:
- bot_require_code_grant
Whether the bot requires the completion of the full oauth2 code grant flow to join.
- Type:
- rpc_origins
A list of RPC origin URLs, if RPC is enabled.
- Type:
Optional[List[
str
]]
- summary
If this application is a game sold on Discord, this field will be the summary field for the store page of its primary SKU.
Deprecated: This field is deprecated and will be removed in API v11
New in version 1.3.
Deprecated since version 2.0.
- Type:
- verify_key
The hex encoded key for verification in interactions and the GameSDK’s GetTicket.
New in version 1.3.
- Type:
- guild_id
If this application is a game sold on Discord, this field will be the guild to which it has been linked to.
New in version 1.3.
- Type:
Optional[
int
]
- primary_sku_id
If this application is a game sold on Discord, this field will be the id of the “Game SKU” that is created, if it exists.
New in version 1.3.
- Type:
Optional[
int
]
- slug
If this application is a game sold on Discord, this field will be the URL slug that links to the store page.
New in version 1.3.
- Type:
Optional[
str
]
- cover_image
If this application is a game sold on Discord, this field will be the hash of the image on store embeds
New in version 1.3.
- Type:
Optional[
str
]
- custom_install_url
The default invite-url for the bot if its set.
- Type:
Optional[
str
]
- install_params
The settings for the application’s default in-app authorization link, if enabled.
- Type:
Optional[
InstallParams
]
- privacy_policy_url
The link to this application’s Privacy Policy if set.
- Type:
Optional[
str
]
- terms_of_service_url
The link to this application’s Terms of Service if set.
- Type:
Optional[
str
]
- interactions_endpoint_url
The endpoint that will receive interactions with this app if its set.
- Type:
Optional[
str
]
- property icon_url
Retrieves the application’s icon asset.
This is equivalent to calling
icon_url_as()
with the default parameters (‘webp’ format and a size of 1024).New in version 1.3.
- Type:
- icon_url_as(*, format='webp', size=1024)
Returns an
Asset
for the icon the application has.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’ or ‘png’. The size must be a power of 2 between 16 and 4096.
New in version 1.6.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- property cover_image_url
Retrieves the cover image on a store embed.
This is equivalent to calling
cover_image_url_as()
with the default parameters (‘webp’ format and a size of 1024).New in version 1.3.
- Type:
- cover_image_url_as(*, format='webp', size=1024)
Returns an
Asset
for the image on store embeds if this application is a game sold on Discord.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’ or ‘png’. The size must be a power of 2 between 16 and 4096.
New in version 1.6.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- property guild
If this application is a game sold on Discord, this field will be the guild to which it has been linked
New in version 1.3.
- Type:
Optional[
Guild
]
Team
- class discord.Team
Represents an application team for a bot provided by Discord.
- icon
The icon hash, if it exists.
- Type:
Optional[
str
]
- members
A list of the members in the team
New in version 1.3.
- Type:
List[
TeamMember
]
- property icon_url
Retrieves the team’s icon asset.
This is equivalent to calling
icon_url_as()
with the default parameters (‘webp’ format and a size of 1024).- Type:
- icon_url_as(*, format='webp', size=1024)
Returns an
Asset
for the icon the team has.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’ or ‘png’. The size must be a power of 2 between 16 and 4096.
New in version 2.0.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- property owner
The team’s owner.
- Type:
Optional[
TeamMember
]
TeamMember
- class discord.TeamMember
Represents a team member in a team.
- x == y
Checks if two team members are equal.
- x != y
Checks if two team members are not equal.
- hash(x)
Return the team member’s hash.
- str(x)
Returns the team member’s name with discriminator.
New in version 1.3.
- avatar
The avatar hash the team member has. Could be None.
- Type:
Optional[
str
]
Event Reference
This section 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_shard_connect(shard_id)
Similar to
on_connect()
except used byAutoShardedClient
to denote when a particular shard ID has connected to Discord.New in version 1.4.
- Parameters:
shard_id (
int
) – The shard ID that has connected.
- discord.on_disconnect()
Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. This could happen either through the internet being disconnected, explicit calls to close, or Discord terminating the connection one way or the other.
This function can be called many times without a corresponding
on_connect()
call.
- discord.on_shard_disconnect(shard_id)
Similar to
on_disconnect()
except used byAutoShardedClient
to denote when a particular shard ID has disconnected from Discord.New in version 1.4.
- Parameters:
shard_id (
int
) – The shard ID that has disconnected.
- 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 byAutoShardedClient
to denote when a particular shard ID has become ready.- Parameters:
shard_id (
int
) – The shard ID that is ready.
- discord.on_shard_resumed(shard_id)
Similar to
on_resumed()
except used byAutoShardedClient
to denote when a particular shard ID has resumed a session.New in version 1.4.
- Parameters:
shard_id (
int
) – The shard ID that has resumed.
- 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 suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to
sys.exc_info()
.If you want exception to propagate out of the
Client
class you can define anon_error
handler consisting of a single empty raise statement. Exceptions raised byon_error
will not be handled in any way byClient
.Note
on_error
will only be dispatched toClient.event()
.It will not be received by
Client.wait_for()
, or, if used, Bots listeners such aslisten()
orlistener()
.- Parameters:
event (
str
) – 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 exception.
- discord.on_application_command_error(command, interaction, exception)
The default error handler when an exception was raised while invoking an application-command .
Note
This includes when a
check()
failsBy default, this prints to
sys.stderr
however it could be overridden to have a different implementation.- Parameters:
command (
ApplicationCommand
) – TheSlashCommand
/SubCommand
,MessageCommand
orUserCommand
in wich invocation the exception was raised.interaction (
ApplicationCommandInteraction
) – The interaction that was invokedexception (
Exception
) – The exception that was raised
- 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.
- 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 sent from the client WebSocket. The voice WebSocket will not trigger this event.
- discord.on_typing(channel, user, when)
Called when someone begins typing a message.
The
channel
parameter can be aabc.Messageable
instance. Which could either beTextChannel
,GroupChannel
, orDMChannel
.If the
channel
is aTextChannel
then theuser
parameter is aMember
, otherwise it is aUser
.This requires
Intents.typing
to be enabled.- Parameters:
channel (
abc.Messageable
) – The location where the typing originated from.when (
datetime.datetime
) – When the typing started as a naive datetime in UTC.
- discord.on_message(message)
Called when a
Message
is created and sent.This requires
Intents.messages
to be enabled.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 (
Message
) – The current message.
- discord.on_message_delete(message)
Called when a message is deleted. If the message is not found in the internal message cache, then this event will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the
Client.max_messages
attribute or use theon_raw_message_delete()
event instead.This requires
Intents.messages
to be enabled.- Parameters:
message (
Message
) – The deleted message.
- discord.on_bulk_message_delete(messages)
Called when messages are bulk deleted. If none of the messages deleted are found in the internal message cache, then this event will not be called. If individual messages were not found in the internal message cache, this event will still be called, but the messages not found will not be included in the messages list. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the
Client.max_messages
attribute or use theon_raw_bulk_message_delete()
event instead.This requires
Intents.messages
to be enabled.- Parameters:
messages (List[
Message
]) – The messages that have been deleted.
- 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.If the message is found in the message cache, it can be accessed via
RawMessageDeleteEvent.cached_message
This requires
Intents.messages
to be enabled.- Parameters:
payload (
RawMessageDeleteEvent
) – The raw event payload data.
- discord.on_raw_bulk_message_delete(payload)
Called when a bulk delete is triggered. Unlike
on_bulk_message_delete()
, this is called regardless of the messages being in the internal message cache or not.If the messages are found in the message cache, they can be accessed via
RawBulkMessageDeleteEvent.cached_messages
This requires
Intents.messages
to be enabled.- 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 internal message cache, then these events will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.If this occurs increase the
Client.max_messages
attribute or use theon_raw_message_edit()
event instead.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.
The message’s embeds were suppressed or unsuppressed.
A call message has received an update to its participants or ending time.
This requires
Intents.messages
to be enabled.
- 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.If the message is found in the message cache, it can be accessed via
RawMessageUpdateEvent.cached_message
. The cached message represents the message before it has been edited. For example, if the content of a message is modified and triggers theon_raw_message_edit()
coroutine, theRawMessageUpdateEvent.cached_message
will return aMessage
object that represents the message before the content was modified.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.This requires
Intents.messages
to be enabled.- 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 internal message cache, then this event will not be called. Consider usingon_raw_reaction_add()
instead.Note
To get the
Message
being reacted, access it viaReaction.message
.This requires
Intents.reactions
to be enabled.Note
This doesn’t require
Intents.members
within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider usingon_raw_reaction_add()
if you need this and do not otherwise want to enable the members intent.
- 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.This requires
Intents.reactions
to be enabled.- 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 internal message cache, then this event will not be called.
Note
To get the message being reacted, access it via
Reaction.message
.This requires both
Intents.reactions
andIntents.members
to be enabled.Note
Consider using
on_raw_reaction_remove()
if you need this and do not want to enable the members intent.
- discord.on_raw_reaction_remove(payload)
Called when a message has a reaction removed. Unlike
on_reaction_remove()
, this is called regardless of the state of the internal message cache.This requires
Intents.reactions
to be enabled.- 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 internal message cache, then this event will not be called. Consider usingon_raw_reaction_clear()
instead.This requires
Intents.reactions
to be enabled.
- 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.This requires
Intents.reactions
to be enabled.- Parameters:
payload (
RawReactionClearEvent
) – The raw event payload data.
- discord.on_reaction_clear_emoji(reaction)
Called when a message has a specific reaction removed from it. Similar to
on_message_edit()
, if the message is not found in the internal message cache, then this event will not be called. Consider usingon_raw_reaction_clear_emoji()
instead.This requires
Intents.reactions
to be enabled.New in version 1.3.
- Parameters:
reaction (
Reaction
) – The reaction that got cleared.
- discord.on_raw_reaction_clear_emoji(payload)
Called when a message has a specific reaction removed from it. Unlike
on_reaction_clear_emoji()
this is called regardless of the state of the internal message cache.This requires
Intents.reactions
to be enabled.New in version 1.3.
- Parameters:
payload (
RawReactionClearEmojiEvent
) – 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.
This requires
Intents.messages
to be enabled.- Parameters:
channel (
abc.PrivateChannel
) – The private channel 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.
This requires
Intents.messages
to be enabled.- Parameters:
before (
GroupChannel
) – The updated group channel’s old info.after (
GroupChannel
) – The updated group channel’s new info.
- discord.on_private_channel_pins_update(channel, last_pin)
Called whenever a message is pinned or unpinned from a private channel.
- Parameters:
channel (
abc.PrivateChannel
) – The private channel that had its pins updated.last_pin (Optional[
datetime.datetime
]) – The latest message that was pinned as a naive datetime in UTC. Could beNone
.
- 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
.This requires
Intents.guilds
to be enabled.- Parameters:
channel (
abc.GuildChannel
) – The guild channel 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.
This requires
Intents.guilds
to be enabled.- Parameters:
before (
abc.GuildChannel
) – The updated guild channel’s old info.after (
abc.GuildChannel
) – The updated guild channel’s new info.
- discord.on_guild_channel_pins_update(channel, last_pin)
Called whenever a message is pinned or unpinned from a guild channel.
This requires
Intents.guilds
to be enabled.- Parameters:
channel (
abc.GuildChannel
) – The guild channel that had its pins updated.last_pin (Optional[
datetime.datetime
]) – The latest message that was pinned as a naive datetime in UTC. Could beNone
.
- discord.on_guild_integrations_update(guild)
New in version 1.4.
Called whenever an integration is created, modified, or removed from a guild.
This requires
Intents.integrations
to be enabled.- Parameters:
guild (
Guild
) – The guild that had its integrations updated.
- discord.on_webhooks_update(channel)
Called whenever a webhook is created, modified, or removed from a guild channel.
This requires
Intents.webhooks
to be enabled.- Parameters:
channel (
abc.GuildChannel
) – The channel that had its webhooks updated.
- discord.on_member_join(member)
- discord.on_member_remove(member)
Called when a
Member
leaves or joins aGuild
.This requires
Intents.members
to be enabled.- Parameters:
member (
Member
) – The member who 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
activity
nickname
roles
pending
This requires
Intents.members
to be enabled.
- discord.on_user_update(before, after)
Called when a
User
updates their profile.This is called when one or more of the following things change:
avatar
username
discriminator
This requires
Intents.members
to be enabled.
- discord.on_guild_join(guild)
Called when a
Guild
is either created by theClient
or when theClient
joins a guild.This requires
Intents.guilds
to be enabled.- Parameters:
guild (
Guild
) – The guild that was joined.
- discord.on_guild_remove(guild)
Called when a
Guild
is removed from theClient
.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 ofClient.guilds
)This requires
Intents.guilds
to be enabled.- Parameters:
guild (
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
This requires
Intents.guilds
to be enabled.
- discord.on_guild_role_create(role)
- discord.on_guild_role_delete(role)
Called when a
Guild
creates or deletes a newRole
.To get the guild it belongs to, use
Role.guild
.This requires
Intents.guilds
to be enabled.- Parameters:
role (
Role
) – The role that was created or deleted.
- discord.on_guild_role_update(before, after)
Called when a
Role
is changed guild-wide.This requires
Intents.guilds
to be enabled.
- discord.on_guild_emojis_update(guild, before, after)
Called when a
Guild
adds or removesEmoji
.This requires
Intents.emojis
to be enabled.
- discord.on_guild_available(guild)
Called when a guild becomes available or unavailable. The guild must have existed in the
Client.guilds
cache.This requires
Intents.guilds
to be enabled.- Parameters:
guild – The
Guild
that has changed availability.
- discord.on_voice_state_update(member, before, after)
Called when a
Member
changes theirVoiceState
.The following, but not limited to, examples illustrate when this event is called:
A member joins a voice channel.
A member leaves a voice channel.
A member is muted or deafened by their own accord.
A member is muted or deafened by a guild administrator.
This requires
Intents.voice_states
to be enabled.- Parameters:
member (
Member
) – The member whose voice states changed.before (
VoiceState
) – The voice state prior to the changes.after (
VoiceState
) – The voice state after the changes.
- discord.on_member_ban(guild, user)
Called when user gets banned from a
Guild
.This requires
Intents.bans
to be enabled.
- discord.on_member_unban(guild, user)
Called when a
User
gets unbanned from aGuild
.This requires
Intents.bans
to be enabled.
- discord.on_invite_create(invite)
Called when an
Invite
is created. You must have themanage_channels
permission to receive this.New in version 1.3.
Note
There is a rare possibility that the
Invite.guild
andInvite.channel
attributes will be ofObject
rather than the respective models.This requires
Intents.invites
to be enabled.- Parameters:
invite (
Invite
) – The invite that was created.
- discord.on_invite_delete(invite)
Called when an
Invite
is deleted. You must have themanage_channels
permission to receive this.New in version 1.3.
Note
There is a rare possibility that the
Invite.guild
andInvite.channel
attributes will be ofObject
rather than the respective models.Outside of those two attributes, the only other attribute guaranteed to be filled by the Discord gateway for this event is
Invite.code
.This requires
Intents.invites
to be enabled.- Parameters:
invite (
Invite
) – The invite that was deleted.
- discord.on_group_join(channel, user)
- discord.on_group_remove(channel, user)
Called when someone joins or leaves a
GroupChannel
.- Parameters:
channel (
GroupChannel
) – The group that the user joined or left.user (
User
) – The user that joined or left.
- discord.on_automod_rule_create(rule)
Called when a auto moderation rule is created.
- Parameters:
rule (
AutoModRule
) – The rule that was created.
- discord.on_automod_rule_update(before, after)
Called when a auto moderation rule is updated.
- Parameters:
before (
AutoModRule
) – The old rule.
Warning
This will be
None
if the rule was not in the cache before.- Parameters:
after (
AutoModRule
) – The updated rule.
- discord.on_automod_rule_delete(rule)
Called when a auto moderation rule is deleted.
- Parameters:
rule (
AutoModRule
) – The rule that was deleted.
- discord.on_automod_action(payload)
Called when a
AutoModRule
was triggered by a user- Parameters:
payload (
AutoModActionPayload
) – The payload containing all the information
- discord.on_button_click(interaction, button)
Called when a
Button
, that is attached to aMessage
wich is in the internal cache, is pressed.Note
In general it is more efficient to use
on_click()
/ext.commands.Cog.on_click()
instead of this andon_raw_button_click()
to make a callback for buttons- Parameters:
interaction (
ComponentInteraction
) – The Interaction-object with all his attributes and methods to respond to the interactionbutton (
Button
) – The button that was pressed. (this is also available underdiscord.ComponentInteraction.component
).
- discord.on_raw_button_click(interaction, button)
Called when a
Button
, that is attached to anyMessage
of the bot, is pressed.Warning
This may be removed and be included in
on_button_click()
in a future release- Parameters:
interaction (
ComponentInteraction
) – The Interaction-object with all his attributes and methods to respond to the interactionbutton (
Button
) – The button that was pressed. (this is also available underdiscord.ComponentInteraction.component
).
- discord.on_selection_select(interaction, select_menu)
Called when a
SelectMenu
, that is attached to aMessage
wich is in the internal cache, is used.Note
In general it is more efficient to use
on_select()
/ext.commands.Cog.on_select()
instead of this andon_raw_selection_select()
to make a callback for select menus- Parameters:
interaction (
ComponentInteraction
) – The Interaction-object with all his attributes and methods to respond to the interactionselect_menu (
SelectMenu
) – TheSelectMenu
but with theSelectMenu.values
set wich contains a list of the selectedoptions
. (this is also available underdiscord.ComponentInteraction.component
).
- discord.on_raw_selection_select(interaction, select_menu)
Called when a
SelectMenu
, that is attached to anyMessage
of the bot, is used.Warning
This may be removed and be included in
on_selection_select()
in a future release- Parameters:
interaction (
ComponentInteraction
) – The Interaction-object with all his attributes and methods to respond to the interactionselect_menu (
SelectMenu
) – TheSelectMenu
but with theSelectMenu.values
set wich contains a list of the selectedoptions
. (this is also available underdiscord.ComponentInteraction.component
).
- discord.on_modal_submit(interaction)
Called when a user press the
Submit
button in aModal
.Note
In general it is more efficient to use
on_submit()
/ext.commands.Cog.on_submit()
instead of this to make a callback for modals- Parameters:
interaction (
ModalSubmitInteraction
) – he Interaction-object with all his attributes and methods to respond to the interaction
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 = discord.utils.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, thenNone
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 forfind()
.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 inx__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)
- Parameters:
id (
int
) – The snowflake ID.- Returns:
The creation date in UTC of a Discord snowflake ID.
- Return type:
- discord.utils.oauth_url(client_id, permissions=None, guild=None, redirect_uri=None, scopes=('bot',))
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.scopes (Iterable[
str
]) –An optional valid list of scopes. Defaults to
('bot',)
.New in version 1.7.
- Returns:
The OAuth2 URL for inviting the bot into guilds.
- Return type:
- discord.utils.remove_markdown(text, *, ignore_links=True)
A helper function that removes markdown characters.
New in version 1.7.
Note
This function is not markdown aware and may remove meaning from the original text. For example, if the input contains
10 * 5
then it will be converted into10 5
.- Parameters:
- Returns:
The text with the markdown special characters removed.
- Return type:
- discord.utils.escape_markdown(text, *, as_needed=False, ignore_links=True)
A helper function that escapes Discord’s markdown.
- Parameters:
text (
str
) – The text to escape markdown from.as_needed (
bool
) – Whether to escape the markdown characters as needed. This means that it does not escape extraneous characters if it’s not necessary, e.g.**hello**
is escaped into\*\*hello**
instead of\*\*hello\*\*
. Note however that this can open you up to some clever syntax abuse. Defaults toFalse
.ignore_links (
bool
) – Whether to leave links alone when escaping markdown. For example, if a URL in the text contains characters such as_
then it will be left alone. This option is not supported withas_needed
. Defaults toTrue
.
- Returns:
The text with the markdown special characters escaped with a slash.
- Return type:
- discord.utils.escape_mentions(text)
A helper function that escapes everyone, here, role, and user mentions.
Note
This does not include channel mentions.
Note
For more granular control over what mentions should be escaped within messages, refer to the
AllowedMentions
class.
- discord.utils.resolve_invite(invite)
Resolves an invite from a
Invite
, URL or code.
- discord.utils.resolve_template(code)
Resolves a template code from a
Template
, URL or code.New in version 1.4.
- await discord.utils.sleep_until(when, result=None)
This function is a coroutine.
Sleep until a specified time.
If the time supplied is in the past this function will yield instantly.
New in version 1.3.
- Parameters:
when (
datetime.datetime
) – The timestamp in which to sleep until. If the datetime is naive then it is assumed to be in UTC.result (Any) – If provided is returned to the caller when the coroutine completes.
- discord.utils.styled_timestamp(timestamp, style=short)
A small function that returns a styled timestamp for discord, this will be displayed accordingly in the Discord client depending on the
style
specified.Timestamps will display the given timestamp in the user’s timezone and locale.
- Parameters:
timestamp (Union[
datetime.datetime
,int
]) – The timestamp; Adatetime.datetime
object or a unix timestamp as anint
.style (Optional[Union[
TimestampStyle
,str
]]) –How the timestamp should be displayed in Discord; this can either be a
TimestampStyle
or directly the associated value.- default:
Examples
# Normal timestamp @client.command() async def time(ctx): await ctx.send(discord.utils.styled_timestamp(discord.utils.utcnow(), discord.TimestampStyle.long)) # Relative timestamp @client.command() async def countdown(ctx, seconds: int): happens_in = discord.utils.utcnow() + datetime.timedelta(seconds=seconds) await ctx.send(f'Happens {discord.utils.styled_timestamp(happens_in, discord.TimestampStyle.relative)}')
- Raises:
AttributeError – If the
style
is not a valid member ofTimestampStyle
- Returns:
The formatted timestamp.
- Return type:
- discord.MISSING
The
MISSING
object is a special object used as default value in places whereNone
cant be used as it is a valid value too. For example in the mostedit
functions.
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 an internal class which mimics the behaviour
of enum.Enum
.
Note
You can use any of the enum classe members as an attribute of an instance of it to get a bool
whether the instance has this value.
For example channel.type.private will return True
if the channel is a private channel (PS: channel must be a DMChannel
or any other channel like object in this case)
- 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.- x == y
Checks if two messages are equal.
- x != y
Checks if two messages are not equal.
- 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
.
The system message denoting that a member has “nitro boosted” a guild.
The system message denoting that a member has “nitro boosted” a guild and it achieved level 1.
The system message denoting that a member has “nitro boosted” a guild and it achieved level 2.
The system message denoting that a member has “nitro boosted” a guild and it achieved level 3.
- channel_follow_add
The system message denoting that an announcement channel has been followed.
New in version 1.3.
- guild_stream
The system message denoting that a member is streaming in the guild.
New in version 1.7.
- guild_discovery_disqualified
The system message denoting that the guild is no longer eligible for Server Discovery.
New in version 1.7.
- guild_discovery_requalified
The system message denoting that the guild has become eligible again for Server Discovery.
New in version 1.7.
- guild_discovery_grace_period_initial_warning
The system message denoting that the guild has failed to meet the Server Discovery requirements for one week.
New in version 1.7.
- guild_discovery_grace_period_final_warning
The system message denoting that the guild has failed to meet the Server Discovery requirements for 3 weeks in a row.
New in version 1.7.
- guild_invite_reminder
The system message denoting that a guild invite reminder has been sent.
New in version 2.0.
A message that is a context menu command.
New in version 2.0.
- role_subscription_purchase
A message informing about a role subscription purchase.
New in version 2.0.
A message informing about a premium upsell.
New in version 2.0.
- stage_raise_hand
A message informing about someone raising their hand in a stage.
New in version 2.0.
The system message denoting that a member has subscribed to a guild application.
New in version 2.4.
- class discord.ButtonStyle
The possible styles for a
Button
- class discord.InteractionCallbackType
InteractionCallbackType to react to an
BaseInteraction
NAME
VALUE
DESCRIPTION
USAGE
EXAMPLE
1
ACK a
Ping
ACK a Ping to Discord
~
4
respond to an interaction with a message
Interaction.respond
Click to view example
5
ACK an interaction and edit a response later, the user sees a loading state
Possible
response_type
for _deferClick to view example
6
for components, ACK an interaction and edit the original message later; the user does not see a loading state
Possible
response_type
for _deferClick to view example
7
for components, edit the message the component was attached to
Interaction.edit
Click to view example
- class discord.Locale
Valid locals that are used at different places in the discord api.
Note
Usually you can use the lowercase
Language Name
(spaces replaced with underscores) as a valid locale too.Locale
Language Name
Native Name
Danish
Dansk
German
Deutsch
English, UK
English, UK
English, US
English, US
Spanish
Español
French
Français
Croatian
Hrvatski
Italian
Italiano
Lithuanian
Lietuviškai
Hungarian
Magyar
Dutch
Nederlands
Norwegian
Norsk
Polish
Polski
Portuguese/Brazilian
Português do Brasil
Romanian, Romania
Română
Finnish
Suomi
Swedish
Svenska
Vietnamese
Tiếng Việt
Turkish
Türkçe
Czech
Čeština
Greek
Ελληνικά
Bulgarian
български
Russian
Pусский
Ukrainian
Українська
Hindi
हिन्दी
Thai
ไทย
Chinese, China
中文
Japanese
日本語
Chinese, Taiwan
繁體中文
Korean
한국어
- class discord.ActivityType
Specifies the type of
Activity
. This is used to check how to interpret the activity itself.
- 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.
- 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
.
- double_table_flip
An alias for
extreme
.
- very_high
An alias for
extreme
.New in version 1.4.
- class discord.NotificationLevel
Specifies whether a
Guild
has notifications on for all messages or mentions only by default.
- 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.
- class discord.Status
Specifies a
Member
‘s status.- 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 beoffline
instead.
- class discord.AuditLogAction
Represents the type of action being done for a
AuditLogEntry
, which is retrievable viaGuild.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 theGuild
.Possible attributes for
AuditLogDiff
:
- channel_create
A new channel was created.
When this is the action, the type of
target
is either aabc.GuildChannel
orObject
with an ID.A more filled out object in the
Object
case can be found by usingafter
.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 theabc.GuildChannel
orObject
with an ID.A more filled out object in the
Object
case can be found by usingafter
orbefore
.Possible attributes for
AuditLogDiff
:
- channel_delete
A channel was deleted.
When this is the action, the type of
target
is anObject
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 theabc.GuildChannel
orObject
with an ID.When this is the action, the type of
extra
is either aRole
orMember
. If the object is not found then it is aObject
with an ID being filled, a name, and atype
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 thetarget
andextra
fields are set.Possible attributes for
AuditLogDiff
:
- overwrite_delete
A channel permission overwrite was deleted.
See
overwrite_create
for more information on how thetarget
andextra
fields are set.Possible attributes for
AuditLogDiff
:
- kick
A member was kicked.
When this is the action, the type of
target
is theUser
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 toNone
.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 theUser
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 theUser
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 theMember
orUser
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 theMember
orUser
who got the role.Possible attributes for
AuditLogDiff
:
- member_move
A member’s voice channel has been updated. This triggers when a member is moved to a different voice channel.
When this is the action, the type of
extra
is set to an unspecified proxy object with two attributes:channel
: ATextChannel
orObject
with the channel ID where the members were moved.count
: An integer specifying how many members were moved.
New in version 1.3.
- member_disconnect
A member’s voice state has changed. This triggers when a member is force disconnected from voice.
When this is the action, the type of
extra
is set to an unspecified proxy object with one attribute:count
: An integer specifying how many members were disconnected.
New in version 1.3.
- bot_add
A bot was added to the guild.
When this is the action, the type of
target
is theMember
orUser
which was added to the guild.New in version 1.3.
- role_create
A new role was created.
When this is the action, the type of
target
is theRole
or aObject
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 theRole
or aObject
with the ID.Possible attributes for
AuditLogDiff
:
- role_delete
A role was deleted.
When this is the action, the type of
target
is theRole
or aObject
with the ID.Possible attributes for
AuditLogDiff
:
- invite_create
An invite was created.
When this is the action, the type of
target
is theInvite
that was created.Possible attributes for
AuditLogDiff
:
- invite_update
An invite was updated.
When this is the action, the type of
target
is theInvite
that was updated.
- invite_delete
An invite was deleted.
When this is the action, the type of
target
is theInvite
that was deleted.Possible attributes for
AuditLogDiff
:
- webhook_create
A webhook was created.
When this is the action, the type of
target
is theObject
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 theObject
with the webhook ID.Possible attributes for
AuditLogDiff
:
- webhook_delete
A webhook was deleted.
When this is the action, the type of
target
is theObject
with the webhook ID.Possible attributes for
AuditLogDiff
:
- emoji_create
An emoji was created.
When this is the action, the type of
target
is theEmoji
orObject
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 theEmoji
orObject
with the emoji ID.Possible attributes for
AuditLogDiff
:
- emoji_delete
An emoji was deleted.
When this is the action, the type of
target
is theObject
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 someone other than the author.
When this is the action, the type of
target
is theMember
orUser
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
: ATextChannel
orObject
with the channel ID where the message got deleted.
- message_bulk_delete
Messages were bulk deleted by a moderator.
When this is the action, the type of
target
is theTextChannel
orObject
with the ID of the channel that was purged.When this is the action, the type of
extra
is set to an unspecified proxy object with one attribute:count
: An integer specifying how many messages were deleted.
New in version 1.3.
- message_pin
A message was pinned in a channel.
When this is the action, the type of
target
is theMember
orUser
who had their message pinned.When this is the action, the type of
extra
is set to an unspecified proxy object with two attributes:channel
: ATextChannel
orObject
with the channel ID where the message was pinned.message_id
: the ID of the message which was pinned.
New in version 1.3.
- message_unpin
A message was unpinned in a channel.
When this is the action, the type of
target
is theMember
orUser
who had their message unpinned.When this is the action, the type of
extra
is set to an unspecified proxy object with two attributes:channel
: ATextChannel
orObject
with the channel ID where the message was unpinned.message_id
: the ID of the message which was unpinned.
New in version 1.3.
- integration_create
A guild integration was created.
When this is the action, the type of
target
is theObject
with the integration ID of the integration which was created.New in version 1.3.
- class discord.AuditLogActionCategory
Represents the category that the
AuditLogAction
belongs to.This can be retrieved via
AuditLogEntry.category
.
- class discord.PremiumType
Represents the user’s Discord Nitro subscription type.
Deprecated since version 1.7.
Note
This only applies to users, not bots.
- class discord.Theme
Represents the theme synced across all Discord clients.
Deprecated since version 1.7.
Note
This only applies to users, not bots.
- class discord.TeamMembershipState
Represents the membership state of a team member retrieved through
Bot.application_info()
.New in version 1.3.
- class discord.TimestampStyle
The Styles you could use for the
style
of adiscord.utils.styled_timestamp()
See also in the Discord-Documentation
- class discord.ExpireBehaviour
Represents the behaviour the
Integration
should perform when a user’s subscription has finished.There is an alias for this called
ExpireBehavior
.New in version 1.4.
- class discord.DefaultAvatar
Represents the default avatar of a Discord
User
- blurple
Represents the default avatar with the color blurple. See also
Colour.blurple
- grey
Represents the default avatar with the color grey. See also
Colour.greyple
- gray
An alias for
grey
.
- green
Represents the default avatar with the color green. See also
Colour.green
- orange
Represents the default avatar with the color orange. See also
Colour.orange
- red
Represents the default avatar with the color red. See also
Colour.red
- class discord.EventEntityType
The location where a
GuildScheduledEvent
will be scheduled at
- class discord.EventStatus
The status of a
GuildScheduledEvent
Note
* Once
status
is set tocompleted
orcanceled
, thestatus
can no longer be updatedValid Guild Scheduled Event Status Transitions
scheduled
–>active
active
——–>completed
scheduled
–>canceled
- class discord.AutoModEventType
Indicates in what event context a
AutoModRule
should be checked.
- class discord.AutoModActionType
The type of action that should be taken in an
AutoModAction
.- timeout_user
Timeout the user for a specific duration
Note
This can only be used when the
trigger_type
iskeyword
- class discord.TextInputStyle
The style a
TextInput
should have- singleline
An aliase for
short
- multiline
An aliase for
paragraph
- class discord.OptionType
Option types for
SlashCommandOption
- string
A string (
str
)
- integer
Any integer between -2^53 and 2^53 (
int
)
- boolean
A boolean (
bool
)
- channel
Includes all channel types + categories
Note
To only accept specific channel types use
SlashCommandOption.channel_types
- role
A role (
Role
)
- number
Any double between -2^53 and 2^53 (
float
)
- attachment
An
Attachment
- class discord.PostSortOrder
Type used to order posts in
ForumChannel
channels.
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.
- await next()
This function is a coroutine.
Advances the iterator by one, if possible. If no more items are found then this raises
NoMoreItems
.
- await 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')
- await 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. Could be a coroutine.
- Returns:
The first element that returns
True
for the predicate orNone
.
- await 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:
- chunk(max_size)
Collects items into chunks of up to a given maximum size. Another
AsyncIterator
is returned which collects items intolist
s of a given size. The maximum chunk size must be a positive integer.New in version 1.6.
Collecting groups of users:
async for leader, *users in reaction.users().chunk(3): ...
Warning
The last chunk collected may not be as large as
max_size
.- Parameters:
max_size – The size of individual chunks.
- Return type:
- map(func)
This is similar to the built-in
map
function. AnotherAsyncIterator
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.
- Return type:
- filter(predicate)
This is similar to the built-in
filter
function. AnotherAsyncIterator
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.
- Return type:
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.
AuditLogEntry
- class discord.AuditLogEntry(*, users, data, guild)
Represents an Audit Log entry.
You retrieve these via
Guild.audit_logs()
.- x == y
Checks if two entries are equal.
- x != y
Checks if two entries are not equal.
- hash(x)
Returns the entry’s hash.
Changed in version 1.7: Audit log entries are now comparable and hashable.
- target
The target that got changed. The exact type of this depends on the action being done.
- Type:
Any
- reason
The reason this action was done.
- Type:
Optional[
str
]
- extra
Extra information that this entry has that might be useful. For most actions, this is
None
. However in some cases it contains extra information. SeeAuditLogAction
for which actions have this field filled out.- Type:
Any
- category
The category of the action, if applicable.
- Type:
Optional[
AuditLogActionCategory
]
AuditLogChanges
- class discord.AuditLogChanges
An audit log change set.
- before
The old value. The attribute has the type of
AuditLogDiff
.Depending on the
AuditLogActionCategory
retrieved bycategory
, the data retrieved by this attribute differs:
- after
The new value. The attribute has the type of
AuditLogDiff
.Depending on the
AuditLogActionCategory
retrieved bycategory
, the data retrieved by this attribute differs:
AuditLogDiff
- afk_channel
- afk_timeout
- allow
- avatar
- bitrate
- channel
- code
- color
- colour
- deaf
- default_message_notifications
- default_notifications
- deny
- explicit_content_filter
- hoist
- icon
- id
- inviter
- max_age
- max_uses
- mentionable
- mfa_level
- mute
- name
- nick
- overwrites
- owner
- permissions
- position
- region
- roles
- slowmode_delay
- splash
- system_channel
- temporary
- topic
- type
- uses
- vanity_url_code
- verification_level
- widget_channel
- widget_enabled
- 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)
Returns an iterator over (attribute, value) tuple of this diff.
- icon
A guild’s icon hash. See also
Guild.icon
.- Type:
- splash
The guild’s invite splash hash. See also
Guild.splash
.- Type:
- owner
The guild’s owner. See also
Guild.owner
- afk_channel
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
.- Type:
Union[
VoiceChannel
,Object
]
- system_channel
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
.- Type:
Union[
TextChannel
,Object
]
- afk_timeout
The guild’s AFK timeout. See
Guild.afk_timeout
.- Type:
- mfa_level
The guild’s MFA level. See
Guild.mfa_level
.- Type:
- widget_channel
The widget’s channel.
If this could not be found then it falls back to a
Object
with the ID being set.- Type:
Union[
TextChannel
,Object
]
- verification_level
The guild’s verification level.
See also
Guild.verification_level
.- Type:
- default_notifications
The guild’s default notification level.
See also
Guild.default_notifications
.- Type:
- explicit_content_filter
The guild’s content filter.
See also
Guild.explicit_content_filter
.- Type:
- vanity_url_code
The guild’s vanity URL.
See also
Guild.vanity_invite()
andGuild.edit()
.- Type:
- position
The position of a
Role
orabc.GuildChannel
.- Type:
- type
The type of channel or channel permission overwrite.
If the type is an
int
, then it is a type of channel which can be either0
to indicate a text channel or1
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
The topic of a
TextChannel
.See also
TextChannel.topic
.- Type:
- bitrate
The bitrate of a
VoiceChannel
.See also
VoiceChannel.bitrate
.- Type:
- overwrites
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
orUser
orRole
. If this object is not found then it is aObject
with an ID being filled and atype
attribute set to either'role'
or'member'
to help decide what type of ID it is.- Type:
List[Tuple[target,
PermissionOverwrite
]]
- roles
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
The nickname of a member.
See also
Member.nick
- Type:
Optional[
str
]
- deaf
Whether the member is being server deafened.
See also
VoiceState.deaf
.- Type:
- mute
Whether the member is being server muted.
See also
VoiceState.mute
.- Type:
- permissions
The permissions of a role.
See also
Role.permissions
.- Type:
- colour
- color
The colour of a role.
See also
Role.colour
- Type:
- hoist
Whether the role is being hoisted or not.
See also
Role.hoist
- Type:
- mentionable
Whether the role is mentionable or not.
See also
Role.mentionable
- Type:
- code
The invite’s code.
See also
Invite.code
- Type:
- channel
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.- Type:
Union[
abc.GuildChannel
,Object
]
- inviter
The user who created the invite.
See also
Invite.inviter
.- Type:
- max_uses
The invite’s max uses.
See also
Invite.max_uses
.- Type:
- uses
The invite’s current uses.
See also
Invite.uses
.- Type:
- max_age
The invite’s max age in seconds.
See also
Invite.max_age
.- Type:
- temporary
If the invite is a temporary invite.
See also
Invite.temporary
.- Type:
- avatar
The avatar hash of a member.
See also
User.avatar
.- Type:
- slowmode_delay
The number of seconds members have to wait before sending another message in the channel.
See also
TextChannel.slowmode_delay
.- Type:
Webhook Support
discord.py-message-components offers support for creating, editing, and executing webhooks through the Webhook
class.
Webhook
- clsWebhook.from_url
- clsWebhook.partial
- defavatar_url_as
- defdelete
- defdelete_message
- defedit
- defedit_message
- defexecute
- defsend
- 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()
andTextChannel.webhooks()
. The ones received by the library will automatically have an adapter bound using the library’s HTTP _session. Those webhooks will havesend()
,delete()
andedit()
as coroutines.The second form involves creating a webhook object manually without having it bound to a websocket connection using the
from_url()
orpartial()
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')
- x == y
Checks if two webhooks are equal.
- x != y
Checks if two webhooks are not equal.
- hash(x)
Returns the webhooks’s hash.
Changed in version 1.4: Webhooks are now comparable and hashable.
Changed in version 2.0: Added support for forum channels, threads, components, the ability to edit attachments and to suppress notifications.
- token
The authentication token of the webhook. If this is
None
then the webhook cannot be used to make requests.- Type:
Optional[
str
]
- guild_id
The guild ID this webhook is for.
- Type:
Optional[
int
]
- channel_id
The channel ID this webhook is for.
- Type:
Optional[
int
]
- user
The user this webhook was created by. If the webhook was received without authentication then this will be
None
.- Type:
Optional[
abc.User
]
- name
The default name of the webhook.
- Type:
Optional[
str
]
- avatar
The default avatar of the webhook.
- Type:
Optional[
str
]
- classmethod partial(id, token, *, adapter)
Creates a partial
Webhook
.- Parameters:
id (
int
) – The ID of the webhook.token (
str
) – The authentication token of the webhook.adapter (
WebhookAdapter
) – The webhook adapter to use when sending requests. This is typicallyAsyncWebhookAdapter
for aiohttp orRequestsWebhookAdapter
for requests.
- Returns:
A partial
Webhook
. A partial webhook is just a webhook object with an ID and a token.- Return type:
- classmethod from_url(url, *, adapter)
Creates a partial
Webhook
from a webhook URL.- Parameters:
url (
str
) – The URL of the webhook.adapter (
WebhookAdapter
) – The webhook adapter to use when sending requests. This is typicallyAsyncWebhookAdapter
for aiohttp orRequestsWebhookAdapter
for requests.
- Raises:
InvalidArgument – The URL is invalid.
- Returns:
A partial
Webhook
. A partial webhook is just a webhook object with an ID and a token.- Return type:
- property guild
The guild this webhook belongs to.
If this is a partial webhook, then this will always return
None
.- Type:
Optional[
Guild
]
- property channel
The text or forum channel this webhook belongs to.
If this is a partial webhook, then this will always return
None
.- Type:
Optional[
TextChannel
,ForumChannel
]
- property avatar_url
Returns an
Asset
for the avatar the webhook has.If the webhook does not have a traditional avatar, an asset for the default avatar is returned instead.
This is equivalent to calling
avatar_url_as()
with the default parameters.- Type:
- avatar_url_as(*, format=None, size=1024)
Returns an
Asset
for the avatar the webhook has.If the webhook does not have a traditional avatar, an asset for the default avatar 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:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- delete(*, reason=None)
This function could be a coroutine.
Deletes this Webhook.
If the webhook is constructed with a
RequestsWebhookAdapter
then this is not a coroutine.- Parameters:
reason (Optional[
str
]) –The reason for deleting this webhook. Shows up on the audit log.
New in version 1.4.
- Raises:
HTTPException – Deleting the webhook failed.
NotFound – This webhook does not exist.
Forbidden – You do not have permissions to delete this webhook.
InvalidArgument – This webhook does not have a token associated with it.
- edit(*, reason=None, **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.reason (Optional[
str
]) –The reason for editing this webhook. Shows up on the audit log.
New in version 1.4.
- Raises:
HTTPException – Editing the webhook failed.
NotFound – This webhook does not exist.
InvalidArgument – This webhook does not have a token associated with it.
- send(content=None, *, wait=False, thread_id=MISSING, thread_name=MISSING, username=MISSING, avatar_url=MISSING, tts=False, file=MISSING, files=MISSING, embed=MISSING, embeds=MISSING, components=MISSING, allowed_mentions=MISSING, suppress_embeds=False, suppress_notifications=False)
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)
.All parameters are optional but at least one of
content
,file
/files
,embed
/embeds
or if possiblecomponents
must be provided.If the webhook belongs to a
ForumChannel
then eitherthread_id``(to send the message to an existing post) or ``thread_name
(to create a new post) must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type..- Parameters:
content (
str
) – The content of the message to send.wait (
bool
) – Whether the server should wait before sending a response. This essentially means that the return type of this function changes fromNone
to aWebhookMessage
if set toTrue
.thread_id (
int
) –Send a message to the specified thread/forum-post within a webhook’s channel. The thread/forum-post will automatically be unarchived.
..versionadded:: 2.0
thread_name (
str
) –ForumChannel
webhooks only: Will create a new post with the webhook message will be the starter message...versionadded:: 2.0
username (
str
) – The username to send with this message. If no username is provided then the default username for the webhook is used.avatar_url (Union[
str
,Asset
]) – The avatar URL to send with this message. If no avatar URL is provided then the default avatar for the webhook is used.tts (
bool
) – Indicates if the message should be sent using text-to-speech.file (
File
) – The file to upload. This cannot be mixed withfiles
parameter.files (List[
File
]) – A list of files to send with the content. This cannot be mixed with thefile
parameter.embed (
Embed
) – The rich embed for the content to send. This cannot be mixed withembeds
parameter.embeds (List[
Embed
]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with theembed
parameter.components (List[Union[
ActionRow
, List[Union[Button
,SelectMenu
]]]]) –A list of components to include in the message.
Note
Due to discord limitations this can only be used when the Webhook was created by a bot.
New in version 2.0.
allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message.
New in version 1.4.
suppress_embeds (
bool
) –Whether to suppress embeds send with the message, defaults to
False
.New in version 2.0.
suppress_notifications (
bool
) –Whether to suppress desktop- & push-notifications for the message.
Users will still see a ping-symbol when they are mentioned in the message.
New in version 2.0.
- Raises:
HTTPException – Sending the message failed.
NotFound – This webhook was not found.
Forbidden – The authorization token for the webhook is incorrect.
InvalidArgument – The length of
embeds
was invalid or there was no token associated with this webhook.
- Returns:
The message that was sent.
- Return type:
Optional[
WebhookMessage
]
- execute(*args, **kwargs)
An alias for
send()
.
- edit_message(message_id, *, content=MISSING, embed=MISSING, embeds=MISSING, components=MISSING, attachments=MISSING, allowed_mentions=MISSING, suppress_embeds=MISSING)
This function could be a coroutine.
Edits a message owned by this webhook.
This is a lower level interface to
WebhookMessage.edit()
in case you only have an ID.Warning
Since API v10, the
attachments
(when passed) must contain all attachments that should be present after edit, including retained and new attachments.As this requires to know the current attachments consider either storing the attachments that were sent with a message or using a fetched version of the message to edit it.
New in version 1.6.
Changed in version 2.0: The
suppress
keyword-only parameter was renamed tosuppress_embeds
.- Parameters:
message_id (
int
) – The message ID to edit.content (Optional[
str
]) – The content to edit the message with orNone
to clear it.embed (Optional[
Embed
]) – The new embed to replace the original with. Could beNone
to remove all embeds.embeds (Optional[List[
Embed
]]) – A list containing up to 10 embeds. IfNone
empty, all embeds will be removed.components (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) –A list of up to five
Button
’s or oneBaseSelect
like object.Note
Due to discord limitations this can only be used when the webhook is owned by an application.
New in version 2.0.
attachments (List[Union[
Attachment
,File
]]) –A list containing previous attachments to keep as well as new files to upload.
When empty, all attachment will be removed.
Note
New files will always appear under existing ones.
New in version 2.0.
allowed_mentions (
AllowedMentions
) – Controls the mentions being processed in this message. Seeabc.Messageable.send()
for more information.suppress_embeds (
bool
) – Whether to suppress embeds send with the message.
- Raises:
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
InvalidArgument – The length of
embeds
was invalid or there was no token associated with this webhook.
- delete_message(message_id)
This function could be a coroutine.
Deletes a message owned by this webhook.
This is a lower level interface to
WebhookMessage.delete()
in case you only have an ID.New in version 1.6.
- Parameters:
message_id (
int
) – The message ID to delete.- Raises:
HTTPException – Deleting the message failed.
Forbidden – Deleted a message that is not yours.
WebhookMessage
- class discord.WebhookMessage(*, state, channel, data)
Represents a message sent from your webhook.
This allows you to edit or delete a message sent by your webhook.
This inherits from
discord.Message
with changes toedit()
anddelete()
to work.New in version 1.6.
- edit(*, content=MISSING, embed=MISSING, embeds=MISSING, components=MISSING, attachments=MISSING, keep_existing_attachments=False, allowed_mentions=MISSING, suppress_embeds=MISSING)
This function could be a coroutine.
Edits a message owned by this webhook.
This is a lower level interface to
WebhookMessage.edit()
in case you only have an ID.Warning
Since API v10, the
attachments
(when passed) must contain all attachments that should be present after edit, including retained and new attachments.As this requires to know the current attachments consider either storing the attachments that were sent with a message or using a fetched version of the message to edit it.
New in version 1.6.
Changed in version 2.0: The
suppress
keyword-only parameter was renamed tosuppress_embeds
.- Parameters:
content (Optional[
str
]) – The content to edit the message with orNone
to clear it.embed (Optional[
Embed
]) – The new embed to replace the original with. Could beNone
to remove all embeds.embeds (Optional[List[
Embed
]]) – A list containing up to 10 embeds. IfNone
empty, all embeds will be removed.components (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) –A list of up to five
Button
’s or oneBaseSelect
like object.Note
Due to discord limitations this can only be used when the webhook is owned by an application.
New in version 2.0.
attachments (List[Union[
Attachment
,File
]]) –A list containing previous attachments to keep as well as new files to upload.
When empty, all attachment will be removed.
Note
New files will always appear under existing ones.
New in version 2.0.
keep_existing_attachments (
bool
) –Whether to auto-add existing attachments to
attachments
, defaults toFalse
.Note
Only needed when
attachments
are passed, otherwise will be ignored.allowed_mentions (
AllowedMentions
) – Controls the mentions being processed in this message. Seeabc.Messageable.send()
for more information.suppress_embeds (
bool
) – Whether to suppress embeds send with the message.
- Raises:
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
InvalidArgument – The length of
embeds
was invalid or there was no token associated with this webhook.
- delete(*, delay=None)
This function is a coroutine.
Deletes the message.
- Parameters:
delay (Optional[
float
]) – If provided, the number of seconds to wait before deleting the message. If this is a coroutine, the waiting is done in the background and deletion failures are ignored. If this is not a coroutine then the delay blocks the thread.- Raises:
Forbidden – You do not have proper permissions to delete the message.
NotFound – The message was deleted already.
HTTPException – Deleting the message failed.
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.
- request(verb, url, payload=None, multipart=None, **kwargs)
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 afile
key which will have a 3-elementtuple
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.
- await request(verb, url, payload=None, multipart=None, *, files=None, reason=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 afile
key which will have a 3-elementtuple
denoting(filename, file, content_type)
.payload (Optional[
dict
]) – The JSON to send with the request, if any.
- await handle_execution_response(response, *, wait)
Transforms the webhook execution response into something more meaningful.
This is mainly used to convert the data into a
Message
if necessary.Subclasses must implement this.
- Parameters:
data – The data that was returned from the request.
wait (
bool
) – Whether the webhook execution was asked to wait or not.
- class discord.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 toTrue
. If set toFalse
then this will raise anHTTPException
instead.
- request(verb, url, payload=None, multipart=None, *, files=None, reason=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 afile
key which will have a 3-elementtuple
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.
Snowflake
- class discord.abc.Snowflake
An ABC that details the common operations on a Discord model.
Almost all Discord models meet this abstract base class.
If you want to create a snowflake on your own, consider using
Object
.
User
- class discord.abc.User
An ABC that details the common operations on a Discord user.
The following implement this ABC:
This ABC must also implement
Snowflake
.- avatar
The avatar hash the user has.
- Type:
Optional[
str
]
PrivateChannel
- class discord.abc.PrivateChannel
An ABC that details the common operations on a private Discord channel.
The following implement this ABC:
This ABC must also implement
Snowflake
.
GuildChannel
- asyncclone
- asynccreate_invite
- asyncdelete
- asyncinvites
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncset_permissions
- class discord.abc.GuildChannel
An ABC that details the common operations on a Discord guild channel.
The following implement this ABC:
This ABC must also implement
Snowflake
.- position
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type:
- property changed_roles
Returns a list of roles that have been overridden from their default values in the
roles
attribute.- Type:
List[
Role
]
- overwrites_for(obj)
Returns the channel-specific overwrites for a member or a role.
- property overwrites
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Role
or aMember
and the value is the overwrite as aPermissionOverwrite
.- Returns:
The channel’s permission overwrites.
- Return type:
Mapping[Union[
Role
,Member
],PermissionOverwrite
]
- property category
The category this channel belongs to.
If there is no category then this is
None
.- Type:
Optional[
CategoryChannel
]
- property permissions_synced
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False
.New in version 1.3.
- Type:
- 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:
- await delete(*, reason=None)
This function is a coroutine.
Deletes the channel.
You must have
manage_channels
permission to use this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await set_permissions(target, *, overwrite=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 aMember
or aRole
that belongs to guild.The
overwrite
parameter, if given, must either beNone
orPermissionOverwrite
. For convenience, you can pass in keyword arguments denotingPermissions
attributes. If this is done, then you cannot mix the keyword arguments with theoverwrite
parameter.If the
overwrite
parameter isNone
, then the permission overwrites are deleted.You must have the
manage_roles
permission to use this.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwrite
overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (Union[
Member
,Role
]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite
]) – The permissions to allow and deny to the target, orNone
to delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite
.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
InvalidArgument – The overwrite parameter invalid or the target type was not
Role
orMember
.
- await clone(*, name=None, reason=None)
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channels
permission to do this.New in version 1.1.
- Parameters:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- await move(**kwargs)
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
edit()
should be used instead.You must have the
manage_channels
permission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
- Parameters:
beginning (
bool
) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend
,before
, andafter
.end (
bool
) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning
,before
, andafter
.before (
Snowflake
) – The channel that should be before our current channel. This is mutually exclusive withbeginning
,end
, andafter
.after (
Snowflake
) – The channel that should be after our current channel. This is mutually exclusive withbeginning
,end
, andbefore
.offset (
int
) – The number of channels to offset the move by. For example, an offset of2
withbeginning=True
would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning
,end
,before
, andafter
parameters.category (Optional[
Snowflake
]) – The category to move this channel under. IfNone
is given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool
) – Whether to sync the permissions with the category (if given).reason (
str
) – The reason for the move.
- Raises:
InvalidArgument – An invalid position was given or a bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- await create_invite(*, reason=None, **fields)
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invite
permission to do this.- Parameters:
max_age (Optional[
int
]) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0
.max_uses (Optional[
int
]) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0
.temporary (Optional[
bool
]) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse
.unique (Optional[
bool
]) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalse
then it will return a previously created invite.target_type (Optional[
int
]) – The type of target for this voice channel invite.1
for stream and2
for embedded-application.target_user_id (Optional[
int
]) – The id of theUser
whose stream to display for this invite, required iftarget_type
is1
, the user must be streaming in the channel.target_application_id (Optional[
int
]) – The id of the embedded application to open for this invite, required iftarget_type
is2
, the application must have the EMBEDDED flag.reason (Optional[
str
]) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The invite that was created.
- Return type:
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channels
to get this information.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite
]
Messageable
- asyncfetch_message
- defhistory
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
- class discord.abc.Messageable
An ABC that details the common operations on a model that can send messages.
The following implement this ABC:
Context
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
Returns an
AsyncIterator
that enables receiving the destination’s message history.You must have
read_message_history
permissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of messages to retrieve. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) – If set toTrue
, return messages in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message
– The message with the message data parsed.
- async with typing()
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
Note
This is both a regular context manager and an async context manager. This means that both
with
andasync with
work with this.Example Usage:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
- await send(content=None, *, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set toNone
(the default), then theembed
parameter must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type.- Parameters:
content (
str
) – The content of the message to send.tts (
bool
) – Indicates if the message should be sent using text-to-speech.embed (
Embed
) – The rich embed for the content.embeds (List[
Embed
]) – A list containing up to ten embedscomponents (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) – A list of up to fiveButton
’s or oneBaseSelect
like object.file (
File
) – The file to upload.files (List[
File
]) – Alist
of files to upload. Must be a maximum of 10.stickers (List[
GuildSticker
]) – A list of up to 3discord.GuildSticker
that should be sent with the message.nonce (
int
) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
]) –A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
suppress_embeds (
bool
) – Whether to supress embeds send with the message, default toFalse
suppress_notifications (
bool
) –Whether to suppress desktop- & push-notifications for this message, default to
False
Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.
New in version 2.0.
- 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, you specified bothfile
andfiles
, or thereference
object is not aMessage
orMessageReference
.
- Returns:
The message that was sent.
- Return type:
- await trigger_typing()
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- await fetch_message(id)
This function is a coroutine.
Retrieves a single
Message
from the destination.This can only be used by bot accounts.
- Parameters:
id (
int
) – The message ID to look for.- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- Returns:
The message asked for.
- Return type:
- await pins()
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Message
objects returned by this method do not contain completeMessage.reactions
data.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message
]
Connectable
Discord Models
Models are classes that are received from Discord and are not meant to be created by the user of the library.
Danger
The classes listed below are not intended to be created by users and are also read-only.
For example, this means that you should not make your own User
instances
nor should you modify the User
instance yourself.
If you want to get one of these model classes instances they’d have to be through
the cache, and a common way of doing so is through the utils.find()
function
or attributes of model classes that you receive from the events specified in the
Event Reference.
Note
Nearly all classes here have __slots__ defined which means that it is impossible to have dynamic attributes to the data classes.
ClientUser
- defavatar_url_as
- defbanner_url_as
- asyncedit
- defis_avatar_animated
- defis_banner_animated
- defmentioned_in
- defpermissions_in
- 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.
- avatar
The avatar hash the user has. Could be
None
.- Type:
Optional[
str
]
- locale
The IETF language tag used to identify the language the user is using.
- Type:
Optional[
str
]
- await edit(**fields)
This function is a coroutine.
Edits the current profile of the client.
Note
To upload an avatar, a bytes-like object must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via
open('some_filename', 'rb')
and the bytes-like object is given through the use offp.read()
.The only image formats supported for uploading is JPEG and PNG.
- Parameters:
username (
str
) – The new username you wish to change to.avatar (
bytes
) – A bytes-like object representing the image to upload. Could beNone
to denote no avatar.
- Raises:
HTTPException – Editing your profile failed.
InvalidArgument – Wrong image format passed for
avatar
.
- property avatar_url
Returns an
Asset
for the avatar the user has.If the user does not have a traditional avatar, an asset for the default avatar is returned instead.
This is equivalent to calling
avatar_url_as()
with the default parameters (i.e. webp/gif detection and a size of 1024).- Type:
- avatar_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the avatar the user has.If the user does not have a traditional avatar, an asset for the default avatar is returned instead.
The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the avatar to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the avatar being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
, or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- property banner_url
Returns an asset for the banner the user has, if any. This is equal to calling
banner_url_as()
with the default arguments.
- banner_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the banner the user has. Could beNone
.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated banners. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the banner to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the banner being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated banner to. Defaults to ‘webp’size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
, or invalidsize
.- Returns:
The resulting CDN asset if any.
- Return type:
Optional[
Asset
]
- property color
A property that returns a color denoting the rendered color for the user. This always returns
Colour.default()
.There is an alias for this named
colour
.- Type:
- property colour
A property that returns a colour denoting the rendered colour for the user. This always returns
Colour.default()
.There is an alias for this named
color
.- Type:
- property created_at
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
- Type:
- property default_avatar
Returns the default avatar for a given user. This is calculated by the user’s discriminator.
- Type:
- property 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.
- Type:
- is_avatar_animated()
bool
: Indicates if the user has an animated avatar.
- is_banner_animated()
bool
: Indicates if the user has an animated banner.
- permissions_in(channel)
An alias for
abc.GuildChannel.permissions_for()
.Basically equivalent to:
channel.permissions_for(self)
- Parameters:
channel (
abc.GuildChannel
) – The channel to check your permissions for.
User
- defavatar_url_as
- defbanner_url_as
- asynccreate_dm
- asyncfetch_message
- defhistory
- defis_avatar_animated
- defis_banner_animated
- defmentioned_in
- defpermissions_in
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
- 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.
- avatar
The avatar hash the user has. Could be None.
- Type:
Optional[
str
]
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
Returns an
AsyncIterator
that enables receiving the destination’s message history.You must have
read_message_history
permissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of messages to retrieve. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) – If set toTrue
, return messages in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message
– The message with the message data parsed.
- async with typing()
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
Note
This is both a regular context manager and an async context manager. This means that both
with
andasync with
work with this.Example Usage:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
- property dm_channel
Returns the channel associated with this user if it exists.
If this returns
None
, you can create a DM channel by calling thecreate_dm()
coroutine function.- Type:
Optional[
DMChannel
]
- property mutual_guilds
The guilds that the user shares with the client.
Note
This will only return mutual guilds within the client’s internal cache.
New in version 1.7.
- Type:
List[
Guild
]
- await create_dm()
This function is a coroutine.
Creates a
DMChannel
with this user.This should be rarely called, as this is done transparently for most people.
- Returns:
The channel that was created.
- Return type:
- property avatar_url
Returns an
Asset
for the avatar the user has.If the user does not have a traditional avatar, an asset for the default avatar is returned instead.
This is equivalent to calling
avatar_url_as()
with the default parameters (i.e. webp/gif detection and a size of 1024).- Type:
- avatar_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the avatar the user has.If the user does not have a traditional avatar, an asset for the default avatar is returned instead.
The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the avatar to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the avatar being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
, or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- property banner_url
Returns an asset for the banner the user has, if any. This is equal to calling
banner_url_as()
with the default arguments.
- banner_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the banner the user has. Could beNone
.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated banners. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the banner to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the banner being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated banner to. Defaults to ‘webp’size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
, or invalidsize
.- Returns:
The resulting CDN asset if any.
- Return type:
Optional[
Asset
]
- property color
A property that returns a color denoting the rendered color for the user. This always returns
Colour.default()
.There is an alias for this named
colour
.- Type:
- property colour
A property that returns a colour denoting the rendered colour for the user. This always returns
Colour.default()
.There is an alias for this named
color
.- Type:
- property created_at
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
- Type:
- property default_avatar
Returns the default avatar for a given user. This is calculated by the user’s discriminator.
- Type:
- property 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.
- Type:
- await fetch_message(id)
This function is a coroutine.
Retrieves a single
Message
from the destination.This can only be used by bot accounts.
- Parameters:
id (
int
) – The message ID to look for.- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- Returns:
The message asked for.
- Return type:
- is_avatar_animated()
bool
: Indicates if the user has an animated avatar.
- is_banner_animated()
bool
: Indicates if the user has an animated banner.
- permissions_in(channel)
An alias for
abc.GuildChannel.permissions_for()
.Basically equivalent to:
channel.permissions_for(self)
- Parameters:
channel (
abc.GuildChannel
) – The channel to check your permissions for.
- await pins()
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Message
objects returned by this method do not contain completeMessage.reactions
data.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message
]
- await send(content=None, *, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set toNone
(the default), then theembed
parameter must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type.- Parameters:
content (
str
) – The content of the message to send.tts (
bool
) – Indicates if the message should be sent using text-to-speech.embed (
Embed
) – The rich embed for the content.embeds (List[
Embed
]) – A list containing up to ten embedscomponents (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) – A list of up to fiveButton
’s or oneBaseSelect
like object.file (
File
) – The file to upload.files (List[
File
]) – Alist
of files to upload. Must be a maximum of 10.stickers (List[
GuildSticker
]) – A list of up to 3discord.GuildSticker
that should be sent with the message.nonce (
int
) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
]) –A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
suppress_embeds (
bool
) – Whether to supress embeds send with the message, default toFalse
suppress_notifications (
bool
) –Whether to suppress desktop- & push-notifications for this message, default to
False
Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.
New in version 2.0.
- 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, you specified bothfile
andfiles
, or thereference
object is not aMessage
orMessageReference
.
- Returns:
The message that was sent.
- Return type:
- await trigger_typing()
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
Attachment
- defis_spoiler
- asyncread
- asyncsave
- defto_dict
- asyncto_file
- class discord.Attachment
Represents an attachment from Discord.
- str(x)
Returns the URL of the attachment.
- x == y
Checks if the attachment is equal to another attachment.
- x != y
Checks if the attachment is not equal to another attachment.
- hash(x)
Returns the hash of the attachment.
Changed in version 1.7: Attachment can now be casted to
str
and is hashable.- height
The attachment’s height, in pixels. Only applicable to images and videos.
- Type:
Optional[
int
]
- width
The attachment’s width, in pixels. Only applicable to images and videos.
- Type:
Optional[
int
]
- url
The attachment URL. If the message this attachment was attached to is deleted, then this will 404.
- Type:
- proxy_url
The proxy URL. This is a cached version of the
url
in the case of images. When the message is deleted, this URL might be valid for a few minutes or not valid at all.- Type:
- content_type
The attachment’s media type
- Type:
Optional[
str
]
- description
The description for the file.
- Type:
Optional[
str
]
- is_spoiler()
bool
: Whether this attachment contains a spoiler.
- to_dict()
dict
: A minimal dictionary containing the filename and description of the attachment.
- await save(fp, *, seek_begin=True, use_cached=False)
This function is a coroutine.
Saves this attachment into a file-like object.
- Parameters:
fp (Union[
io.BufferedIOBase
,os.PathLike
]) – The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead.seek_begin (
bool
) – Whether to seek to the beginning of the file after saving is successfully done.use_cached (
bool
) – Whether to useproxy_url
rather thanurl
when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.
- Raises:
HTTPException – Saving the attachment failed.
NotFound – The attachment was deleted.
- Returns:
The number of bytes written.
- Return type:
- await read(*, use_cached=False)
This function is a coroutine.
Retrieves the content of this attachment as a
bytes
object.New in version 1.1.
- Parameters:
use_cached (
bool
) – Whether to useproxy_url
rather thanurl
when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.- Raises:
HTTPException – Downloading the attachment failed.
Forbidden – You do not have permissions to access this attachment
NotFound – The attachment was deleted.
- Returns:
The contents of the attachment.
- Return type:
- await to_file(*, use_cached=False, spoiler=False, description=MISSING)
This function is a coroutine.
Converts the attachment into a
File
suitable for sending viaabc.Messageable.send()
.New in version 1.3.
- Parameters:
use_cached (
bool
) –Whether to use
proxy_url
rather thanurl
when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments.New in version 1.4.
spoiler (
bool
) –Whether the file is a spoiler.
New in version 1.4.
description (
bool
) –The description (alt text) for the file.
This will be default to the
description
. Set the value toNone
to supress this. .. versionadded:: 2.0
- Raises:
HTTPException – Downloading the attachment failed.
Forbidden – You do not have permissions to access this attachment
NotFound – The attachment was deleted.
- Returns:
The attachment as a file suitable for sending.
- Return type:
Asset
- class discord.Asset
Represents a CDN asset on Discord.
- str(x)
Returns the URL of the CDN asset.
- len(x)
Returns the length of the CDN asset’s URL.
- bool(x)
Checks if the Asset has a URL.
- x == y
Checks if the asset is equal to another asset.
- x != y
Checks if the asset is not equal to another asset.
- hash(x)
Returns the hash of the asset.
- await read()
This function is a coroutine.
Retrieves the content of this asset as a
bytes
object.Warning
PartialEmoji
won’t have a connection state if user created, and a URL won’t be present if a custom image isn’t associated with the asset, e.g. a guild with no custom icon.New in version 1.1.
- Raises:
DiscordException – There was no valid URL or internal connection state.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns:
The content of the asset.
- Return type:
- await save(fp, *, seek_begin=True)
This function is a coroutine.
Saves this asset into a file-like object.
- Parameters:
fp (Union[BinaryIO,
os.PathLike
]) – Same as inAttachment.save()
.seek_begin (
bool
) – Same as inAttachment.save()
.
- Raises:
DiscordException – There was no valid URL or internal connection state.
HTTPException – Downloading the asset failed.
NotFound – The asset was deleted.
- Returns:
The number of bytes written.
- Return type:
Message
- activity
- all_buttons
- all_components
- all_select_menus
- application
- attachments
- author
- channel
- channel_mentions
- clean_content
- components
- content
- created_at
- edited_at
- embeds
- flags
- guild
- id
- jump_url
- mention_everyone
- mentions
- nonce
- pinned
- raw_channel_mentions
- raw_mentions
- raw_role_mentions
- reactions
- reference
- role_mentions
- stickers
- system_content
- thread
- tts
- type
- webhook_id
- asyncadd_reaction
- asyncclear_reaction
- asyncclear_reactions
- asynccreate_thread
- asyncdelete
- asyncedit
- defis_system
- asyncpin
- asyncpublish
- asyncremove_reaction
- asyncreply
- defto_reference
- asyncunpin
- class discord.Message
Represents a message from Discord.
- x == y
Checks if two messages are equal.
- x != y
Checks if two messages are not equal.
- hash(x)
Returns the message’s hash.
- tts
Specifies if the message was done with text-to-speech. This can only be accurately received in
on_message()
due to a discord limitation.- Type:
- type
The type of message. In most cases this should not be checked, but it is helpful in cases where it might be a system message for
system_content
.- Type:
- author
A
Member
that sent the message. Ifchannel
is a private channel or the user has left the guild, then it is aUser
instead.- Type:
- nonce
The value used by the discord guild and the client to verify that the message is successfully sent. This is not stored long term within Discord’s servers and is only used ephemerally.
- embeds
A list of embeds the message has.
- Type:
List[
Embed
]
- components
A list of components the message has.
- Type:
List[
ActionRow
]:
- channel
The
TextChannel
,ThreadChannel
orVoiceChannel
that the message was sent from. Could be aDMChannel
orGroupChannel
if it’s a private message.- Type:
Union[
abc.Messageable
,ThreadChannel
]
- reference
The message that this message references. This is only applicable to messages of type
MessageType.pins_add
, crossposted messages created by a followed channel integration, or message replies.New in version 1.5.
- Type:
Optional[
MessageReference
]
- mention_everyone
Specifies if the message mentions everyone.
Note
This does not check if the
@everyone
or the@here
text is in the message itself. Rather this boolean indicates if either the@everyone
or the@here
text is in the message and it did end up mentioning.- Type:
- mentions
A list of
Member
that were mentioned. If the message is in a private message then the list will be ofUser
instead. For messages that are not of typeMessageType.default
, this array can be used to aid in system messages. For more information, seesystem_content
.Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
- Type:
List[
abc.User
]
- channel_mentions
A list of
abc.GuildChannel
that were mentioned. If the message is in a private message then the list is always empty.- Type:
List[
abc.GuildChannel
]
- role_mentions
A list of
Role
that were mentioned. If the message is in a private message then the list is always empty.- Type:
List[
Role
]
- webhook_id
If this message was sent by a webhook, then this is the webhook ID’s that sent this message.
- Type:
Optional[
int
]
- attachments
A list of attachments given to a message.
- Type:
List[
Attachment
]
- reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
- Type:
List[
Reaction
]
- activity
The activity associated with this message. Sent with Rich-Presence related messages that for example, request joining, spectating, or listening to or with another member.
It is a dictionary with the following optional keys:
type
: An integer denoting the type of message activity being requested.party_id
: The party ID associated with the party.
- Type:
Optional[
dict
]
- application
The rich presence enabled application associated with this message.
It is a dictionary with the following keys:
id
: A string representing the application’s ID.name
: A string representing the application’s name.description
: A string representing the application’s description.icon
: A string representing the icon ID of the application.cover_image
: A string representing the embed’s image asset ID.
- Type:
Optional[
dict
]
- stickers
A list of stickers given to the message.
New in version 1.6.
- Type:
List[
Sticker
]
- guild
The guild that the message belongs to, if applicable.
- Type:
Optional[
Guild
]
- raw_mentions
A property that returns an array of user IDs matched with the syntax of
<@user_id>
in the message content.This allows you to receive the user IDs of mentioned users even in a private message context.
- Type:
List[
int
]
- raw_channel_mentions
A property that returns an array of channel IDs matched with the syntax of
<#channel_id>
in the message content.- Type:
List[
int
]
- raw_role_mentions
A property that returns an array of role IDs matched with the syntax of
<@&role_id>
in the message content.- Type:
List[
int
]
- clean_content
A property that returns the content in a “cleaned up” manner. This basically means that mentions are transformed into the way the client shows it. e.g.
<#id>
will transform into#name
.This will also transform @everyone and @here mentions into non-mentions.
Note
This does not affect markdown. If you want to escape or remove markdown then use
utils.escape_markdown()
orutils.remove_markdown()
respectively, along with this function.- Type:
- property edited_at
A naive UTC datetime object containing the edited time of the message.
- Type:
Optional[
datetime.datetime
]
- is_system()
bool
: Whether the message is a system message.New in version 1.3.
- system_content
A property that returns the content that is rendered regardless of the
Message.type
.In the case of
MessageType.default
, this just returns the regularMessage.content
. Otherwise this returns an English message denoting the contents of the system message.- Type:
- property all_components
Returns all
Button
’s andSelectMenu
’s that are contained in the message
- property all_buttons
Returns all
Button
’s that are contained in the message
Returns all
SelectMenu
’s that are contained in the message
- property thread
The thread that belongs to this message, if there is one
- Type:
Optional[
ThreadChannel
]
- await delete(*, delay=None)
This function is a coroutine.
Deletes the message.
Your own messages could be deleted without any proper permissions. However, to delete other people’s messages, you need the
manage_messages
permission.Changed in version 1.1: Added the new
delay
keyword-only parameter.- Parameters:
delay (Optional[
float
]) – If provided, the number of seconds to wait in the background before deleting the message. If the deletion fails then it is silently ignored.- Raises:
Forbidden – You do not have proper permissions to delete the message.
NotFound – The message was deleted already
HTTPException – Deleting the message failed.
- await edit(*, content=MISSING, embed=MISSING, embeds=MISSING, components=MISSING, attachments=MISSING, keep_existing_attachments=False, delete_after=None, allowed_mentions=MISSING, suppress_embeds=MISSING)
This function is a coroutine.
Edits the message.
The content must be able to be transformed into a string via
str(content)
.Warning
Since API v10, the
attachments
must contain all attachments that should be present after edit, including retained and new attachments.Changed in version 1.3: The
suppress
keyword-only parameter was added.Changed in version 2.0: The
suppress
keyword-only parameter was renamed tosuppress_embeds
.Changed in version 2.0: The
components`, ``attachments
andkeep_existing_attachments
keyword-only parameters were added.- Parameters:
content (Optional[
str
]) – The new content to replace the message with. Could beNone
to remove the content.embed (Optional[
Embed
]) – The new embed to replace the original with. Could beNone
to remove all embeds.embeds (Optional[List[
Embed
]]) –A list containing up to 10 embeds`to send. If
None
or empty, all embeds will be removed.If passed,
embed
does also count towards the limit of 10 embeds.components (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) – A list of up to fiveButton
’s or oneBaseSelect
like object.attachments (List[Union[
Attachment
,File
]]) –A list containing previous attachments to keep as well as new files to upload. You can use
keep_existing_attachments
to auto-add the existing attachments to the list. IfNone
or empty, all attachments will be removed.Note
New files will always appear under existing ones.
keep_existing_attachments (
bool
) –Whether to auto-add existing attachments to
attachments
, defaults toFalse
.Note
Only needed when
attachments
are passed, otherwise will be ignored.suppress_embeds (
bool
) – Whether to suppress embeds for the message. This removes all the embeds if set toTrue
. If set toFalse
this brings the embeds back if they were suppressed. Requiresmanage_messages
permissions for messages that aren’t from the bot.delete_after (Optional[
float
]) – If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.allowed_mentions (Optional[
AllowedMentions
]) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
- Raises:
HTTPException – Editing the message failed.
Forbidden – Tried to suppress a message without permissions or edited a message’s content or embed that isn’t yours.
- await publish()
This function is a coroutine.
Publishes this message to your announcement channel.
If the message is not your own then the
manage_messages
permission is needed.- Raises:
Forbidden – You do not have the proper permissions to publish this message.
HTTPException – Publishing the message failed.
- await pin(*, reason=None)
This function is a coroutine.
Pins the message.
You must have the
manage_messages
permission to do this in a non-private channel context.- Parameters:
reason (Optional[
str
]) –The reason for pinning the message. Shows up on the audit log.
New in version 1.4.
- Raises:
Forbidden – You do not have permissions to pin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Pinning the message failed, probably due to the channel having more than 50 pinned messages.
- await unpin(*, reason=None)
This function is a coroutine.
Unpins the message.
You must have the
manage_messages
permission to do this in a non-private channel context.- Parameters:
reason (Optional[
str
]) –The reason for unpinning the message. Shows up on the audit log.
New in version 1.4.
- Raises:
Forbidden – You do not have permissions to unpin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Unpinning the message failed.
- await add_reaction(emoji)
This function is a coroutine.
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild
Emoji
.You must have the
read_message_history
permission to use this. If nobody else has reacted to the message using this emoji, theadd_reactions
permission is required.- Parameters:
emoji (Union[
Emoji
,Reaction
,PartialEmoji
,str
]) – The emoji to react with.- Raises:
HTTPException – Adding the reaction failed.
Forbidden – You do not have the proper permissions to react to the message.
NotFound – The emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- await remove_reaction(emoji, member)
This function is a coroutine.
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild
Emoji
.If the reaction is not your own (i.e.
member
parameter is not you) then themanage_messages
permission is needed.The
member
parameter must represent a member and meet theabc.Snowflake
abc.- Parameters:
emoji (Union[
Emoji
,Reaction
,PartialEmoji
,str
]) – The emoji to remove.member (
abc.Snowflake
) – The member for which to remove the reaction.
- Raises:
HTTPException – Removing the reaction failed.
Forbidden – You do not have the proper permissions to remove the reaction.
NotFound – The member or emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- await clear_reaction(emoji)
This function is a coroutine.
Clears a specific reaction from the message.
The emoji may be a unicode emoji or a custom guild
Emoji
.You need the
manage_messages
permission to use this.New in version 1.3.
- Parameters:
emoji (Union[
Emoji
,Reaction
,PartialEmoji
,str
]) – The emoji to clear.- Raises:
HTTPException – Clearing the reaction failed.
Forbidden – You do not have the proper permissions to clear the reaction.
NotFound – The emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- await clear_reactions()
This function is a coroutine.
Removes all the reactions from the message.
You need the
manage_messages
permission to use this.- Raises:
HTTPException – Removing the reactions failed.
Forbidden – You do not have the proper permissions to remove all the reactions.
- await reply(content=None, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)
This function is a coroutine.
A shortcut method to
abc.Messageable.send()
to reply to theMessage
.New in version 1.6.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
files
list is not of the appropriate size or you specified bothfile
andfiles
.
- Returns:
The message that was sent.
- Return type:
- await create_thread(name, auto_archive_duration=None, slowmode_delay=0, reason=None)
This function is a coroutine.
Creates a new thread in the channel of the message with this message as the
starter_message
.- Parameters:
name (
str
) – The name of the thread.auto_archive_duration (Optional[
AutoArchiveDuration
]) – Amount of time after that the thread will auto-hide from the channel listslowmode_delay (
int
) – Amount of seconds a user has to wait before sending another message (0-21600)reason (Optional[
str
]) – The reason for creating the thread. Shows up in the audit log.
- Raises:
TypeError – The channel of the message is not a text or news channel, or the message has already a thread, or
auto_archive_duration
is not a valid member ofAutoArchiveDuration
ValueError – The
name
is of invalid lengthForbidden – The bot is missing permissions to create threads in this channel
HTTPException – Creating the thread failed
- Returns:
The created thread on success
- Return type:
- to_reference(*, fail_if_not_exists=True)
Creates a
MessageReference
from the current message.New in version 1.6.
- Parameters:
fail_if_not_exists (
bool
) –Whether replying using the message reference should raise
HTTPException
if the message no longer exists or Discord could not fetch the message.New in version 1.7.
- Returns:
The reference to this message.
- Return type:
- class discord.EphemeralMessage
Like a normal
Message
but with a modifiededit()
method and withoutdelete()
method.- guild
The guild that the message belongs to, if applicable.
- Type:
Optional[
Guild
]
- property all_components
Returns all
Button
’s andSelectMenu
’s that are contained in the message
- property all_buttons
Returns all
Button
’s that are contained in the message
Returns all
SelectMenu
’s that are contained in the message
- await edit(*, content=MISSING, embed=MISSING, embeds=MISSING, components=MISSING, attachments=MISSING, keep_existing_attachments=False, allowed_mentions=MISSING, suppress=False, delete_after=None)
This function is a coroutine.
Edits the message.
- Parameters:
content (Optional[
str
]) – The new content to replace the message with. Could beNone
to remove the content.embed (Optional[
Embed
]) – The new embed to replace the original with. Could beNone
to remove all embeds.embeds (Optional[List[
Embed
]]) –A list containing up to 10 embeds`to send. If
None
or empty, all embeds will be removed.If passed,
embed
does also count towards the limit of 10 embeds.components (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) – A list of up to fiveButton
’s or oneBaseSelect
like object.attachments (List[Union[
Attachment
,File
]]) –A list containing previous attachments to keep as well as new files to upload. You can use
keep_existing_attachments
to auto-add the existing attachments to the list. If an empty list ([]
) is passed, all attachment will be removed.Note
New files will always appear under existing ones.
keep_existing_attachments (
bool
) –Whether to auto-add existing attachments to
attachments
, defaultFalse
.Note
Only needed when
attachments
are passed, otherwise will be ignored.suppress (
bool
) – Whether to suppress embeds for the message. IfTrue
this will remove all embeds from the message. If ´False` it adds them back.delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the response we just edited. If the deletion fails, then it is silently ignored.allowed_mentions (Optional[
AllowedMentions
]) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.
- await delete(*, delay=None)
This function is a coroutine.
Deletes the message.
Note
This can only be used while the interaction token is valid. So within 15 minutes after the interaction.
- Parameters:
delay (Optional[
float
]) – If provided, the number of seconds to wait in the background before deleting the message. If the deletion fails then it is silently ignored.- Raises:
NotFound – The message was deleted already or the interaction token expired
HTTPException – Deleting the message failed.
DeletedReferencedMessage
- class discord.DeletedReferencedMessage
A special sentinel type that denotes whether the resolved message referenced message had since been deleted.
The purpose of this class is to separate referenced messages that could not be fetched and those that were previously fetched but have since been deleted.
New in version 1.6.
- property guild_id
The guild ID of the deleted referenced message.
- Type:
Optional[
int
]
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
The reaction emoji. May be a custom emoji, or a unicode emoji.
- Type:
Union[
Emoji
,PartialEmoji
,str
]
- async for ... in users(limit=None, after=None)
Returns an
AsyncIterator
representing the users that have reacted to the message.The
after
parameter must represent a member and meet theabc.Snowflake
abc.Examples
Usage
# I do not actually recommend doing this. async for user in reaction.users(): await channel.send('{0} has reacted with {1.emoji}!'.format(user, reaction))
Flattening into a list:
users = await reaction.users().flatten() # users is now a list of User... winner = random.choice(users) await channel.send('{} has won the raffle.'.format(winner))
- Parameters:
limit (
int
) – The maximum number of results to return. If not provided, returns all the users who reacted to the message.after (
abc.Snowflake
) – For pagination, reactions are sorted by member.
- Raises:
HTTPException – Getting the users for the reaction failed.
- Yields:
Union[
User
,Member
] – The member (if retrievable) or the user that has reacted to this message. The case where it can be aMember
is in a guild message context. Sometimes it can be aUser
if the member has left the guild.
- await remove(user)
This function is a coroutine.
Remove the reaction by the provided
User
from the message.If the reaction is not your own (i.e.
user
parameter is not you) then themanage_messages
permission is needed.The
user
parameter must represent a user or member and meet theabc.Snowflake
abc.- Parameters:
user (
abc.Snowflake
) – The user or member from which to remove the reaction.- Raises:
HTTPException – Removing the reaction failed.
Forbidden – You do not have the proper permissions to remove the reaction.
NotFound – The user you specified, or the reaction’s message was not found.
- await clear()
This function is a coroutine.
Clears this reaction from the message.
You need the
manage_messages
permission to use this.New in version 1.3.
- Raises:
HTTPException – Clearing the reaction failed.
Forbidden – You do not have the proper permissions to clear the reaction.
NotFound – The emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
Guild
- afk_channel
- afk_timeout
- application_commands
- banner
- banner_url
- bitrate_limit
- cached_automod_rules
- categories
- channels
- chunked
- created_at
- default_notifications
- default_role
- description
- discovery_splash
- discovery_splash_url
- emoji_limit
- emojis
- events
- explicit_content_filter
- features
- filesize_limit
- forum_channels
- forum_posts
- icon
- icon_url
- id
- large
- max_members
- max_presences
- max_video_channel_users
- me
- member_count
- members
- mfa_level
- name
- owner
- owner_id
- preferred_locale
- premium_progress_bar_enabled
- premium_subscriber_role
- premium_subscribers
- premium_subscription_count
- premium_tier
- public_updates_channel
- roles
- rules_channel
- scheduled_events
- self_role
- shard_id
- splash
- splash_url
- stage_channels
- sticker_limit
- system_channel
- system_channel_flags
- text_channels
- thread_channels
- unavailable
- verification_level
- voice_channels
- voice_client
- defaudit_logs
- asyncautomod_rules
- asyncban
- defbanner_url_as
- defbans
- defby_category
- asyncchange_voice_state
- asyncchunk
- asynccreate_automod_rule
- asynccreate_category
- asynccreate_category_channel
- asynccreate_custom_emoji
- asynccreate_forum_channel
- asynccreate_integration
- asynccreate_role
- asynccreate_scheduled_event
- asynccreate_stage_channel
- asynccreate_sticker
- asynccreate_template
- asynccreate_text_channel
- asynccreate_voice_channel
- asyncdelete
- defdiscovery_splash_url_as
- asyncedit
- asyncedit_role_positions
- asyncestimate_pruned_members
- asyncfetch_ban
- asyncfetch_channels
- asyncfetch_emoji
- asyncfetch_emojis
- asyncfetch_event
- asyncfetch_events
- asyncfetch_member
- deffetch_members
- asyncfetch_roles
- defget_application_command
- defget_channel
- defget_event
- defget_member
- defget_member_named
- defget_role
- defget_scheduled_event
- deficon_url_as
- asyncintegrations
- asyncinvites
- defis_icon_animated
- asynckick
- asyncleave
- asyncprune_members
- asyncquery_members
- defsplash_url_as
- asynctemplates
- asyncunban
- asyncvanity_invite
- asyncwebhooks
- asyncwelcome_screen
- asyncwidget
- 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.
- emojis
All emojis that the guild owns.
- Type:
Tuple[
Emoji
, …]
- afk_channel
The channel that denotes the AFK channel.
None
if it doesn’t exist.- Type:
Optional[
VoiceChannel
]
- icon
The guild’s icon.
- Type:
Optional[
str
]
- owner_id
The guild owner’s ID. Use
Guild.owner
instead.- Type:
Indicates if the guild is unavailable. If this is
True
then the reliability of other attributes outside ofGuild.id
is slim, and they might all beNone
. It is best to not do anything with the guild if it is unavailable.Check the
on_guild_unavailable()
andon_guild_available()
events.- Type:
- max_presences
The maximum amount of presences for the guild.
- Type:
Optional[
int
]
- max_members
The maximum amount of members for the guild.
Note
This attribute is only available via
Client.fetch_guild()
.- Type:
Optional[
int
]
- max_video_channel_users
The maximum amount of users in a video channel.
New in version 1.4.
- Type:
Optional[
int
]
- banner
The guild’s banner.
- Type:
Optional[
str
]
- description
The guild’s description.
- Type:
Optional[
str
]
- mfa_level
Indicates the guild’s two-factor authorisation level. If this value is 0 then the guild does not require 2FA for their administrative members. If the value is 1 then they do.
- Type:
- features
A list of features that the guild has. They are currently as follows:
VIP_REGIONS
: Guild has VIP voice regionsVANITY_URL
: Guild can have a vanity invite URL (e.g. discord.gg/discord-api)INVITE_SPLASH
: Guild’s invite page can have a special splash.VERIFIED
: Guild is a verified server.PARTNERED
: Guild is a partnered server.MORE_EMOJI
: Guild is allowed to have more than 50 custom emoji.MORE_STICKER
: Guild is allowed to have more than 60 custom sticker.DISCOVERABLE
: Guild shows up in Server Discovery.FEATURABLE
: Guild is able to be featured in Server Discovery.COMMUNITY
: Guild is a community server.PUBLIC
: Guild is a public guild.NEWS
: Guild can create news channels.BANNER
: Guild can upload and use a banner (i.e.banner_url()
).ANIMATED_ICON
: Guild can upload an animated icon.PUBLIC_DISABLED
: Guild cannot be public.WELCOME_SCREEN_ENABLED
: Guild has enabled the welcome screenMEMBER_VERIFICATION_GATE_ENABLED
: Guild has Membership Screening enabled.PREVIEW_ENABLED
: Guild can be viewed before being accepted via Membership Screening.
- Type:
List[
str
]
- splash
The guild’s invite splash.
- Type:
Optional[
str
]
The premium tier for this guild. Corresponds to “Nitro Server” in the official UI. The number goes from 0 to 3 inclusive.
- Type:
The number of “boosts” this guild currently has.
- Type:
- preferred_locale
The preferred locale for the guild. Used when filtering Server Discovery results to a specific language.
- Type:
Optional[
str
]
Whether the guild has the boost progress bar enabled.
- Type:
- async for ... in fetch_members(*, limit=1000, after=None)
Retrieves an
AsyncIterator
that enables receiving the guild’s members. In order to use this,Intents.members()
must be enabled.Note
This method is an API call. For general usage, consider
members
instead.New in version 1.3.
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of members to retrieve. Defaults to 1000. PassNone
to fetch all members. Note that this is potentially slow.after (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Retrieve members after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.
- Raises:
ClientException – The members intent is not enabled.
HTTPException – Getting the members failed.
- Yields:
Member
– The member with the member data parsed.
Examples
Usage
async for member in guild.fetch_members(limit=150): print(member.name)
Flattening into a list
members = await guild.fetch_members(limit=150).flatten() # members is now a list of Member...
- async for ... in audit_logs(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)
Returns an
AsyncIterator
that enables receiving the guild’s audit logs.You must have the
view_audit_log
permission to use this.Examples
Getting the first 100 entries:
async for entry in guild.audit_logs(limit=100): print('{0.user} did {0.action} to {0.target}'.format(entry))
Getting entries for a specific action:
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban): print('{0.user} banned {0.target}'.format(entry))
Getting entries made by a specific user:
entries = await guild.audit_logs(limit=None, user=guild.me).flatten() await channel.send('I made {} moderation actions.'.format(len(entries)))
- Parameters:
limit (Optional[
int
]) – The number of entries to retrieve. IfNone
retrieve all entries.before (Union[
abc.Snowflake
,datetime.datetime
]) – Retrieve entries before this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Union[
abc.Snowflake
,datetime.datetime
]) – Retrieve entries after this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time.oldest_first (
bool
) – If set toTrue
, return entries in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.user (
abc.Snowflake
) – The moderator to filter entries from.action (
AuditLogAction
) – The action to filter with.
- Raises:
Forbidden – You are not allowed to fetch audit logs
HTTPException – An error occurred while fetching the audit logs.
- Yields:
AuditLogEntry
– The audit log entry.
- property application_commands
A list of application-commands from this application that are registered only in this guild.
- Type:
List[
ApplicationCommand
]
- get_application_command(id)
Optional[
ApplicationCommand
]: Returns an application-command from this application that are registered only in this guild with the given id
- property channels
A list of channels that belongs to this guild.
- Type:
List[
abc.GuildChannel
,ThreadChannel
,ForumPost
]
- property events
A list of scheduled events that belong to this guild.
- Type:
List[
GuildScheduledEvent
]
- property scheduled_events
A list of scheduled events that belong to this guild.
- Type:
List[
GuildScheduledEvent
]
- property cached_automod_rules
A list of auto moderation rules that are cached.
Reliable Fetching
This property is only reliable if
automod_rules()
was used before. To ensure that the rules are up-to-date, useautomod_rules()
instead.- Type:
List[
AutoModRules
]
- get_event(id)
Returns a scheduled event with the given ID.
- Parameters:
id (
int
) – The ID of the event to get.- Returns:
The scheduled event or
None
if not found.- Return type:
Optional[
GuildScheduledEvent
]
- get_scheduled_event(id)
Returns a scheduled event with the given ID.
- Parameters:
id (
int
) – The ID of the event to get.- Returns:
The scheduled event or
None
if not found.- Return type:
Optional[
GuildScheduledEvent
]
- property large
Indicates if the guild is a ‘large’ guild.
A large guild is defined as having more than
large_threshold
count members, which for this library is set to the maximum of 250.- Type:
- property voice_channels
A list of voice channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
- Type:
List[
VoiceChannel
]
- property stage_channels
A list of voice channels that belongs to this guild.
New in version 1.7.
This is sorted by the position and are in UI order from top to bottom.
- Type:
List[
StageChannel
]
- property me
Similar to
Client.user
except an instance ofMember
. This is essentially used to get the member version of yourself.- Type:
- property voice_client
Returns the
VoiceProtocol
associated with this guild, if any.- Type:
Optional[
VoiceProtocol
]
- property text_channels
A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
- Type:
List[
TextChannel
]
- property thread_channels
A list of cached thread channels the guild has.
This is sorted by the position of the threads
parent
and are in UI order from top to bottom.- Type:
List[
ThreadChannel
]
- property forum_channels
A list of forum channels the guild has.
This is sorted by the position of the forums
parent
and are in UI order from top to bottom.- Type:
List[
ForumChannel
]
- property forum_posts
A list of cached forum posts the guild has.
This is sorted by the position of the forums
parent
and are in UI order from top to bottom.- Type:
List[
ForumPost
]
- property categories
A list of categories that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
- Type:
List[
CategoryChannel
]
- by_category()
Returns every
CategoryChannel
and their associated channels.These channels and categories are sorted in the official Discord UI order.
If the channels do not have a category, then the first element of the tuple is
None
.- Returns:
The categories and their associated channels.
- Return type:
List[Tuple[Optional[
CategoryChannel
], List[abc.GuildChannel
]]]
- get_channel(channel_id)
Returns a channel with the given ID.
- Parameters:
channel_id (
int
) – The ID to search for.- Returns:
The returned channel or
None
if not found.- Return type:
Optional[Union[
abc.GuildChannel
,ThreadChannel
,ForumPost
]]
- property system_channel
Returns the guild’s channel used for system messages.
If no channel is set, then this returns
None
.- Type:
Optional[
TextChannel
]
- await welcome_screen()
Optional[
WelcomeScreen
]: fetches the welcome screen from the guild if any.
- property rules_channel
Return’s the guild’s channel used for the rules. The guild must be a Community guild.
If no channel is set, then this returns
None
.New in version 1.3.
- Type:
Optional[
TextChannel
]
- property public_updates_channel
Return’s the guild’s channel where admins and moderators of the guilds receive notices from Discord. The guild must be a Community guild.
If no channel is set, then this returns
None
.New in version 1.4.
- Type:
Optional[
TextChannel
]
- property filesize_limit
The maximum number of bytes files can have when uploaded to this guild.
- Type:
- property members
A list of members that belong to this guild.
- Type:
List[
Member
]
A list of members who have “boosted” this guild.
- Type:
List[
Member
]
- property roles
Returns a
list
of the guild’s roles in hierarchy order.The first element of this list will be the lowest role in the hierarchy.
- Type:
List[
Role
]
Gets the premium subscriber role, AKA “boost” role, in this guild.
New in version 1.6.
- Type:
Optional[
Role
]
- property self_role
Gets the role associated with this client’s user, if any.
New in version 1.6.
- Type:
Optional[
Role
]
- property owner
The member that owns the guild.
- Type:
Optional[
Member
]
- is_icon_animated()
bool
: Returns True if the guild has an animated icon.
- icon_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the guild’s icon.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the icon to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the icon being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated icons to.size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- banner_url_as(*, format='webp', size=2048)
Returns an
Asset
for the guild’s banner.The format must be one of ‘webp’, ‘jpeg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- splash_url_as(*, format='webp', size=2048)
Returns an
Asset
for the guild’s invite splash.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- discovery_splash_url_as(*, format='webp', size=2048)
Returns an
Asset
for the guild’s discovery splash.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
New in version 1.3.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- property member_count
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires
Intents.members
to be specified.- Type:
- property chunked
Returns a boolean indicating if the guild is “chunked”.
A chunked guild means that
member_count
is equal to the number of members stored in the internalmembers
cache.If this value returns
False
, then you should request for offline members.- Type:
- property shard_id
Returns the shard ID for this guild if applicable.
- Type:
Optional[
int
]
- 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.
- await create_text_channel(name, *, overwrites=None, category=None, reason=None, **options)
This function is a coroutine.
Creates a
TextChannel
for the guild.Note that you need the
manage_channels
permission to create the channel.The
overwrites
parameter can be used to create a ‘secret’ channel upon creation. This parameter expects adict
of overwrites with the target (either aMember
or aRole
) as the key and aPermissionOverwrite
as the value.Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to
edit()
will be required to update the position of the channel in the channel list.Examples
Creating a basic channel:
channel = await guild.create_text_channel('cool-channel')
Creating a “secret” channel:
overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True) } channel = await guild.create_text_channel('secret', overwrites=overwrites)
- Parameters:
name (
str
) – The channel’s name.overwrites – A
dict
of target (either a role or a member) toPermissionOverwrite
to apply upon creation of a channel. Useful for creating secret channels.category (Optional[
CategoryChannel
]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int
) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (Optional[
str
]) – The new channel’s topic.slowmode_delay (
int
) – Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is 21600.default_thread_slowmode_delay (
int
) – The initialslowmode_delay
to set on newly created threads in the channel. This field is copied to the thread at creation time and does not live update.nsfw (
bool
) – To mark the channel as NSFW or not.reason (Optional[
str
]) – The reason for creating this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Returns:
The channel that was just created.
- Return type:
- await create_voice_channel(name, *, overwrites=None, category=None, reason=None, **options)
This function is a coroutine.
This is similar to
create_text_channel()
except makes aVoiceChannel
instead, in addition to having the following new parameters.- Parameters:
bitrate (
int
) – The channel’s preferred audio bitrate in bits per second.user_limit (
int
) – The channel’s limit for number of members that can be in a voice channel.rtc_region (Optional[
VoiceRegion
]) –The region for the voice channel’s voice communication. A value of
None
indicates automatic voice region detection.New in version 1.7.
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Returns:
The channel that was just created.
- Return type:
- await create_stage_channel(name, *, topic=None, category=None, overwrites=None, reason=None, position=None)
This function is a coroutine.
This is similar to
create_text_channel()
except makes aStageChannel
instead, in addition to having the following new parameters.- Parameters:
topic (Optional[
str
]) – The topic of the Stage instance (1-120 characters)note:: (..) – The
slowmode_delay
andnsfw
parameters are not supported in this function.versionadded: (..) – 1.7:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Returns:
The channel that was just created.
- Return type:
- await create_forum_channel(name, *, topic=None, slowmode_delay=None, default_post_slowmode_delay=None, default_auto_archive_duration=None, overwrites=None, nsfw=None, category=None, position=None, reason=None)
This function is a coroutine.
Same as
create_text_channel()
excepts that it creates a forum channel instead- Parameters:
name (
str
) – The name of the channeloverwrites – A
dict
of target (either a role or a member) toPermissionOverwrite
to apply upon creation of a channel. Useful for creating secret channels.category (Optional[
CategoryChannel
]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int
) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (Optional[
str
]) – The new channel’s topic.slowmode_delay (
int
) – Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is 21600.default_post_slowmode_delay (
int
) – The initialslowmode_delay
to set on newly created threads in the channel. This field is copied to the thread at creation time and does not live update.default_auto_archive_duration (
AutoArchiveDuration
) – The default duration that the clients use (not the API) for newly created threads in the channel, in minutes, to automatically archive the thread after recent activitynsfw (
bool
) – To mark the channel as NSFW or not.reason (Optional[
str
]) – The reason for creating this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form, or the
default_auto_archive_duration
is not a valid member ofAutoArchiveDuration
- Returns:
The channel that was just created
- Return type:
- await create_category(name, *, overwrites=None, reason=None, position=None)
This function is a coroutine.
Same as
create_text_channel()
except makes aCategoryChannel
instead.Note
The
category
parameter is not supported in this function since categories cannot have categories.- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Returns:
The channel that was just created.
- Return type:
- await create_category_channel(name, *, overwrites=None, reason=None, position=None)
This function is a coroutine.
Same as
create_text_channel()
except makes aCategoryChannel
instead.Note
The
category
parameter is not supported in this function since categories cannot have categories.- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Returns:
The channel that was just created.
- Return type:
- await leave()
This function is a coroutine.
Leaves the guild.
Note
You cannot leave the guild that you own, you must delete it instead via
delete()
.- Raises:
HTTPException – Leaving the guild failed.
- await delete()
This function is a coroutine.
Deletes the guild. You must be the guild owner to delete the guild.
- Raises:
HTTPException – Deleting the guild failed.
Forbidden – You do not have permissions to delete the guild.
- await edit(name=MISSING, description=MISSING, icon=MISSING, banner=MISSING, splash=MISSING, discovery_splash=MISSING, region=MISSING, afk_channel=MISSING, afk_timeout=MISSING, system_channel=MISSING, system_channel_flags=MISSING, rules_channel=MISSING, public_updates_channel=MISSING, preferred_locale=MISSING, verification_level=MISSING, default_notifications=MISSING, explicit_content_filter=MISSING, vanity_code=MISSING, owner=MISSING, *, reason=None)
This function is a coroutine.
Edits the guild.
You must have the
manage_guild
permission to edit the guild.Changed in version 1.4: The rules_channel and public_updates_channel keyword-only parameters were added.
- Parameters:
name (
str
) – The new name of the guild.description (
str
) – The new description of the guild. This is only available to guilds that containPUBLIC
inGuild.features
.icon (
bytes
) – A bytes-like object representing the icon. Only PNG/JPEG is supported. GIF is only available to guilds that containANIMATED_ICON
inGuild.features
. Could beNone
to denote removal of the icon.banner (
bytes
) – A bytes-like object representing the banner. Could beNone
to denote removal of the banner.splash (
bytes
) – A bytes-like object representing the invite splash. Only PNG/JPEG supported. Could beNone
to denote removing the splash. This is only available to guilds that containINVITE_SPLASH
inGuild.features
.discovery_splash (
bytes
) – A bytes-like object representing the discovery splash. Only PNG/JPEG supported. Could beNone
to denote removing the splash. This is only available to guilds that containDISCOVERABLE
inGuild.features
.region (
VoiceRegion
) – Deprecated: The new region for the guild’s voice communication.afk_channel (Optional[
VoiceChannel
]) – The new channel that is the AFK channel. Could beNone
for no AFK channel.afk_timeout (
int
) – The number of seconds until someone is moved to the AFK channel.owner (
Member
) – The new owner of the guild to transfer ownership to. Note that you must be owner of the guild to do this.verification_level (
VerificationLevel
) – The new verification level for the guild.default_notifications (
NotificationLevel
) – The new default notification level for the guild.explicit_content_filter (
ContentFilter
) – The new explicit content filter for the guild.vanity_code (
str
) – The new vanity code for the guild.system_channel (Optional[
TextChannel
]) – The new channel that is used for the system channel. Could beNone
for no system channel.system_channel_flags (
SystemChannelFlags
) – The new system channel settings to use with the new system channel.preferred_locale (
str
) – The new preferred locale for the guild. Used as the primary language in the guild. If set, this must be an ISO 639 code, e.g.en-US
orja
orzh-CN
.rules_channel (Optional[
TextChannel
]) – The new channel that is used for rules. This is only available to guilds that containPUBLIC
inGuild.features
. Could beNone
for no rules channel.public_updates_channel (Optional[
TextChannel
]) – The new channel that is used for public updates from Discord. This is only available to guilds that containPUBLIC
inGuild.features
. Could beNone
for no public updates channel.reason (Optional[
str
]) – The reason for editing this guild. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit the guild.
HTTPException – Editing the guild failed.
InvalidArgument – The image format passed in to
icon
is invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer.
- await fetch_channels()
This function is a coroutine.
Retrieves all
abc.GuildChannel
that the guild has.Note
This method is an API call. For general usage, consider
channels
instead.New in version 1.2.
- Raises:
InvalidData – An unknown channel type was received from Discord.
HTTPException – Retrieving the channels failed.
- Returns:
All channels in the guild.
- Return type:
List[
abc.GuildChannel
]
- await fetch_member(member_id)
This function is a coroutine.
Retrieves a
Member
from a guild ID, and a member ID.Note
This method is an API call. If you have
Intents.members
and member cache enabled, considerget_member()
instead.- Parameters:
member_id (
int
) – The member’s ID to fetch from.- Raises:
Forbidden – You do not have access to the guild.
HTTPException – Fetching the member failed.
- Returns:
The member from the member ID.
- Return type:
- await fetch_ban(user)
This function is a coroutine.
Retrieves the
BanEntry
for a user.You must have the
ban_members
permission to get this information.- Parameters:
user (
abc.Snowflake
) – The user to get ban information from.- Raises:
Forbidden – You do not have proper permissions to get the information.
NotFound – This user is not banned.
HTTPException – An error occurred while fetching the information.
- Returns:
The
BanEntry
object for the specified user.- Return type:
- bans(limit=None, before=None, after=None)
Retrieves an
AsyncIterator
that enables receiving the guild’s bans.You must have the
ban_members
permission to get this information.Note
This method is an API call. Use it careful.
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of bans to retrieve. Defaults to all. Note that this is potentially slow.before (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Retrieve members before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Retrieve members after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.
- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – Getting the bans failed.
- Yields:
BanEntry
– The ban entry containing the user and an optional reason.
Examples
Usage
async for ban_entry in guild.bans(limit=150): print(ban_entry.user)
Flattening into a list
ban_entries = await guild.bans(limit=150).flatten() # ban_entries is now a list of BanEntry...
- await prune_members(*, days, compute_prune_count=True, roles=None, reason=None)
This function is a coroutine.
Prunes the guild from its inactive members.
The inactive members are denoted if they have not logged on in
days
number of days, and they have no roles.You must have the
kick_members
permission to use this.To check how many members you would prune without actually pruning, see the
estimate_pruned_members()
function.To prune members that have specific roles see the
roles
parameter.Changed in version 1.4: The
roles
keyword-only parameter was added.- Parameters:
days (
int
) – The number of days before counting as inactive.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.compute_prune_count (
bool
) – Whether to compute the prune count. This defaults toTrue
which makes it prone to timeouts in very large guilds. In order to prevent timeouts, you must set this toFalse
. If this is set toFalse
, then this function will always returnNone
.roles (Optional[List[
abc.Snowflake
]]) – A list ofabc.Snowflake
that represent roles to include in the pruning process. If a member has a role that is not specified, they’ll be excluded.
- Raises:
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while pruning members.
InvalidArgument – An integer was not passed for
days
.
- Returns:
The number of members pruned. If
compute_prune_count
isFalse
then this returnsNone
.- Return type:
Optional[
int
]
- await templates()
This function is a coroutine.
Gets the list of templates from this guild.
Requires
manage_guild
permissions.New in version 1.7.
- await webhooks()
This function is a coroutine.
Gets the list of webhooks from this guild.
Requires
manage_webhooks
permissions.
- await estimate_pruned_members(*, days, roles=None)
This function is a coroutine.
Similar to
prune_members()
except instead of actually pruning members, it returns how many members it would prune from the guild had it been called.- Parameters:
days (
int
) – The number of days before counting as inactive.roles (Optional[List[
abc.Snowflake
]]) –A list of
abc.Snowflake
that represent roles to include in the estimate. If a member has a role that is not specified, they’ll be excluded.New in version 1.7.
- Raises:
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while fetching the prune members estimate.
InvalidArgument – An integer was not passed for
days
.
- Returns:
The number of members estimated to be pruned.
- Return type:
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from the guild.
You must have the
manage_guild
permission to get this information.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite
]
- await create_template(*, name, description=None)
This function is a coroutine.
Creates a template for the guild.
You must have the
manage_guild
permission to do this.New in version 1.7.
- await create_integration(*, type, id)
This function is a coroutine.
Attaches an integration to the guild.
You must have the
manage_guild
permission to do this.New in version 1.4.
- Parameters:
- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – The account could not be found.
- await integrations()
This function is a coroutine.
Returns a list of all integrations attached to the guild. You must have the
manage_guild
permission to do this. .. versionadded:: 1.4 :raises Forbidden: You do not have permission to create the integration. :raises HTTPException: Fetching the integrations failed.- Returns:
The list of integrations that are attached to the guild.
- Return type:
List[
Integration
]
- await fetch_emojis()
This function is a coroutine.
Retrieves all custom
Emoji
s from the guild.Note
This method is an API call. For general usage, consider
emojis
instead.- Raises:
HTTPException – An error occurred fetching the emojis.
- Returns:
The retrieved emojis.
- Return type:
List[
Emoji
]
- await fetch_emoji(emoji_id)
This function is a coroutine.
Retrieves a custom
Emoji
from the guild.Note
This method is an API call. For general usage, consider iterating over
emojis
instead.- Parameters:
emoji_id (
int
) – The emoji’s ID.- Raises:
NotFound – The emoji requested could not be found.
HTTPException – An error occurred fetching the emoji.
- Returns:
The retrieved emoji.
- Return type:
- await create_custom_emoji(*, name, image, roles=None, reason=None)
This function is a coroutine.
Creates a custom
Emoji
for the guild.There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the
MORE_EMOJI
feature which extends the limit to 200.You must have the
manage_emojis
permission to do this.- Parameters:
name (
str
) – The emoji name. Must be at least 2 characters.image (
bytes
) – The bytes-like object representing the image data to use. Only JPG, PNG and GIF images are supported.roles (Optional[List[
Role
]]) – Alist
ofRole
s that can use this emoji. Leave empty to make it available to everyone.reason (Optional[
str
]) – The reason for creating this emoji. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to create emojis.
HTTPException – An error occurred creating an emoji.
- Returns:
The created emoji.
- Return type:
- await fetch_roles()
This function is a coroutine.
Retrieves all
Role
that the guild has.Note
This method is an API call. For general usage, consider
roles
instead.New in version 1.3.
- Raises:
HTTPException – Retrieving the roles failed.
- Returns:
All roles in the guild.
- Return type:
List[
Role
]
- await create_role(*, name=MISSING, permissions=MISSING, color=MISSING, colour=MISSING, hoist=False, mentionable=False, icon=None, unicode_emoji=None, reason=None)
This function is a coroutine.
Creates a
Role
for the guild.All fields are optional.
You must have the
manage_roles
permission to do this.Changed in version 1.6: Can now pass
int
tocolour
keyword-only parameter.New in version 2.0: Added the
icon
andunicode_emoji
keyword-only parameters.Note
The
icon
andunicode_emoji
can’t be used together. Both of them can only be used whenROLE_ICONS
is in the guildfeatures()
.- Parameters:
name (
str
) – The role name. Defaults to ‘new role’.permissions (
Permissions
) – The permissions to have. Defaults to no permissions.color (Union[
Colour
,int
]) – The colour for the role. Defaults toColour.default()
.colour (Union[
Colour
,int
]) – The colour for the role. Defaults toColour.default()
. This is aliased tocolor
as well.hoist (
bool
) – Indicates if the role should be shown separately in the member list. Defaults toFalse
.mentionable (
bool
) – Indicates if the role should be mentionable by others. Defaults toFalse
.icon (Optional[
bytes
]) – The bytes-like object representing the image data to use as the roleicon
.unicode_emoji (Optional[
str
]) – The unicode emoji to use as the roleunicode_emoji
.reason (Optional[
str
]) – The reason for creating this role. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to create the role.
HTTPException – Creating the role failed.
InvalidArgument – Both
icon
andunicode_emoji
were passed.
- Returns:
The newly created role.
- Return type:
- await edit_role_positions(positions, *, reason=None)
This function is a coroutine.
Bulk edits a list of
Role
in the guild.You must have the
manage_roles
permission to do this.New in version 1.4.
Example:
positions = { bots_role: 1, # penultimate role tester_role: 2, admin_role: 6 } await guild.edit_role_positions(positions=positions)
- Parameters:
- Raises:
Forbidden – You do not have permissions to move the roles.
HTTPException – Moving the roles failed.
InvalidArgument – An invalid keyword argument was given.
- Returns:
A list of all the roles in the guild.
- Return type:
List[
Role
]
- await kick(user, *, reason=None)
This function is a coroutine.
Kicks a user from the guild.
The user must meet the
abc.Snowflake
abc.You must have the
kick_members
permission to do this.- Parameters:
user (
abc.Snowflake
) – The user to kick from their guild.reason (Optional[
str
]) – The reason the user got kicked.
- Raises:
Forbidden – You do not have the proper permissions to kick.
HTTPException – Kicking failed.
- await ban(user, *, reason=None, delete_message_days=None, delete_message_seconds=0)
This function is a coroutine.
Bans a user from the guild.
The user must meet the
abc.Snowflake
abc.You must have the
ban_members
permission to do this.- Parameters:
user (
abc.Snowflake
) – The user to ban from their guild.delete_message_days (
int
) –The number of days worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 7.
Deprecated since version 2.0.
delete_message_seconds (
int
) – The number of days worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (7 days).reason (Optional[
str
]) – The reason the user got banned.
- Raises:
Forbidden – You do not have the proper permissions to ban.
HTTPException – Banning failed.
- await unban(user, *, reason=None)
This function is a coroutine.
Unbans a user from the guild.
The user must meet the
abc.Snowflake
abc.You must have the
ban_members
permission to do this.- Parameters:
user (
abc.Snowflake
) – The user to unban.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have the proper permissions to unban.
HTTPException – Unbanning failed.
- await vanity_invite()
This function is a coroutine.
Returns the guild’s special vanity invite.
The guild must have
VANITY_URL
infeatures
.You must have the
manage_guild
permission to use this as well.- Raises:
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the vanity invite failed.
- Returns:
The special vanity invite.
- Return type:
- await widget()
This function is a coroutine.
Returns the widget of the guild.
Note
The guild must have the widget enabled to get this information.
- Raises:
Forbidden – The widget for this guild is disabled.
HTTPException – Retrieving the widget failed.
- Returns:
The guild’s widget.
- Return type:
- await chunk(*, cache=True)
This function is a coroutine.
Requests all members that belong to this guild. In order to use this,
Intents.members()
must be enabled.This is a websocket operation and can be slow.
New in version 1.5.
- Parameters:
cache (
bool
) – Whether to cache the members as well.- Raises:
ClientException – The members intent is not enabled.
- await query_members(query=None, *, limit=5, user_ids=None, presences=False, cache=True)
This function is a coroutine.
Request members that belong to this guild whose username starts with the query given.
This is a websocket operation and can be slow.
New in version 1.3.
- Parameters:
query (Optional[
str
]) – The string that the username’s start with.limit (
int
) – The maximum number of members to send back. This must be a number between 5 and 100.presences (
bool
) –Whether to request for presences to be provided. This defaults to
False
.New in version 1.6.
cache (
bool
) – Whether to cache the members internally. This makes operations such asget_member()
work for those that matched.user_ids (Optional[List[
int
]]) –List of user IDs to search for. If the user ID is not in the guild then it won’t be returned.
New in version 1.4.
- Raises:
asyncio.TimeoutError – The query timed out waiting for the members.
ValueError – Invalid parameters were passed to the function
ClientException – The presences intent is not enabled.
- Returns:
The list of members that have matched the query.
- Return type:
List[
Member
]
- await change_voice_state(*, channel, self_mute=False, self_deaf=False)
This function is a coroutine.
Changes client’s voice state in the guild.
New in version 1.4.
- Parameters:
channel (Optional[
VoiceChannel
]) – Channel the client wants to join. UseNone
to disconnect.self_mute (
bool
) – Indicates if the client should be self-muted.self_deaf (
bool
) – Indicates if the client should be self-deafened.
- await create_sticker(name, file, tags, description=None, *, reason=None)
This function is a coroutine.
Create a new sticker for the guild.
Requires the
MANAGE_EMOJIS_AND_STICKERS
permission.- Parameters:
name (
str
) – The name of the sticker (2-30 characters).tags (Union[
str
, List[str
]]) – Autocomplete/suggestion tags for the sticker separated by,
or in a list. (max 200 characters).description (Optional[
str
]) – The description of the sticker (None or 2-100 characters).file (Union[
UploadFile
,str
]) – The sticker file to upload or the path to it, must be a PNG, APNG, GIF or Lottie JSON file, max 500 KBreason (Optional[
str
]) – The reason for creating the sticker., shows up in the audit-log.
- Raises:
discord.Forbidden: – You don’t have the permissions to upload stickers in this guild.
discord.HTTPException: – Creating the sticker failed.
ValueError – Any of name, description or tags is too short/long.
- Returns:
The new GuildSticker created on success.
- Return type:
- await fetch_events(with_user_count=True)
This function is a coroutine.
Retrieves a
list
of scheduled events the guild has.Note
This method is an API call. For general usage, consider iterating over
events
instead.- Parameters:
with_user_count (
bool
) – Whether to include the number of interested users the event has, defaultTrue
.- Returns:
A list of scheduled events the guild has.
- Return type:
Optional[List[
GuildScheduledEvent
]]
- await fetch_event(id, with_user_count=True)
This function is a coroutine.
Fetches the
GuildScheduledEvent
with the given id.- Parameters:
- Returns:
The event on success.
- Return type:
Optional[
GuildScheduledEvent
]
- await create_scheduled_event(name, entity_type, start_time, end_time=None, channel=None, description=None, location=None, cover_image=None, *, reason=None)
This function is a coroutine.
Schedules a new Event in this guild. Requires
MANAGE_EVENTS
at least in thechannel
or in the entire guild iftype
isexternal
.- Parameters:
name (
str
) – The name of the scheduled event. 1-100 characters long.entity_type (
EventEntityType
) –The entity_type of the scheduled event.
Important
end_time
andlocation
must be provided if entity_type isexternal
, otherwisechannel
start_time (
datetime.datetime
) – The time when the event will start. Must be a valid date in the future.end_time (Optional[
datetime.datetime
]) –The time when the event will end. Must be a valid date in the future.
Important
If
entity_type
isexternal
this must be provided.channel (Optional[Union[
StageChannel
,VoiceChannel
]]) – The channel in which the event takes place. Must be provided ifentity_type
isstage
orvoice
.description (Optional[
str
]) – The description of the scheduled event. 1-1000 characters long.location (Optional[
str
]) –The location where the event will take place. 1-100 characters long.
Important
This must be provided if
entity_type
isexternal
cover_image (Optional[
bytes
]) – The cover image of the scheduled event.reason (Optional[
str
]) – The reason for scheduling the event, shows up in the audit-log.
- Returns:
The scheduled event on success.
- Return type:
- Raises:
TypeError: – Any parameter is of wrong type.
errors.InvalidArgument: – entity_type is
stage
orvoice
butchannel
is not provided orexternal
but nolocation
and/orend_time
provided.ValueError: – The value of any parameter is invalid. (e.g. to long/short)
errors.Forbidden: – You don’t have permissions to schedule the event.
discord.HTTPException: – Scheduling the event failed.
- await automod_rules()
This function is a coroutine.
Fetches the Auto Moderation rules for this guild
Warning
This is an API-call, use it carefully.
- Returns:
A list of AutoMod rules the guild has
- Return type:
List[
AutoModRule
]
- await create_automod_rule(name, event_type, trigger_type, trigger_metadata, actions, enabled=True, exempt_roles=[], exempt_channels=[], *, reason=None)
This function is a coroutine.
Creates a new AutoMod rule for this guild
- Parameters:
name (
str
) – The name, the rule should have. Only valid if it’s not a preset rule.event_type (
AutoModEventType
) – Indicates in what event context a rule should be checked.trigger_type (
AutoModTriggerType
) – Characterizes the type of content which can trigger the rule.trigger_metadata (
AutoModTriggerMetadata
) – Additional data used to determine whether a rule should be triggered. Different fields are relevant based on the value oftrigger_type
.actions (List[
AutoModAction
]) – The actions which will execute when the rule is triggered.exempt_roles (List[
Snowflake
]) – Up to 20Role
’s, that should not be affected by the rule.exempt_channels (List[
Snowflake
]) – Up to 50TextChannel
/VoiceChannel
’s, that should not be affected by the rule.reason (Optional[
str
]) – The reason for creating the rule. Shows up in the audit log.
- Raises:
discord.Forbidden – The bot is missing permissions to create AutoMod rules
HTTPException – Creating the rule failed
- Returns:
The AutoMod rule created
- Return type:
GuildScheduledEvent
- asyncdelete
- asyncedit
- deficon_url_as
- asyncusers
- class discord.GuildScheduledEvent
Represents a scheduled event in a guild
Warning
Do not initialize this class manually. Use
fetch_event()
/fetch_events()
or to create onecreate_scheduled_event()
instead.- end_time
Optional, when the event will end
- Type:
Optional[
datetime.datetime
]
- async for ... in await users(limit=100, before=None, after=None, with_member=False)
Returns an
AsyncIterator
that enables receiving the interest users of the event.All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of users to retrieve. IfNone
, retrieves every user of the event. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve users before this user. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve users after this user. If a date is provided it must be a timezone-naive datetime representing UTC time.with_member (Optional[
bool
]) – If set toTrue
, return theMember
instead of theUser
if it is part of the guild the event is in.
Examples
# Usage counter = 0 async for user in event.users(limit=200): if user.id > 264905529753600000: # all accounts created before 2018 counter += 1 # Flattening into a list users = await event.users(limit=123).flatten() # users is now a list of Member/User...
- Raises:
Forbidden – You do not have permissions to get the event users.
HTTPException – The request to get event users failed.
- Yields:
- property location
The location of the event if
entity_type
isexternal
.
- property channel
Optional[Union[
StageChannel
,VoiceChannel
]]: The channel the event is scheduled in ifentity_type
isstage
orvoice
.
- icon_url_as(*, format='webp', size=1024)
Returns an
Asset
for the event image.The format must be one of ‘webp’, ‘jpeg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- await edit(reason=None, **fields)
This function is a coroutine.
Modify the event. Requires
MANAGE_EVENTS
permissions.- Parameters:
name (
str
) – The new name of the eventdescription (
str
) – The new description of the eventstart_time (
datetime.datetime
) – The new start time of the eventend_time (Optional[
datetime.datetime
]) – The new end time of the eventstatus (
EventStatus
) – The new status of the event.entity_type (
EventEntityType
) – The new type of the scheduled eventlocation (
str
) – The new location of the event. Ifentity_type
isexternal
channel (Optional[Union[
StageChannel, :class:`VoiceChannel
]]) – The new channel the event is scheduled in ifentity_type
isEventEntityType.stage
orEventEntityType.voice
.reason (Optional[
str
]) – The reason for editing the event, shows up in the audit-log.
- Returns:
The updatet event.
- Return type:
- await delete(*, reason=None)
Deletes the event. Requires
MANAGE_EVENTS
permissions.- Parameters:
reason (Optional[
str
]) – The reason for deleting the event, shows up in the audit-log.- Return type:
None
AutoModRule
- class discord.AutoModRule
Represents a rule for auto moderation
Warning
Do not initialize this class directly. Use
create_automod_rule()
instead.- trigger_metadata
Additional data used to determine whether a rule should be triggered. Different fields are relevant based on the value of
trigger_type
.- Type:
- actions
The actions which will execute when the rule is triggered
- Type:
List[
AutoModAction
]
- property exempt_roles
Yields the roles that should not be affected by the rule (Maximum of 20)
Note
This is equal to
for role_id in self._exempt_roles: role = self.guild.get_role(int(role_id)) yield role or Object(int(role_id))
- property exempt_channels
Yields the channels that should not be affected by the rule (Maximum of 20)
Note
This is equal to
for channel_id in self._exempt_channels: channel = self.guild.get_role(int(channel_id)) yield channel or Object(channel_id, type=GuildChannel, state=self._state)
- property creator
Returns the creator of the rule
Note
The
Intents.members
must be enabled, otherwise this may return `` None``
- await delete(*, reason)
This function is a coroutine.
Deletes the automod rule, this requires the
manage_server
permission.- Parameters:
reason (Optional[
str
]) – The reason for deleting this rule. Shows up in the audit log.- Raises:
discord.Forbidden – The bot is missing permissions to delete the rule
HTTPException – Deleting the rule failed
- await edit(*, name=MISSING, event_type=MISSING, trigger_type=MISSING, trigger_metadata=MISSING, actions=MISSING, enabled=MISSING, exempt_roles=MISSING, exempt_channels=MISSING, reason=None)
This function is a coroutine.
Edits the automod rule, this requires the
manage_server
permission.You only need to provide the parameters you want to edit the.
- Parameters:
name (
str
) – The name, the rule should have. Only valid if it’s not a preset rule.event_type (
AutoModEventType
) – Indicates in what event context a rule should be checked.trigger_type (
AutoModTriggerType
) – Characterizes the type of content which can trigger the ruletrigger_metadata (
AutoModTriggerMetadata
) – Additional data used to determine whether a rule should be triggered. Different fields are relevant based on the value oftrigger_type
.actions (List[
AutoModAction
]) – The actions which will execute when the rule is triggered.enabled (
bool
) – Whether the rule is enabled.exempt_roles (List[
Snowflake
]) – Up to 20Role
’s, that should not be affected by the rule.exempt_channels (List[
Snowflake
]) – Up to 50TextChannel
/VoiceChannel
/StageChannel
’s, that should not be affected by the rule.reason (Optional[
str
]) – The reason for editing the rule. Shows up in the audit log.
- Raises:
discord.Forbidden – The bot is missing permissions to edit the rule
HTTPException – Editing the rule failed
- Returns:
The updated rule on success.
- Return type:
AutoModActionPayload
- class discord.AutoModActionPayload
Represents the payload for an
on_automod_action()
event- channel_id
The id of the channel in which user content was posted
- Type:
Optional[
int
]
- message_id
The id of any user message which content belongs to
Note
This wil not exists if message was blocked by automod or content was not part of any message
- Type:
Optional[
int
]
- alert_system_message_id
The id of any system auto moderation messages posted as the result of this action
Note
This will only exist if the
type
of theaction
issend_alert_message
- Type:
Optional[
int
]
- content
The user generated text content
Important
The
Intents.message_content
intent is required to get a non-empty value for this field- Type:
- matched_content
The substring in
content
that triggered the ruleImportant
The
message_content
intent is required to get a non-empty value for this field- Type:
- property channel
The channel in wich user content was posted, if any.
- Returns:
The
TextChannel
,VoiceChannel
orThreadChannel
the user content was posted in.- Return type:
Optional[
abc.GuildChannel
]
WelcomeScreen
- class discord.WelcomeScreen
Represents a welcome screen for a guild returned by
welcome_screen()
.Warning
Do not initialize this class directly. Use
welcome_screen()
instead.- welcome_channels
- Type:
List[
WelcomeScreenChannel
]
Integration
- class discord.Integration
Represents a guild integration.
New in version 1.4.
- await delete()
This function is a coroutine. Deletes the integration. You must have the
manage_guild
permission to do this.- Raises:
Forbidden – You do not have permission to delete the integration.
HTTPException – Deleting the integration failed.
Member
- activities
- activity
- avatar
- avatar_url
- banner
- banner_color
- banner_url
- bot
- color
- colour
- communication_disabled_until
- created_at
- default_avatar
- default_avatar_url
- desktop_status
- discriminator
- display_avatar_url
- display_banner_url
- display_name
- dm_channel
- flags
- guild
- guild_avatar_url
- guild_banner_url
- guild_permissions
- hex_banner_color
- id
- joined_at
- mention
- mobile_status
- mutual_guilds
- name
- nick
- pending
- premium_since
- public_flags
- raw_status
- role_ids
- roles
- status
- system
- top_role
- voice
- web_status
- asyncadd_roles
- defavatar_url_as
- asyncban
- defbanner_url_as
- asynccreate_dm
- defdisplay_avatar_url_as
- defdisplay_banner_url_as
- asyncedit
- asyncfetch_message
- defguild_avatar_url_as
- defguild_banner_url_as
- defhistory
- defis_avatar_animated
- defis_banner_animated
- defis_guild_avatar_animated
- defis_guild_banner_animated
- defis_on_mobile
- asynckick
- defmentioned_in
- asyncmove_to
- defpermissions_in
- asyncpins
- asyncremove_roles
- asyncremove_timeout
- asyncrequest_to_speak
- asyncsend
- asynctimeout
- asynctrigger_typing
- deftyping
- asyncunban
- 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
A datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be
None
.- Type:
Optional[
datetime.datetime
]
- activities
The activities that the user is currently doing.
Note
Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.
- Type:
Tuple[Union[
BaseActivity
,Spotify
]]
- nick
The guild specific nickname of the user.
- Type:
Optional[
str
]
A datetime object that specifies the date and time in UTC when the member used their Nitro boost on the guild, if available. This could be
None
.- Type:
Optional[
datetime.datetime
]
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
Returns an
AsyncIterator
that enables receiving the destination’s message history.You must have
read_message_history
permissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of messages to retrieve. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) – If set toTrue
, return messages in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message
– The message with the message data parsed.
- async with typing()
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
Note
This is both a regular context manager and an async context manager. This means that both
with
andasync with
work with this.Example Usage:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
- property status
The member’s overall status. If the value is unknown, then it will be a
str
instead.- Type:
- is_on_mobile()
bool
: A helper function that determines if a member is active on a mobile device.
- property colour
A property that returns a colour denoting the rendered colour for the member. If the default colour is the one rendered then an instance of
Colour.default()
is returned.There is an alias for this named
color
.- Type:
- property color
A property that returns a color denoting the rendered color for the member. If the default color is the one rendered then an instance of
Colour.default()
is returned.There is an alias for this named
colour
.- Type:
- property role_ids
An iterable of
int
contain the ID’s of the roles the member has. You can use this to check on an efficient way whether a member has a role or not- Type:
utils.SnowflakeList
- property roles
A
list
ofRole
that the member belongs to. Note that the first element of this list is always the default ‘@everyone’ role.These roles are sorted by their position in the role hierarchy.
- Type:
List[
Role
]
- property 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.
- Type:
- property guild_avatar_url
Returns the guild-specific banner asset for the member if any.
- Type:
Optional[
Asset
]
- guild_avatar_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the guild-specific avatar of the member if any, elseNone
.The format must be one of ‘webp’, ‘jpeg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset if any.
- Return type:
Optional[
Asset
]
- is_guild_avatar_animated()
bool
: Indicates if the member has an animated guild-avatar.
- property display_avatar_url
Returns the guild-specific avatar asset for the member if he has one, else the default avatar asset
- Type:
- display_avatar_url_as(format=None, static_format='webp', size=1024)
Asset
: Same behaviour asUser.avatar_url_as()
andguild_avatar_url_as()
but it prefers the guild-specific avatar
- property guild_banner_url
Returns the guild-specific banner asset for the member if any.
- Type:
Optional[
Asset
]
- guild_banner_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the guild-specific banner of the member if any, elseNone
.The format must be one of ‘webp’, ‘jpeg’, ‘gif’ or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset if any.
- Return type:
Optional[
Asset
}
- is_guild_banner_animated()
bool
: Indicates if the member has an animated guild-banner.
- property display_banner_url
Returns the guild-specific banner asset for the member if he has one, else the default banner asset if any.
- Type:
Optional[
Asset
]
- display_banner_url_as(format=None, static_format='webp', size=1024)
Optional[
Asset
]: Same behaviour asUser.banner_url_as()
andguild_banner_url_as()
but it prefers the guild-specific banner
- property activity
Returns the primary activity the user is currently doing. Could be
None
if no activity is being done.Note
Due to a Discord API limitation, this may be
None
if the user is listening to a song on Spotify with a title longer than 128 characters. See GH-1738 for more information.Note
A user may have multiple activities, these can be accessed under
activities
.- Type:
Union[
BaseActivity
,Spotify
]
- permissions_in(channel)
An alias for
abc.GuildChannel.permissions_for()
.Basically equivalent to:
channel.permissions_for(self)
- Parameters:
channel (
abc.GuildChannel
) – The channel to check your permissions for.- Returns:
The resolved permissions for the member.
- Return type:
- property top_role
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
- Type:
- property guild_permissions
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use either
permissions_in()
orabc.GuildChannel.permissions_for()
.This does take into consideration guild ownership and the administrator implication.
- Type:
- property voice
Returns the member’s current voice state.
- Type:
Optional[
VoiceState
]
- property communication_disabled_until
The time until the member is timeouted, if any
- Type:
Optional[
datetime.datetime
]
- await timeout(until, *, reason=None)
This function is a coroutine.
A shortcut method to timeout a member.
The
moderate_members
permission is needed to do this.- Parameters:
until (
datetime.datetime
) –Until when the member should be timeouted. This can be a timezone aware :class`~datetime.datetime` object or a
timedelta
object.Note
This can be max 28 days from current time!
reason (Optional[
str
]) – The reason for sending the member to timeout - Shows up in the audit-log
- Raises:
TypeError – The passed
datetime
object is not timezone awareForbidden – The bot missing access to time out this member
HTTPException – Sending the member to timeout failed
- await remove_timeout(*, reason=None)
This function is a coroutine.
A shortcut method to remove a member from timeout.
The
moderate_members
permission is needed to do this.- Parameters:
reason (Optional[
str
]) – The reason for removing the member from timeout - Shows up in the audit-log- Raises:
Forbidden – The bot missing access to remove this member from timeout
HTTPException – Removing the member from timeout failed
- await ban(**kwargs)
This function is a coroutine.
Bans this member. Equivalent to
Guild.ban()
.
- await unban(*, reason=None)
This function is a coroutine.
Unbans this member. Equivalent to
Guild.unban()
.
- await kick(*, reason=None)
This function is a coroutine.
Kicks this member. Equivalent to
Guild.kick()
.
- await edit(*, nick=MISSING, mute=MISSING, deafen=MISSING, suppress=MISSING, roles=MISSING, voice_channel=MISSING, flags=MISSING, communication_disabled_until=MISSING, reason=None)
This function is a coroutine.
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below:
Parameter
Permission
nick
mute
deafen
roles
voice_channel
flags
communication_disabled_until
All parameters are optional.
Changed in version 1.1: Can now pass
None
tovoice_channel
to kick a member from voice.- Parameters:
nick (Optional[
str
]) – The member’s new nickname. UseNone
to remove the nickname.mute (
bool
) – Indicates if the member should be guild muted or un-muted.deafen (
bool
) – Indicates if the member should be guild deafened or un-deafened.suppress (
bool
) –Indicates if the member should be suppressed in stage channels.
New in version 1.7.
roles (Optional[List[
Role
]]) – The member’s new list of roles. This replaces the roles.voice_channel (Optional[
VoiceChannel
]) – The voice channel to move the member to. PassNone
to kick them from voice.flags (Optional[
GuildMemberFlags
]) – The new flags for this member. Note that you currently only update thebypasses_verification
flag value.communication_disabled_until (Optional[
datetime.datetime
]) –Temporarily puts the member in timeout until this time. If
None
, then the member is removed from timeout.Note
The
datetime
object must be timezone aware.reason (Optional[
str
]) – The reason for editing this member. Shows up on the audit log.
- Raises:
TypeError – The
datetime
object passed tocommunication_disabled_until
is not timezone awareForbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
- await request_to_speak()
This function is a coroutine.
Request to speak in the connected channel.
Only applies to stage channels.
Note
Requesting members that are not the client is equivalent to
edit
providingsuppress
asFalse
.New in version 1.7.
- Raises:
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
- await move_to(channel, *, reason=None)
This function is a coroutine.
Moves a member to a new voice channel (they must be connected first).
You must have the
move_members
permission to use this.This raises the same exceptions as
edit()
.Changed in version 1.1: Can now pass
None
to kick a member from voice.- Parameters:
channel (Optional[
VoiceChannel
]) – The new voice channel to move the member to. PassNone
to kick them from voice.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.
- await add_roles(*roles, reason=None, atomic=True)
This function is a coroutine.
Gives the member a number of
Role
s.You must have the
manage_roles
permission to use this, and the addedRole
s must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake
) – An argument list ofabc.Snowflake
representing aRole
to give to the member.reason (Optional[
str
]) – The reason for adding these roles. Shows up on the audit log.atomic (
bool
) – Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- Raises:
Forbidden – You do not have permissions to add these roles.
HTTPException – Adding roles failed.
- property avatar
Equivalent to
User.avatar
- property avatar_url
Equivalent to
User.avatar_url
- avatar_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the avatar the user has.If the user does not have a traditional avatar, an asset for the default avatar is returned instead.
The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the avatar to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the avatar being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
, or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- property banner_url
Equivalent to
User.banner_url
- banner_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the banner the user has. Could beNone
.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated banners. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the banner to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the banner being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated banner to. Defaults to ‘webp’size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
, or invalidsize
.- Returns:
The resulting CDN asset if any.
- Return type:
Optional[
Asset
]
- property bot
Equivalent to
User.bot
- await create_dm()
This function is a coroutine.
Creates a
DMChannel
with this user.This should be rarely called, as this is done transparently for most people.
- Returns:
The channel that was created.
- Return type:
- property created_at
Equivalent to
User.created_at
- property default_avatar
Equivalent to
User.default_avatar
- property default_avatar_url
Equivalent to
User.default_avatar_url
- property discriminator
Equivalent to
User.discriminator
- property dm_channel
Equivalent to
User.dm_channel
- await fetch_message(id)
This function is a coroutine.
Retrieves a single
Message
from the destination.This can only be used by bot accounts.
- Parameters:
id (
int
) – The message ID to look for.- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- Returns:
The message asked for.
- Return type:
- property id
Equivalent to
User.id
- is_avatar_animated()
bool
: Indicates if the user has an animated avatar.
- is_banner_animated()
bool
: Indicates if the user has an animated banner.
- property mutual_guilds
Equivalent to
User.mutual_guilds
- property name
Equivalent to
User.name
- await pins()
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Message
objects returned by this method do not contain completeMessage.reactions
data.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message
]
- property public_flags
Equivalent to
User.public_flags
- await remove_roles(*roles, reason=None, atomic=True)
This function is a coroutine.
Removes
Role
s from this member.You must have the
manage_roles
permission to use this, and the removedRole
s must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake
) – An argument list ofabc.Snowflake
representing aRole
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.
- await send(content=None, *, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set toNone
(the default), then theembed
parameter must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type.- Parameters:
content (
str
) – The content of the message to send.tts (
bool
) – Indicates if the message should be sent using text-to-speech.embed (
Embed
) – The rich embed for the content.embeds (List[
Embed
]) – A list containing up to ten embedscomponents (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) – A list of up to fiveButton
’s or oneBaseSelect
like object.file (
File
) – The file to upload.files (List[
File
]) – Alist
of files to upload. Must be a maximum of 10.stickers (List[
GuildSticker
]) – A list of up to 3discord.GuildSticker
that should be sent with the message.nonce (
int
) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
]) –A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
suppress_embeds (
bool
) – Whether to supress embeds send with the message, default toFalse
suppress_notifications (
bool
) –Whether to suppress desktop- & push-notifications for this message, default to
False
Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.
New in version 2.0.
- 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, you specified bothfile
andfiles
, or thereference
object is not aMessage
orMessageReference
.
- Returns:
The message that was sent.
- Return type:
- property system
Equivalent to
User.system
- await trigger_typing()
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
GuildMemberFlags
- class discord.GuildMemberFlags
Wraps up the Discord Guild Member flags.
- x == y
Checks if two GuildMemberFlags are equal.
- x != y
Checks if two GuildMemberFlags are not equal.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)
pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
- value
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type:
- bypasses_verification
Returns
True
if the member bypasses guild verification requirementsNote
This flag is editable and let you manually “verify” the member. This requires
moderate_members
permissions.- Type:
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’.
- property type
Returns the activity’s type. This is for compatibility with
Activity
.It always returns
ActivityType.listening
.- Type:
- property created_at
When the user started listening in UTC.
New in version 1.3.
- Type:
Optional[
datetime.datetime
]
- property colour
Returns the Spotify integration colour, as a
Colour
.There is an alias for this named
color
- Type:
- property color
Returns the Spotify integration colour, as a
Colour
.There is an alias for this named
colour
- Type:
- property artists
The artists of the song being played.
- Type:
List[
str
]
- property artist
The artist of the song being played.
This does not attempt to split the artist information into multiple artists. Useful if there’s only a single artist.
- Type:
VoiceState
- class discord.VoiceState
Represents a Discord user’s voice state.
- self_stream
Indicates if the user is currently streaming via ‘Go Live’ feature.
New in version 1.3.
- Type:
- suppress
Indicates if the user is suppressed from speaking.
Only applies to stage channels.
New in version 1.7.
- Type:
- requested_to_speak_at
A datetime object that specifies the date and time in UTC that the member requested to speak. It will be
None
if they are not requesting to speak anymore or have been accepted to speak.Only applicable to stage channels.
New in version 1.7.
- Type:
Optional[
datetime.datetime
]
- channel
The voice channel that the user is currently connected to.
None
if the user is not currently in a voice channel.- Type:
Optional[Union[
VoiceChannel
,StageChannel
]]
Emoji
- class discord.Emoji
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.
- user
The user that created the emoji. This can only be retrieved using
Guild.fetch_emoji()
and having themanage_emojis
permission.- Type:
Optional[
User
]
- property url
Returns the asset of the emoji.
This is equivalent to calling
url_as()
with the default parameters (i.e. png/gif detection).- Type:
- property roles
A
list
of roles that is allowed to use this emoji.If roles is empty, the emoji is unrestricted.
- Type:
List[
Role
]
- url_as(*, format=None, static_format='png')
Returns an
Asset
for the emoji’s url.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’. ‘gif’ is only valid for animated emojis.
New in version 1.6.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the emojis to. If the format isNone
, then it is automatically detected as either ‘gif’ or static_format, depending on whether the emoji is animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated emoji’s to. Defaults to ‘png’
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
.- Returns:
The resulting CDN asset.
- Return type:
- is_usable()
bool
: Whether the bot can use this emoji.New in version 1.3.
- await delete(*, reason=None)
This function is a coroutine.
Deletes the custom emoji.
You must have
manage_emojis
permission to do this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this emoji. Shows up on the audit log.- Raises:
Forbidden – You are not allowed to delete emojis.
HTTPException – An error occurred deleting the emoji.
- await edit(*, name=None, roles=None, reason=None)
This function is a coroutine.
Edits the custom emoji.
You must have
manage_emojis
permission to do this.- Parameters:
- Raises:
Forbidden – You are not allowed to edit emojis.
HTTPException – An error occurred editing the emoji.
PartialEmoji
- class discord.PartialEmoji
Represents a “partial” emoji.
This model will be given in two scenarios:
“Raw” data events such as
on_raw_reaction_add()
Custom emoji that the bot cannot see from e.g.
Message.reactions
- x == y
Checks if two emoji are the same.
- x != y
Checks if two emoji are not the same.
- hash(x)
Return the emoji’s hash.
- str(x)
Returns the emoji rendered for discord.
- name
The custom emoji name, if applicable, or the unicode codepoint of the non-custom emoji. This can be
None
if the emoji got deleted (e.g. removing a reaction with a deleted emoji).- Type:
Optional[
str
]
- id
The ID of the custom emoji, if applicable.
- Type:
Optional[
int
]
- classmethod from_string(string)
Converts a (custom) emoji as they are in a message into a partial emoji object.
Note
To get them, type a custom emoji into the chat, put an
\
in front of it and send it. You can then use what comes out when you add a reaction or similar.Warning
This does not support the :emoji: format for (standard) emojis
- is_custom_emoji()
bool
: Checks if this is a custom non-Unicode emoji.
- is_unicode_emoji()
bool
: Checks if this is a Unicode emoji.
- property created_at
Returns the emoji’s creation time in UTC, or None if Unicode emoji.
New in version 1.6.
- Type:
Optional[
datetime.datetime
]
- property url
Returns the asset of the emoji, if it is custom.
This is equivalent to calling
url_as()
with the default parameters (i.e. png/gif detection).- Type:
- url_as(*, format=None, static_format='png')
Returns an
Asset
for the emoji’s url, if it is custom.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’. ‘gif’ is only valid for animated emojis.
New in version 1.7.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the emojis to. If the format isNone
, then it is automatically detected as either ‘gif’ or static_format, depending on whether the emoji is animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated emoji’s to. Defaults to ‘png’
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
.- Returns:
The resulting CDN asset.
- Return type:
Role
- asyncdelete
- asyncedit
- deficon_url_as
- defis_bot_managed
- defis_default
- defis_integration
- defis_premium_subscriber
- 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.
- icon
The role-icon hash
- Type:
Optional[
str
]
- unicode_emoji
The unicode emoji of the role (shows as role-icon)
- Type:
Optional[
str
]
- position
The position of the role. This number is usually positive. The bottom role has a position of 0.
- Type:
- managed
Indicates if the role is managed by the guild through some form of integrations such as Twitch.
- Type:
- tags
The role tags associated with this role.
- Type:
Optional[
RoleTags
]
- is_default()
bool
: Checks if the role is the default role.
- is_bot_managed()
bool
: Whether the role is associated with a bot.New in version 1.6.
bool
: Whether the role is the premium subscriber, AKA “boost”, role for the guild.New in version 1.6.
- is_integration()
bool
: Whether the role is managed by an integration.New in version 1.6.
- property members
Returns all the members with this role.
- Type:
List[
Member
]
- icon_url_as(*, format='webp', size=1024)
Returns an
Asset
for the role icon.The format must be one of ‘webp’, ‘jpeg’, or ‘png’. The size must be a power of 2 between 16 and 4096.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- await edit(*, reason=None, **fields)
This function is a coroutine.
Edits the role.
You must have the
manage_roles
permission to use this.All fields are optional.
Changed in version 1.4: Can now pass
int
tocolour
keyword-only parameter.- Parameters:
name (
str
) – The new role name to change to.permissions (
Permissions
) – The new permissions to change to.colour (Union[
Colour
,int
]) – The new colour to change to. (aliased to color as well)hoist (
bool
) – Indicates if the role should be shown separately in the member list.mentionable (
bool
) – Indicates if the role should be mentionable by others.position (
int
) – The new role’s position. This must be below your top role’s position or it will fail.unicode_emoji (
str
) – The new role-icon as a unicode-emoji This is only available for guilds that containROLE_ICON
inGuild.features
.icon (
bytes
) – A bytes-like object representing the new role-icon. Only PNG/JPEG is supported. This is only available for guilds that containROLE_ICON
inGuild.features
. Could beNone
to denote removal of the icon.reason (Optional[
str
]) – The reason for editing this role. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to change the role.
HTTPException – Editing the role failed.
InvalidArgument – An invalid position was given or the default role was asked to be moved.
- await delete(*, reason=None)
This function is a coroutine.
Deletes the role.
You must have the
manage_roles
permission to use this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this role. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to delete the role.
HTTPException – Deleting the role failed.
TextChannel
- asyncclone
- asynccreate_invite
- asynccreate_thread
- asynccreate_webhook
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_message
- asyncfollow
- defget_partial_message
- defget_thread
- defhistory
- asyncinvites
- defis_news
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncpins
- asyncpurge
- asyncsend
- asyncset_permissions
- asynctrigger_typing
- deftyping
- asyncwebhooks
- 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.
- category_id
The category channel ID this channel belongs to, if applicable.
- Type:
Optional[
int
]
- topic
The channel’s topic.
None
if it doesn’t exist.- Type:
Optional[
str
]
- position
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type:
- last_message_id
The last message ID of the message sent to this channel. It may not point to an existing or valid message.
- Type:
Optional[
int
]
- slowmode_delay
The number of seconds a member must wait between sending messages in this channel. A value of 0 denotes that it is disabled. Bots and users with
manage_channels
ormanage_messages
bypass slowmode.- Type:
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
Returns an
AsyncIterator
that enables receiving the destination’s message history.You must have
read_message_history
permissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of messages to retrieve. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) – If set toTrue
, return messages in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message
– The message with the message data parsed.
- async with typing()
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
Note
This is both a regular context manager and an async context manager. This means that both
with
andasync with
work with this.Example Usage:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
- get_thread(id)
Optional[
ThreadChannel
]: Returns the cached thread in this channel with the given ID if any, elseNone
- property threads
Returns a list of cached threads for this channel
- Type:
List[
ThreadChannel
]
- permissions_for(member)
Handles permission resolution for the current
Member
.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
- Parameters:
member (
Member
) – The member to resolve permissions for.- Returns:
The resolved permissions for the member.
- Return type:
- property members
Returns all members that can see this channel.
- Type:
List[
Member
]
- is_nsfw()
bool
: Checks if the channel is NSFW.
- is_news()
bool
: Checks if the channel is a news channel.
- property last_message
Fetches the last message from this channel in cache.
The message might not be valid or point to an existing message.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either
history()
orfetch_message()
with thelast_message_id
attribute.- Returns:
The last message in this channel or
None
if not found.- Return type:
Optional[
Message
]
- await edit(*, reason=None, **options)
This function is a coroutine.
Edits the channel.
You must have the
manage_channels
permission to use this.Changed in version 1.3: The
overwrites
keyword-only parameter was added.Changed in version 1.4: The
type
keyword-only parameter was added.- Parameters:
name (
str
) – The new channel name.topic (
str
) – The new channel’s topic.position (
int
) – The new channel’s position.nsfw (
bool
) – To mark the channel as NSFW or not.sync_permissions (
bool
) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse
.category (Optional[
CategoryChannel
]) – The new category for this channel. Can beNone
to remove the category.slowmode_delay (
int
) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600.type (
ChannelType
) – Change the type of this text channel. Currently, only conversion betweenChannelType.text
andChannelType.news
is supported. This is only available to guilds that containNEWS
inGuild.features
.reason (Optional[
str
]) – The reason for editing this channel. Shows up on the audit log.overwrites (
dict
) – Adict
of target (either a role or a member) toPermissionOverwrite
to apply to the channel.
- Raises:
InvalidArgument – If position is less than 0 or greater than the number of channels, or if the permission overwrite information is not in proper form.
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
- await clone(*, name=None, reason=None)
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channels
permission to do this.New in version 1.1.
- Parameters:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- await 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.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- await purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True)
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check
. If acheck
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). Theread_message_history
permission is also needed to retrieve message history.Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.
Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await channel.purge(limit=100, check=is_me) await channel.send('Deleted {} message(s)'.format(len(deleted)))
- Parameters:
limit (Optional[
int
]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message
],bool
]) – The function used to check if a message should be deleted. It must take aMessage
as its sole parameter.before (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asbefore
inhistory()
.after (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asafter
inhistory()
.around (Optional[Union[
abc.Snowflake
,datetime.datetime
]]) – Same asaround
inhistory()
.oldest_first (Optional[
bool
]) – Same asoldest_first
inhistory()
.bulk (
bool
) – IfTrue
, use bulk delete. Setting this toFalse
is useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages
. WhenTrue
, will fall back to single delete if current account is a user bot (now deprecated), or if messages are older than two weeks.
- Raises:
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
- Returns:
The list of messages that were deleted.
- Return type:
List[
Message
]
- await webhooks()
This function is a coroutine.
Gets the list of webhooks from this channel.
Requires
manage_webhooks
permissions.
- await create_webhook(*, name, avatar=None, reason=None)
This function is a coroutine.
Creates a webhook for this channel.
Requires
manage_webhooks
permissions.Changed in version 1.1: Added the
reason
keyword-only parameter.- Parameters:
name (
str
) – The webhook’s name.avatar (Optional[
bytes
]) – A bytes-like object representing the webhook’s default avatar. This operates similarly toedit()
.reason (Optional[
str
]) – The reason for creating this webhook. Shows up in the audit logs.
- Raises:
HTTPException – Creating the webhook failed.
Forbidden – You do not have permissions to create a webhook.
- Returns:
The created webhook.
- Return type:
- await follow(*, destination, reason=None)
Follows a channel using a webhook.
Only news channels can be followed.
Note
The webhook returned will not provide a token to do webhook actions, as Discord does not provide it.
New in version 1.3.
- Parameters:
destination (
TextChannel
) – The channel you would like to follow from.reason (Optional[
str
]) –The reason for following the channel. Shows up on the destination guild’s audit log.
New in version 1.4.
- Raises:
HTTPException – Following the channel failed.
Forbidden – You do not have the permissions to create a webhook.
- Returns:
The created webhook.
- Return type:
- get_partial_message(message_id)
Creates a
PartialMessage
from the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 1.6.
- Parameters:
message_id (
int
) – The message ID to create a partial message for.- Returns:
The partial message.
- Return type:
- await create_thread(name, auto_archive_duration=None, slowmode_delay=0, private=False, invitable=True, *, reason=None)
This function is a coroutine.
Creates a new thread in this channel.
You must have the
create_public_threads
or for privatecreate_private_threads
permission to use this.- Parameters:
name (
str
) – The name of the thread.auto_archive_duration (Optional[
AutoArchiveDuration
]) – Amount of time after that the thread will auto-hide from the channel listslowmode_delay (
int
) – Amount of seconds a user has to wait before sending another message (0-21600)private (
bool
) –Whether to create a private thread
Note
The guild needs to have the
PRIVATE_THREADS
feature wich they get with boost level 2invitable (
bool
) – For private-threads Whether non-moderators can add new members to the thread, default :obj`True`reason (Optional[
str
]) – The reason for creating the thread. Shows up in the audit log.
- Raises:
TypeError – The channel of the message is not a text or news channel, or the message has already a thread, or auto_archive_duration is not a valid member of
AutoArchiveDuration
ValueError – The
name
is of invalid lengthForbidden – The bot is missing permissions to create threads in this channel
HTTPException – Creating the thread failed
- Returns:
The created thread on success
- Return type:
- property category
The category this channel belongs to.
If there is no category then this is
None
.- Type:
Optional[
CategoryChannel
]
- property changed_roles
Returns a list of roles that have been overridden from their default values in the
roles
attribute.- Type:
List[
Role
]
- await create_invite(*, reason=None, **fields)
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invite
permission to do this.- Parameters:
max_age (Optional[
int
]) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0
.max_uses (Optional[
int
]) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0
.temporary (Optional[
bool
]) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse
.unique (Optional[
bool
]) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalse
then it will return a previously created invite.target_type (Optional[
int
]) – The type of target for this voice channel invite.1
for stream and2
for embedded-application.target_user_id (Optional[
int
]) – The id of theUser
whose stream to display for this invite, required iftarget_type
is1
, the user must be streaming in the channel.target_application_id (Optional[
int
]) – The id of the embedded application to open for this invite, required iftarget_type
is2
, the application must have the EMBEDDED flag.reason (Optional[
str
]) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The invite that was created.
- Return type:
- await delete(*, reason=None)
This function is a coroutine.
Deletes the channel.
You must have
manage_channels
permission to use this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await fetch_message(id)
This function is a coroutine.
Retrieves a single
Message
from the destination.This can only be used by bot accounts.
- Parameters:
id (
int
) – The message ID to look for.- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- Returns:
The message asked for.
- Return type:
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channels
to get this information.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite
]
- await move(**kwargs)
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
edit()
should be used instead.You must have the
manage_channels
permission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
- Parameters:
beginning (
bool
) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend
,before
, andafter
.end (
bool
) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning
,before
, andafter
.before (
Snowflake
) – The channel that should be before our current channel. This is mutually exclusive withbeginning
,end
, andafter
.after (
Snowflake
) – The channel that should be after our current channel. This is mutually exclusive withbeginning
,end
, andbefore
.offset (
int
) – The number of channels to offset the move by. For example, an offset of2
withbeginning=True
would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning
,end
,before
, andafter
parameters.category (Optional[
Snowflake
]) – The category to move this channel under. IfNone
is given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool
) – Whether to sync the permissions with the category (if given).reason (
str
) – The reason for the move.
- Raises:
InvalidArgument – An invalid position was given or a bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- property overwrites
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Role
or aMember
and the value is the overwrite as aPermissionOverwrite
.- Returns:
The channel’s permission overwrites.
- Return type:
Mapping[Union[
Role
,Member
],PermissionOverwrite
]
- overwrites_for(obj)
Returns the channel-specific overwrites for a member or a role.
- property permissions_synced
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False
.New in version 1.3.
- Type:
- await pins()
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Message
objects returned by this method do not contain completeMessage.reactions
data.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message
]
- await send(content=None, *, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set toNone
(the default), then theembed
parameter must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type.- Parameters:
content (
str
) – The content of the message to send.tts (
bool
) – Indicates if the message should be sent using text-to-speech.embed (
Embed
) – The rich embed for the content.embeds (List[
Embed
]) – A list containing up to ten embedscomponents (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) – A list of up to fiveButton
’s or oneBaseSelect
like object.file (
File
) – The file to upload.files (List[
File
]) – Alist
of files to upload. Must be a maximum of 10.stickers (List[
GuildSticker
]) – A list of up to 3discord.GuildSticker
that should be sent with the message.nonce (
int
) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
]) –A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
suppress_embeds (
bool
) – Whether to supress embeds send with the message, default toFalse
suppress_notifications (
bool
) –Whether to suppress desktop- & push-notifications for this message, default to
False
Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.
New in version 2.0.
- 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, you specified bothfile
andfiles
, or thereference
object is not aMessage
orMessageReference
.
- Returns:
The message that was sent.
- Return type:
- await 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 aMember
or aRole
that belongs to guild.The
overwrite
parameter, if given, must either beNone
orPermissionOverwrite
. For convenience, you can pass in keyword arguments denotingPermissions
attributes. If this is done, then you cannot mix the keyword arguments with theoverwrite
parameter.If the
overwrite
parameter isNone
, then the permission overwrites are deleted.You must have the
manage_roles
permission to use this.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwrite
overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (Union[
Member
,Role
]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite
]) – The permissions to allow and deny to the target, orNone
to delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite
.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
InvalidArgument – The overwrite parameter invalid or the target type was not
Role
orMember
.
- await trigger_typing()
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
ThreadChannel
- asyncadd_member
- asynccreate_invite
- asyncdelete
- asyncedit
- deffetch_members
- asyncfetch_message
- defget_member
- defhistory
- asyncinvites
- defis_nsfw
- asyncjoin
- asyncleave
- defpermissions_for
- asyncpins
- asyncremove_member
- asyncsend
- asynctrigger_typing
- deftyping
- class discord.ThreadChannel
Represents a thread in a guild
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
Returns an
AsyncIterator
that enables receiving the destination’s message history.You must have
read_message_history
permissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of messages to retrieve. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) – If set toTrue
, return messages in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message
– The message with the message data parsed.
- async with typing()
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
Note
This is both a regular context manager and an async context manager. This means that both
with
andasync with
work with this.Example Usage:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
- async for ... in fetch_members(limit=100, after=None)
Returns a
ThreadMemberIterator
that allows to retrieve the currently joined members of this thread.Note
This requires the
members()
intent to be enabled and will also add the members retrieved tomembers
Examples
Usage
print(f"The thread {channel.name} has the following members:\n") async for member in thread.fetch_members(limit=200): print(member)
Flattening into a list
messages = await thread.fetch_members(limit=123).flatten() # messages is now a list of ThreadMember...
All parameters are optional.
- Parameters:
limit (
int
) – The limit of thread members to retrieve - defaults to 100after (Union[
int
,datetime.datetime
]) – Get thread members after this user ID
- Raises:
ClientException – The
members
intent is not enabled.- Yields:
ThreadMember
– A member of this thread
- property starter_message
The starter message of this thread if it was started from a message and the message is cached
- Type:
Optional[
Message
]
- property owner
Returns the owner(creator) of the thread. Depending on whether the associated guild member is cached, this returns the
Member
instead of theThreadMember
Note
If the thread members are not fetched (can be done manually using
fetch_members()
) and the guild member is not cached, this returnsNone
.- Returns:
The thread owner if cached
- Return type:
Optional[Union[
Member
,ThreadMember
]]
- property members
Returns a list with cached members of this thread
- Type:
List[
Member
]
- property locked
Whether the threads conversation is locked by a moderator. If so, the thread can only be unarchived by a moderator
- Type:
- property auto_archive_duration
The duration after which the thread will auto hide from the channel list
- Type:
AutoArchiveDuration
- property invitable
Private threads only: When
True
only the owner of the thread and members withmanage_threads
permissions can add new members- Return type:
- property archive_time
When the thread’s archive status was last changed, used for calculating recent activity
- Type:
Optional[
datetime.datetime
]
- property me
The thread member of the bot, or
None
if he is not a member of the thread.- Type:
Optional[
ThreadMember
]
- property parent_channel
The parent channel of this tread
- Type:
Union[
TextChannel
,ForumChannel
]
- property category_id
The ID of the threads parent channel category, if any
- Type:
Optional[
int
]
- property created_at
An aware timestamp of when the thread was created in UTC.
Note
This timestamp only exists for threads created after 9 January 2022, otherwise returns
None
.- Type:
Optional[
datetime.datetime
]
- get_member(id)
ThreadMember
: Returns the thread member with the given ID, orNone
if he is not a member of the thread.
- permissions_for(member)
Handles permission resolution for the current
Member
.Note
threads inherit their permissions from their parent channel.
This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
- Parameters:
member (
Member
) – The member to resolve permissions for.- Returns:
The resolved permissions for the member.
- Return type:
- is_nsfw()
bool
: Whether the parent channel of this thread has NSFW enabled.
- await join()
This function is a coroutine.
Adds the current user to the thread.
Note
Also requires the thread is not archived.
This will fire a
discord.thread_members_update()
event.
- await leave()
This function is a coroutine.
Removes the current user from the thread.
Note
Also requires the thread is not archived.
This will fire a
discord.thread_members_update()
event.
- await add_member(member)
This function is a coroutine.
Adds another member to the thread.
Note
Requires the ability to send messages in the thread.
Also requires the thread is not archived.
This will fire a
thread_members_update
event.- Parameters:
member (Union[
discord.Member
,int
]) – The member that should be added to the thread; could be adiscord.Member
or hisid
(e.g. anint
)
- await remove_member(member)
This function is a coroutine.
Removes a member from the thread.
Note
This requires the
MANAGE_THREADS
permission, or to be the creator of the thread if it is aPRIVATE_THREAD
.Also requires the thread is not archived.
This will fire a
thread_members_update
event.- Parameters:
member (Union[
discord.Member
,int
]) – The member that should be removed from the thread; could be adiscord.Member
or hisid
(e.g. anint
)
- await delete(*, reason=None)
This function is a coroutine.
Deletes the thread channel.
The bot must have
manage_channels
permission to use this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this tread. Shows up on the audit log.- Raises:
Forbidden – The bot is missing permissions to delete the thread.
NotFound – The thread was not found or was already deleted.
HTTPException – Deleting the thread failed.
- await create_invite(*, reason=None, **fields)
This function is a coroutine.
Creates an instant invite from this thread.
You must have the
create_instant_invite
permission to do this.- Parameters:
max_age (
int
) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0
.max_uses (
int
) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0
.temporary (
bool
) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse
.unique (
bool
) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalse
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:
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from this thread.
You must have
manage_channels
to get this information.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite
]
- await edit(*, name=MISSING, archived=MISSING, auto_archive_duration=MISSING, locked=MISSING, invitable=MISSING, slowmode_delay=MISSING, reason=None)
This function is a coroutine.
Edits the thread. In order to unarchive it, you must already be a member of it.
- Parameters:
name (Optional[
str
]) – The channel name. Must be 1-100 characters longarchived (Optional[
bool
]) – Whether the thread is archivedauto_archive_duration (Optional[
AutoArchiveDuration
]) – Duration in minutes to automatically archive the thread after recent activitylocked (Optional[
bool
]) – Whether the thread is locked; when a thread is locked, only users withPermissions.manage_threads
can unarchive itinvitable (Optional[
bool
]) – Whether non-moderators can add other non-moderators to a thread; only available on private threadsslowmode_delay (:Optional[
int
]) – Amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permissionPermissions.manage_messages
,Permissions.manage_thread
, orPermissions.manage_channel
, are unaffectedreason (Optional[
str
]) – The reason for editing the channel. Shows up on the audit log.
- Raises:
InvalidArgument: – The
auto_archive_duration
is not a valid member ofAutoArchiveDuration
Forbidden: – The bot missing permissions to edit the thread or the specific field
HTTPException: – Editing the thread failed
- Returns:
The updated thread on success
- Return type:
- await fetch_message(id)
This function is a coroutine.
Retrieves a single
Message
from the destination.This can only be used by bot accounts.
- Parameters:
id (
int
) – The message ID to look for.- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- Returns:
The message asked for.
- Return type:
- await pins()
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Message
objects returned by this method do not contain completeMessage.reactions
data.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message
]
- await send(content=None, *, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set toNone
(the default), then theembed
parameter must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type.- Parameters:
content (
str
) – The content of the message to send.tts (
bool
) – Indicates if the message should be sent using text-to-speech.embed (
Embed
) – The rich embed for the content.embeds (List[
Embed
]) – A list containing up to ten embedscomponents (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) – A list of up to fiveButton
’s or oneBaseSelect
like object.file (
File
) – The file to upload.files (List[
File
]) – Alist
of files to upload. Must be a maximum of 10.stickers (List[
GuildSticker
]) – A list of up to 3discord.GuildSticker
that should be sent with the message.nonce (
int
) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
]) –A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
suppress_embeds (
bool
) – Whether to supress embeds send with the message, default toFalse
suppress_notifications (
bool
) –Whether to suppress desktop- & push-notifications for this message, default to
False
Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.
New in version 2.0.
- 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, you specified bothfile
andfiles
, or thereference
object is not aMessage
orMessageReference
.
- Returns:
The message that was sent.
- Return type:
- await trigger_typing()
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
ThreadMember
- defpermissions_in
- asyncsend
- class discord.ThreadMember
Represents a minimal
Member
that has joined aThreadChannel
orForumPost
- property as_guild_member
Returns the full guild member for the thread member if cached else
None
- Type:
Optional[
Member
]
- await send(*args, **kwargs)
A shortcut to
Member.send()
- permissions_in(channel)
A shorthand method to
Member.permissions_in()
- Raises:
TypeError – The associated guild member is not cached
VoiceChannel
- asyncclone
- asyncconnect
- asynccreate_invite
- asyncdelete
- asyncedit
- asyncfetch_message
- defhistory
- asyncinvites
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncpins
- asyncsend
- asyncset_permissions
- asynctrigger_typing
- deftyping
- 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.
- category_id
The category channel ID this channel belongs to, if applicable.
- Type:
Optional[
int
]
- position
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type:
- rtc_region
The region for the voice channel’s voice communication. A value of
None
indicates automatic voice region detection.New in version 1.7.
- Type:
Optional[
VoiceRegion
]
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
Returns an
AsyncIterator
that enables receiving the destination’s message history.You must have
read_message_history
permissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of messages to retrieve. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) – If set toTrue
, return messages in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message
– The message with the message data parsed.
- async with typing()
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
Note
This is both a regular context manager and an async context manager. This means that both
with
andasync with
work with this.Example Usage:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
- await clone(*, name=None, reason=None)
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channels
permission to do this.New in version 1.1.
- Parameters:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- await edit(*, reason=None, **options)
This function is a coroutine.
Edits the channel.
You must have the
manage_channels
permission to use this.Changed in version 1.3: The
overwrites
keyword-only parameter was added.- Parameters:
name (
str
) – The new channel’s name.bitrate (
int
) – The new channel’s bitrate.user_limit (
int
) – The new channel’s user limit.position (
int
) – The new channel’s position.sync_permissions (
bool
) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse
.category (Optional[
CategoryChannel
]) – The new category for this channel. Can beNone
to remove the category.reason (Optional[
str
]) – The reason for editing this channel. Shows up on the audit log.overwrites (
dict
) – Adict
of target (either a role or a member) toPermissionOverwrite
to apply to the channel.rtc_region (Optional[
VoiceRegion
]) –The new region for the voice channel’s voice communication. A value of
None
indicates automatic voice region detection.New in version 1.7.
- Raises:
InvalidArgument – If the permission overwrite information is not in proper form.
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
- property category
The category this channel belongs to.
If there is no category then this is
None
.- Type:
Optional[
CategoryChannel
]
- property changed_roles
Returns a list of roles that have been overridden from their default values in the
roles
attribute.- Type:
List[
Role
]
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)
This function is a coroutine.
Connects to voice and creates a
VoiceClient
to establish your connection to the voice server.- Parameters:
timeout (
float
) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool
) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (Type[
VoiceProtocol
]) – A type that subclassesVoiceProtocol
to connect with. Defaults toVoiceClient
.
- 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:
- await create_invite(*, reason=None, **fields)
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invite
permission to do this.- Parameters:
max_age (Optional[
int
]) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0
.max_uses (Optional[
int
]) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0
.temporary (Optional[
bool
]) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse
.unique (Optional[
bool
]) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalse
then it will return a previously created invite.target_type (Optional[
int
]) – The type of target for this voice channel invite.1
for stream and2
for embedded-application.target_user_id (Optional[
int
]) – The id of theUser
whose stream to display for this invite, required iftarget_type
is1
, the user must be streaming in the channel.target_application_id (Optional[
int
]) – The id of the embedded application to open for this invite, required iftarget_type
is2
, the application must have the EMBEDDED flag.reason (Optional[
str
]) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The invite that was created.
- Return type:
- await delete(*, reason=None)
This function is a coroutine.
Deletes the channel.
You must have
manage_channels
permission to use this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await fetch_message(id)
This function is a coroutine.
Retrieves a single
Message
from the destination.This can only be used by bot accounts.
- Parameters:
id (
int
) – The message ID to look for.- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- Returns:
The message asked for.
- Return type:
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channels
to get this information.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite
]
- property members
Returns all members that are currently inside this voice channel.
- Type:
List[
Member
]
- await move(**kwargs)
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
edit()
should be used instead.You must have the
manage_channels
permission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
- Parameters:
beginning (
bool
) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend
,before
, andafter
.end (
bool
) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning
,before
, andafter
.before (
Snowflake
) – The channel that should be before our current channel. This is mutually exclusive withbeginning
,end
, andafter
.after (
Snowflake
) – The channel that should be after our current channel. This is mutually exclusive withbeginning
,end
, andbefore
.offset (
int
) – The number of channels to offset the move by. For example, an offset of2
withbeginning=True
would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning
,end
,before
, andafter
parameters.category (Optional[
Snowflake
]) – The category to move this channel under. IfNone
is given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool
) – Whether to sync the permissions with the category (if given).reason (
str
) – The reason for the move.
- Raises:
InvalidArgument – An invalid position was given or a bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- property overwrites
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Role
or aMember
and the value is the overwrite as aPermissionOverwrite
.- Returns:
The channel’s permission overwrites.
- Return type:
Mapping[Union[
Role
,Member
],PermissionOverwrite
]
- overwrites_for(obj)
Returns the channel-specific overwrites for a member or a role.
- 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:
- property permissions_synced
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False
.New in version 1.3.
- Type:
- await pins()
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Message
objects returned by this method do not contain completeMessage.reactions
data.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message
]
- await send(content=None, *, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set toNone
(the default), then theembed
parameter must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type.- Parameters:
content (
str
) – The content of the message to send.tts (
bool
) – Indicates if the message should be sent using text-to-speech.embed (
Embed
) – The rich embed for the content.embeds (List[
Embed
]) – A list containing up to ten embedscomponents (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) – A list of up to fiveButton
’s or oneBaseSelect
like object.file (
File
) – The file to upload.files (List[
File
]) – Alist
of files to upload. Must be a maximum of 10.stickers (List[
GuildSticker
]) – A list of up to 3discord.GuildSticker
that should be sent with the message.nonce (
int
) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
]) –A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
suppress_embeds (
bool
) – Whether to supress embeds send with the message, default toFalse
suppress_notifications (
bool
) –Whether to suppress desktop- & push-notifications for this message, default to
False
Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.
New in version 2.0.
- 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, you specified bothfile
andfiles
, or thereference
object is not aMessage
orMessageReference
.
- Returns:
The message that was sent.
- Return type:
- await 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 aMember
or aRole
that belongs to guild.The
overwrite
parameter, if given, must either beNone
orPermissionOverwrite
. For convenience, you can pass in keyword arguments denotingPermissions
attributes. If this is done, then you cannot mix the keyword arguments with theoverwrite
parameter.If the
overwrite
parameter isNone
, then the permission overwrites are deleted.You must have the
manage_roles
permission to use this.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwrite
overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (Union[
Member
,Role
]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite
]) – The permissions to allow and deny to the target, orNone
to delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite
.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
InvalidArgument – The overwrite parameter invalid or the target type was not
Role
orMember
.
- await trigger_typing()
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- property voice_states
Returns a mapping of member IDs who have voice states in this channel.
New in version 1.3.
Note
This function is intentionally low level to replace
members
when the member cache is unavailable.- Returns:
The mapping of member ID to a voice state.
- Return type:
Mapping[
int
,VoiceState
]
StageChannel
- asyncclone
- asyncconnect
- asynccreate_invite
- asyncdelete
- asyncedit
- asyncfetch_message
- defhistory
- asyncinvites
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncpins
- asyncsend
- asyncset_permissions
- asynctrigger_typing
- deftyping
- class discord.StageChannel
Represents a Discord guild stage channel.
New in version 1.7.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns the channel’s name.
- topic
The channel’s topic.
None
if it isn’t set.- Type:
Optional[
str
]
- category_id
The category channel ID this channel belongs to, if applicable.
- Type:
Optional[
int
]
- position
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type:
- rtc_region
The region for the stage channel’s voice communication. A value of
None
indicates automatic voice region detection.- Type:
Optional[
VoiceRegion
]
- property requesting_to_speak
A list of members who are requesting to speak in the stage channel.
- Type:
List[
Member
]
- await clone(*, name=None, reason=None)
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channels
permission to do this.New in version 1.1.
- Parameters:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- await edit(*, reason=None, **options)
This function is a coroutine.
Edits the channel.
You must have the
manage_channels
permission to use this.- Parameters:
name (
str
) – The new channel’s name.topic (
str
) – The new channel’s topic.position (
int
) – The new channel’s position.sync_permissions (
bool
) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse
.category (Optional[
CategoryChannel
]) – The new category for this channel. Can beNone
to remove the category.reason (Optional[
str
]) – The reason for editing this channel. Shows up on the audit log.overwrites (
dict
) – Adict
of target (either a role or a member) toPermissionOverwrite
to apply to the channel.rtc_region (Optional[
VoiceRegion
]) – The new region for the stage channel’s voice communication. A value ofNone
indicates automatic voice region detection.
- Raises:
InvalidArgument – If the permission overwrite information is not in proper form.
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
- property category
The category this channel belongs to.
If there is no category then this is
None
.- Type:
Optional[
CategoryChannel
]
- property changed_roles
Returns a list of roles that have been overridden from their default values in the
roles
attribute.- Type:
List[
Role
]
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)
This function is a coroutine.
Connects to voice and creates a
VoiceClient
to establish your connection to the voice server.- Parameters:
timeout (
float
) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool
) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (Type[
VoiceProtocol
]) – A type that subclassesVoiceProtocol
to connect with. Defaults toVoiceClient
.
- 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:
- await create_invite(*, reason=None, **fields)
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invite
permission to do this.- Parameters:
max_age (Optional[
int
]) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0
.max_uses (Optional[
int
]) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0
.temporary (Optional[
bool
]) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse
.unique (Optional[
bool
]) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalse
then it will return a previously created invite.target_type (Optional[
int
]) – The type of target for this voice channel invite.1
for stream and2
for embedded-application.target_user_id (Optional[
int
]) – The id of theUser
whose stream to display for this invite, required iftarget_type
is1
, the user must be streaming in the channel.target_application_id (Optional[
int
]) – The id of the embedded application to open for this invite, required iftarget_type
is2
, the application must have the EMBEDDED flag.reason (Optional[
str
]) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The invite that was created.
- Return type:
- await delete(*, reason=None)
This function is a coroutine.
Deletes the channel.
You must have
manage_channels
permission to use this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await fetch_message(id)
This function is a coroutine.
Retrieves a single
Message
from the destination.This can only be used by bot accounts.
- Parameters:
id (
int
) – The message ID to look for.- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- Returns:
The message asked for.
- Return type:
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
Returns an
AsyncIterator
that enables receiving the destination’s message history.You must have
read_message_history
permissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of messages to retrieve. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) – If set toTrue
, return messages in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message
– The message with the message data parsed.
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channels
to get this information.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite
]
- property members
Returns all members that are currently inside this voice channel.
- Type:
List[
Member
]
- await move(**kwargs)
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
edit()
should be used instead.You must have the
manage_channels
permission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
- Parameters:
beginning (
bool
) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend
,before
, andafter
.end (
bool
) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning
,before
, andafter
.before (
Snowflake
) – The channel that should be before our current channel. This is mutually exclusive withbeginning
,end
, andafter
.after (
Snowflake
) – The channel that should be after our current channel. This is mutually exclusive withbeginning
,end
, andbefore
.offset (
int
) – The number of channels to offset the move by. For example, an offset of2
withbeginning=True
would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning
,end
,before
, andafter
parameters.category (Optional[
Snowflake
]) – The category to move this channel under. IfNone
is given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool
) – Whether to sync the permissions with the category (if given).reason (
str
) – The reason for the move.
- Raises:
InvalidArgument – An invalid position was given or a bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- property overwrites
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Role
or aMember
and the value is the overwrite as aPermissionOverwrite
.- Returns:
The channel’s permission overwrites.
- Return type:
Mapping[Union[
Role
,Member
],PermissionOverwrite
]
- overwrites_for(obj)
Returns the channel-specific overwrites for a member or a role.
- 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:
- property permissions_synced
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False
.New in version 1.3.
- Type:
- await pins()
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Message
objects returned by this method do not contain completeMessage.reactions
data.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message
]
- await send(content=None, *, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set toNone
(the default), then theembed
parameter must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type.- Parameters:
content (
str
) – The content of the message to send.tts (
bool
) – Indicates if the message should be sent using text-to-speech.embed (
Embed
) – The rich embed for the content.embeds (List[
Embed
]) – A list containing up to ten embedscomponents (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) – A list of up to fiveButton
’s or oneBaseSelect
like object.file (
File
) – The file to upload.files (List[
File
]) – Alist
of files to upload. Must be a maximum of 10.stickers (List[
GuildSticker
]) – A list of up to 3discord.GuildSticker
that should be sent with the message.nonce (
int
) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
]) –A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
suppress_embeds (
bool
) – Whether to supress embeds send with the message, default toFalse
suppress_notifications (
bool
) –Whether to suppress desktop- & push-notifications for this message, default to
False
Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.
New in version 2.0.
- 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, you specified bothfile
andfiles
, or thereference
object is not aMessage
orMessageReference
.
- Returns:
The message that was sent.
- Return type:
- await 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 aMember
or aRole
that belongs to guild.The
overwrite
parameter, if given, must either beNone
orPermissionOverwrite
. For convenience, you can pass in keyword arguments denotingPermissions
attributes. If this is done, then you cannot mix the keyword arguments with theoverwrite
parameter.If the
overwrite
parameter isNone
, then the permission overwrites are deleted.You must have the
manage_roles
permission to use this.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwrite
overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (Union[
Member
,Role
]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite
]) – The permissions to allow and deny to the target, orNone
to delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite
.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
InvalidArgument – The overwrite parameter invalid or the target type was not
Role
orMember
.
- await trigger_typing()
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- typing()
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
Note
This is both a regular context manager and an async context manager. This means that both
with
andasync with
work with this.Example Usage:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
- property voice_states
Returns a mapping of member IDs who have voice states in this channel.
New in version 1.3.
Note
This function is intentionally low level to replace
members
when the member cache is unavailable.- Returns:
The mapping of member ID to a voice state.
- Return type:
Mapping[
int
,VoiceState
]
ForumChannel
- asyncclone
- asynccreate_post
- asynccreate_webhook
- asyncedit
- defget_post
- defget_tag
- defis_nsfw
- defpermissions_for
- asyncwebhooks
- class discord.ForumChannel
Represents a forum channel.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns the channel’s name.
- category_id
The category channel ID this channel belongs to, if applicable.
- Type:
Optional[
int
]
- topic
The channel’s topic.
None
if it doesn’t exist.- Type:
Optional[
str
]
- default_reaction_emoji
The default emoji for reactiong to a post in this forum
- Type:
Optional[
PartialEmoji
- position
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type:
- last_post_id
The ID of the last post that was createt in this forum, this may not point to an existing or valid post.
- Type:
Optional[
int
]
- slowmode_delay
The number of seconds a member must wait between sending messages in posts inside this channel. A value of 0 denotes that it is disabled. Bots and users with
manage_channels
ormanage_messages
bypass slowmode.- Type:
- get_post(id)
Optional[
ForumPost
]: Returns a post in the forum with the given ID. or None when not found.
- property posts
A list of all cached posts in the forum.
- Type:
List[
ForumPost
]
- get_tag(tag_id)
Optional[
ForumTag
]: Returns a tag with the given ID in the forum, orNone
when not found.
- property available_tags
A list of all tags available in the forum.
- Type:
List[
ForumTag
]
- permissions_for(member)
Handles permission resolution for the current
Member
.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
- Parameters:
member (
Member
) – The member to resolve permissions for.- Returns:
The resolved permissions for the member.
- Return type:
- property members
Returns all members that can see this channel.
- Type:
List[
Member
]
- is_nsfw()
bool
: Checks if the channel is NSFW.
- property last_post
Fetches the last post from this channel in cache.
The post might not be valid or point to an existing post.
- await edit(*, name=MISSING, topic=MISSING, available_tags=MISSING, tags_required=MISSING, default_post_sort_order=MISSING, position=MISSING, nsfw=MISSING, sync_permissions=False, category=MISSING, slowmode_delay=MISSING, overwrites=MISSING, reason=None)
This function is a coroutine.
Edits the channel.
You must have the
manage_channels
permission to use this.- Parameters:
name (
str
) – The new channel name.topic (
str
) – The new channel’s topic.available_tags (Sequence[
ForumTag
]) – An iterable of tags to keep as well of new tags. You can use this to reorder the tags.tags_required (
bool
) – Whether new created post require at least one tag provided on creationdefault_post_sort_order (Optional[PostSortOrder]) – How the posts in the forum will be sorted for users by default.
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 toFalse
.category (Optional[
CategoryChannel
]) – The new category for this channel. Can beNone
to remove the category.slowmode_delay (
int
) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600.overwrites (
dict
) – Adict
of target (either a role or a member) toPermissionOverwrite
to apply to the channel.reason (Optional[
str
]) – The reason for editing this channel. Shows up on the audit log.
- Raises:
InvalidArgument – If position is less than 0 or greater than the number of channels, or if the permission overwrite information is not in proper form.
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
- await clone(*, name=None, reason=None)
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channels
permission to do this.New in version 1.1.
- Parameters:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- await webhooks()
This function is a coroutine.
Gets the list of webhooks from this channel.
Requires
manage_webhooks
permissions.
- await create_webhook(*, name, avatar=None, reason=None)
This function is a coroutine.
Creates a webhook for this channel.
Requires
manage_webhooks
permissions.- Parameters:
name (
str
) – The webhook’s name.avatar (Optional[
bytes
]) – A bytes-like object representing the webhook’s default avatar. This operates similarly toedit()
.reason (Optional[
str
]) – The reason for creating this webhook. Shows up in the audit logs.
- Raises:
HTTPException – Creating the webhook failed.
Forbidden – You do not have permissions to create a webhook.
- Returns:
The created webhook.
- Return type:
- await create_post(*, name, tags=None, content=None, embed=None, embeds=None, components=None, file=None, files=None, allowed_mentions=None, suppress_embeds=False, supress_notifications=False, auto_archive_duration=None, slowmode_delay=0, reason=None)
This function is a coroutine.
Creates a new post in this forum. Requires the
create_posts
permission.- Parameters:
name (
str
) – The name of the post.tags (Optional[List[
ForumTag
]]) – The list of up to 5 tags that should be added to the post. These tags must be from the parent channel (forum).content (
str
) – The content of the post starter-message.embed (Optional[
Embed
]) – A embed of the post starter-message.embeds (List[
Embed
]) – A list of up to 10 embeds to include in the post starter-message.components (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) – A list of components to include in the post starter-message.file (Optional[class:File]) – A file to include in the post starter-message.
files (List[
File
]) – A list of files to include in the post starter-message.allowed_mentions (Optional[
AllowedMentions
]) – The allowed mentions for the post.suppress_embeds (Optional[
bool
]) – Whether to suppress embeds in the post starter-message.supress_notifications (Optional[
bool
]) –Whether to suppress desktop- & push-notifications for the post starter-message.
Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.
auto_archive_duration (Optional[
AutoArchiveDuration
]) – The duration after the post will be archived automatically when inactive.slowmode_delay (Optional[
int
]) – The amount of seconds a user has to wait before sending another message (0-21600)reason (Optional[
str
]) – The reason for creating this post. Shows up in the audit logs.
- Raises:
InvalidArgument – The forum requires
tags
on post creation but no tags where provided, orname
is of invalid length, orauto_archive_duration
is not of valid type.Forbidden – The bot does not have permissions to create posts in this channel
HTTPException – Creating the post failed
ForumPost
- asyncadd_member
- asynccreate_invite
- asyncdelete
- asyncedit
- asyncedit_tags
- deffetch_members
- asyncfetch_message
- defget_member
- defhistory
- asyncinvites
- defis_nsfw
- asyncjoin
- asyncleave
- defpermissions_for
- asyncpins
- asyncremove_member
- asyncsend
- asynctrigger_typing
- deftyping
- class discord.ForumPost
Represents a post in a
ForumChannel
, this is very similar to aThreadChannel
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
Returns an
AsyncIterator
that enables receiving the destination’s message history.You must have
read_message_history
permissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of messages to retrieve. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) – If set toTrue
, return messages in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message
– The message with the message data parsed.
- async with typing()
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
Note
This is both a regular context manager and an async context manager. This means that both
with
andasync with
work with this.Example Usage:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
- async for ... in fetch_members(limit=100, after=None)
Returns a
ThreadMemberIterator
that allows to retrieve the currently joined members of this thread.Note
This requires the
members()
intent to be enabled and will also add the members retrieved tomembers
Examples
Usage
print(f"The thread {channel.name} has the following members:\n") async for member in thread.fetch_members(limit=200): print(member)
Flattening into a list
messages = await thread.fetch_members(limit=123).flatten() # messages is now a list of ThreadMember...
All parameters are optional.
- Parameters:
limit (
int
) – The limit of thread members to retrieve - defaults to 100after (Union[
int
,datetime.datetime
]) – Get thread members after this user ID
- Raises:
ClientException – The
members
intent is not enabled.- Yields:
ThreadMember
– A member of this thread
- property applied_tags
Returns a list of tags applied to this post.
- Type:
List[
ForumTag
]
- await edit_tags(*tags)
This function is a coroutine.
Edits the tags of the post
- await edit(*, name=MISSING, tags=MISSING, pinned=MISSING, auto_archive_duration=MISSING, locked=MISSING, slowmode_delay=MISSING, reason=None)
This function is a coroutine.
Edits the post, all parameters are optional
- Parameters:
name (
str
) – The new name of the posttags (Sequence[
ForumPost
]) – Tags to keep as well as new tags to addpinned (
bool
) –Whether the post is pinned to the top of the parent forum.
Note
Per forum, only one post can be pinned.
auto_archive_duration (
AutoArchiveDuration
) – The new amount of minutes after that the post will stop showing in the channel list afterauto_archive_duration
minutes of inactivity.locked (
bool
) – Whether the post is locked; when a post is locked, only users with :func:~Permissions.manage_threads` permissions can unarchive itslowmode_delay (Optional[
str
]) – Amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffectedreason (Optional[
str
]) – The reason for editing the post, shows up in the audit log.
- await add_member(member)
This function is a coroutine.
Adds another member to the thread.
Note
Requires the ability to send messages in the thread.
Also requires the thread is not archived.
This will fire a
thread_members_update
event.- Parameters:
member (Union[
discord.Member
,int
]) – The member that should be added to the thread; could be adiscord.Member
or hisid
(e.g. anint
)
- property archive_time
When the thread’s archive status was last changed, used for calculating recent activity
- Type:
Optional[
datetime.datetime
]
- property auto_archive_duration
The duration after which the thread will auto hide from the channel list
- Type:
AutoArchiveDuration
- property category_id
The ID of the threads parent channel category, if any
- Type:
Optional[
int
]
- await create_invite(*, reason=None, **fields)
This function is a coroutine.
Creates an instant invite from this thread.
You must have the
create_instant_invite
permission to do this.- Parameters:
max_age (
int
) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0
.max_uses (
int
) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0
.temporary (
bool
) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse
.unique (
bool
) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalse
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:
- property created_at
An aware timestamp of when the thread was created in UTC.
Note
This timestamp only exists for threads created after 9 January 2022, otherwise returns
None
.- Type:
Optional[
datetime.datetime
]
- await delete(*, reason=None)
This function is a coroutine.
Deletes the thread channel.
The bot must have
manage_channels
permission to use this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this tread. Shows up on the audit log.- Raises:
Forbidden – The bot is missing permissions to delete the thread.
NotFound – The thread was not found or was already deleted.
HTTPException – Deleting the thread failed.
- await fetch_message(id)
This function is a coroutine.
Retrieves a single
Message
from the destination.This can only be used by bot accounts.
- Parameters:
id (
int
) – The message ID to look for.- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- Returns:
The message asked for.
- Return type:
- get_member(id)
ThreadMember
: Returns the thread member with the given ID, orNone
if he is not a member of the thread.
- property invitable
Private threads only: When
True
only the owner of the thread and members withmanage_threads
permissions can add new members- Return type:
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from this thread.
You must have
manage_channels
to get this information.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite
]
- is_nsfw()
bool
: Whether the parent channel of this thread has NSFW enabled.
- await join()
This function is a coroutine.
Adds the current user to the thread.
Note
Also requires the thread is not archived.
This will fire a
discord.thread_members_update()
event.
- await leave()
This function is a coroutine.
Removes the current user from the thread.
Note
Also requires the thread is not archived.
This will fire a
discord.thread_members_update()
event.
- property locked
Whether the threads conversation is locked by a moderator. If so, the thread can only be unarchived by a moderator
- Type:
- property me
The thread member of the bot, or
None
if he is not a member of the thread.- Type:
Optional[
ThreadMember
]
- property members
Returns a list with cached members of this thread
- Type:
List[
Member
]
- property owner
Returns the owner(creator) of the thread. Depending on whether the associated guild member is cached, this returns the
Member
instead of theThreadMember
Note
If the thread members are not fetched (can be done manually using
fetch_members()
) and the guild member is not cached, this returnsNone
.- Returns:
The thread owner if cached
- Return type:
Optional[Union[
Member
,ThreadMember
]]
- property parent_channel
The parent channel of this tread
- Type:
Union[
TextChannel
,ForumChannel
]
- permissions_for(member)
Handles permission resolution for the current
Member
.Note
threads inherit their permissions from their parent channel.
This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
- Parameters:
member (
Member
) – The member to resolve permissions for.- Returns:
The resolved permissions for the member.
- Return type:
- await pins()
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Message
objects returned by this method do not contain completeMessage.reactions
data.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message
]
- await remove_member(member)
This function is a coroutine.
Removes a member from the thread.
Note
This requires the
MANAGE_THREADS
permission, or to be the creator of the thread if it is aPRIVATE_THREAD
.Also requires the thread is not archived.
This will fire a
thread_members_update
event.- Parameters:
member (Union[
discord.Member
,int
]) – The member that should be removed from the thread; could be adiscord.Member
or hisid
(e.g. anint
)
- await send(content=None, *, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set toNone
(the default), then theembed
parameter must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type.- Parameters:
content (
str
) – The content of the message to send.tts (
bool
) – Indicates if the message should be sent using text-to-speech.embed (
Embed
) – The rich embed for the content.embeds (List[
Embed
]) – A list containing up to ten embedscomponents (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) – A list of up to fiveButton
’s or oneBaseSelect
like object.file (
File
) – The file to upload.files (List[
File
]) – Alist
of files to upload. Must be a maximum of 10.stickers (List[
GuildSticker
]) – A list of up to 3discord.GuildSticker
that should be sent with the message.nonce (
int
) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
]) –A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
suppress_embeds (
bool
) – Whether to supress embeds send with the message, default toFalse
suppress_notifications (
bool
) –Whether to suppress desktop- & push-notifications for this message, default to
False
Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.
New in version 2.0.
- 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, you specified bothfile
andfiles
, or thereference
object is not aMessage
orMessageReference
.
- Returns:
The message that was sent.
- Return type:
- property starter_message
The starter message of this thread if it was started from a message and the message is cached
- Type:
Optional[
Message
]
- await trigger_typing()
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
CategoryChannel
- asyncclone
- asynccreate_forum_channel
- asynccreate_invite
- asynccreate_stage_channel
- asynccreate_text_channel
- asynccreate_voice_channel
- asyncdelete
- asyncedit
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncset_permissions
- 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.
- position
The position in the category list. This is a number that starts at 0. e.g. the top category is position 0.
- Type:
- is_nsfw()
bool
: Checks if the category is NSFW.
- await clone(*, name=None, reason=None)
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channels
permission to do this.New in version 1.1.
- Parameters:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- await edit(*, reason=None, **options)
This function is a coroutine.
Edits the channel.
You must have the
manage_channels
permission to use this.Changed in version 1.3: The
overwrites
keyword-only parameter was added.- Parameters:
name (
str
) – The new category’s name.position (
int
) – The new category’s position.nsfw (
bool
) – To mark the category as NSFW or not.reason (Optional[
str
]) – The reason for editing this category. Shows up on the audit log.overwrites (
dict
) – Adict
of target (either a role or a member) toPermissionOverwrite
to apply to the channel.
- Raises:
InvalidArgument – If position is less than 0 or greater than the number of categories.
Forbidden – You do not have permissions to edit the category.
HTTPException – Editing the category failed.
- await move(**kwargs)
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
edit()
should be used instead.You must have the
manage_channels
permission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
- Parameters:
beginning (
bool
) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend
,before
, andafter
.end (
bool
) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning
,before
, andafter
.before (
Snowflake
) – The channel that should be before our current channel. This is mutually exclusive withbeginning
,end
, andafter
.after (
Snowflake
) – The channel that should be after our current channel. This is mutually exclusive withbeginning
,end
, andbefore
.offset (
int
) – The number of channels to offset the move by. For example, an offset of2
withbeginning=True
would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning
,end
,before
, andafter
parameters.category (Optional[
Snowflake
]) – The category to move this channel under. IfNone
is given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool
) – Whether to sync the permissions with the category (if given).reason (
str
) – The reason for the move.
- Raises:
InvalidArgument – An invalid position was given or a bad mix of arguments were passed.
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
- property channels
Returns the channels that are under this category.
These are sorted by the official Discord UI, which places voice channels below the text channels.
- Type:
List[
abc.GuildChannel
]
- property text_channels
Returns the text channels that are under this category.
- Type:
List[
TextChannel
]
- property voice_channels
Returns the voice channels that are under this category.
- Type:
List[
VoiceChannel
]
- property stage_channels
Returns the voice channels that are under this category.
New in version 1.7.
- Type:
List[
StageChannel
]
- property forum_channels
Returns the forum channels that are under this category.
- Type:
List[
ForumChannel
]
- await create_text_channel(name, *, overwrites=None, reason=None, **options)
This function is a coroutine.
A shortcut method to
Guild.create_text_channel()
to create aTextChannel
in the category.- Returns:
The channel that was just created.
- Return type:
- await create_voice_channel(name, *, overwrites=None, reason=None, **options)
This function is a coroutine.
A shortcut method to
Guild.create_voice_channel()
to create aVoiceChannel
in the category.- Returns:
The channel that was just created.
- Return type:
- await create_stage_channel(name, *, overwrites=None, reason=None, **options)
This function is a coroutine.
A shortcut method to
Guild.create_stage_channel()
to create aStageChannel
in the category.New in version 1.7.
- Returns:
The channel that was just created.
- Return type:
- await create_forum_channel(name, *, topic=None, slowmode_delay=None, default_post_slowmode_delay=None, default_auto_archive_duration=None, overwrites=None, nsfw=None, position=None, reason=None)
This function is a coroutine.
A shortcut method to
Guild.create_forum_channel()
to create aForumChannel
in the category.- Returns:
The channel that was just created
- Return type:
- property category
The category this channel belongs to.
If there is no category then this is
None
.- Type:
Optional[
CategoryChannel
]
- property changed_roles
Returns a list of roles that have been overridden from their default values in the
roles
attribute.- Type:
List[
Role
]
- await create_invite(*, reason=None, **fields)
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invite
permission to do this.- Parameters:
max_age (Optional[
int
]) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0
.max_uses (Optional[
int
]) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0
.temporary (Optional[
bool
]) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse
.unique (Optional[
bool
]) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalse
then it will return a previously created invite.target_type (Optional[
int
]) – The type of target for this voice channel invite.1
for stream and2
for embedded-application.target_user_id (Optional[
int
]) – The id of theUser
whose stream to display for this invite, required iftarget_type
is1
, the user must be streaming in the channel.target_application_id (Optional[
int
]) – The id of the embedded application to open for this invite, required iftarget_type
is2
, the application must have the EMBEDDED flag.reason (Optional[
str
]) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The invite that was created.
- Return type:
- await delete(*, reason=None)
This function is a coroutine.
Deletes the channel.
You must have
manage_channels
permission to use this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- await invites()
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channels
to get this information.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite
]
- property overwrites
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Role
or aMember
and the value is the overwrite as aPermissionOverwrite
.- Returns:
The channel’s permission overwrites.
- Return type:
Mapping[Union[
Role
,Member
],PermissionOverwrite
]
- overwrites_for(obj)
Returns the channel-specific overwrites for a member or a role.
- 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:
- property permissions_synced
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False
.New in version 1.3.
- Type:
- await 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 aMember
or aRole
that belongs to guild.The
overwrite
parameter, if given, must either beNone
orPermissionOverwrite
. For convenience, you can pass in keyword arguments denotingPermissions
attributes. If this is done, then you cannot mix the keyword arguments with theoverwrite
parameter.If the
overwrite
parameter isNone
, then the permission overwrites are deleted.You must have the
manage_roles
permission to use this.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwrite
overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (Union[
Member
,Role
]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite
]) – The permissions to allow and deny to the target, orNone
to delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite
.reason (Optional[
str
]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
InvalidArgument – The overwrite parameter invalid or the target type was not
Role
orMember
.
DMChannel
- asyncfetch_message
- defget_partial_message
- defhistory
- defpermissions_for
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
- 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
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
Returns an
AsyncIterator
that enables receiving the destination’s message history.You must have
read_message_history
permissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of messages to retrieve. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) – If set toTrue
, return messages in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message
– The message with the message data parsed.
- async with typing()
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
Note
This is both a regular context manager and an async context manager. This means that both
with
andasync with
work with this.Example Usage:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
- 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:
- get_partial_message(message_id)
Creates a
PartialMessage
from the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 1.6.
- Parameters:
message_id (
int
) – The message ID to create a partial message for.- Returns:
The partial message.
- Return type:
- await fetch_message(id)
This function is a coroutine.
Retrieves a single
Message
from the destination.This can only be used by bot accounts.
- Parameters:
id (
int
) – The message ID to look for.- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- Returns:
The message asked for.
- Return type:
- await pins()
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Message
objects returned by this method do not contain completeMessage.reactions
data.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message
]
- await send(content=None, *, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set toNone
(the default), then theembed
parameter must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type.- Parameters:
content (
str
) – The content of the message to send.tts (
bool
) – Indicates if the message should be sent using text-to-speech.embed (
Embed
) – The rich embed for the content.embeds (List[
Embed
]) – A list containing up to ten embedscomponents (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) – A list of up to fiveButton
’s or oneBaseSelect
like object.file (
File
) – The file to upload.files (List[
File
]) – Alist
of files to upload. Must be a maximum of 10.stickers (List[
GuildSticker
]) – A list of up to 3discord.GuildSticker
that should be sent with the message.nonce (
int
) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
]) –A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
suppress_embeds (
bool
) – Whether to supress embeds send with the message, default toFalse
suppress_notifications (
bool
) –Whether to suppress desktop- & push-notifications for this message, default to
False
Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.
New in version 2.0.
- 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, you specified bothfile
andfiles
, or thereference
object is not aMessage
orMessageReference
.
- Returns:
The message that was sent.
- Return type:
- await trigger_typing()
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
GroupChannel
- asyncadd_recipients
- asyncedit
- asyncfetch_message
- defhistory
- deficon_url_as
- asyncleave
- defpermissions_for
- asyncpins
- asyncremove_recipients
- asyncsend
- asynctrigger_typing
- deftyping
- 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
The users you are participating with in the group channel.
- Type:
List[
User
]
- icon
The group channel’s icon hash if provided.
- Type:
Optional[
str
]
- name
The group channel’s name if provided.
- Type:
Optional[
str
]
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)
Returns an
AsyncIterator
that enables receiving the destination’s message history.You must have
read_message_history
permissions to use this.Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- Parameters:
limit (Optional[
int
]) – The number of messages to retrieve. IfNone
, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool
]) – If set toTrue
, return messages in oldest->newest order. Defaults toTrue
ifafter
is specified, otherwiseFalse
.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message
– The message with the message data parsed.
- async with typing()
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
Note
This is both a regular context manager and an async context manager. This means that both
with
andasync with
work with this.Example Usage:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
- property icon_url
Returns the channel’s icon asset if available.
This is equivalent to calling
icon_url_as()
with the default parameters (‘webp’ format and a size of 1024).- Type:
- icon_url_as(*, format='webp', size=1024)
Returns an
Asset
for the icon the channel has.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’ or ‘png’. The size must be a power of 2 between 16 and 4096.
New in version 2.0.
- Parameters:
- Raises:
InvalidArgument – Bad image format passed to
format
or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- 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:
- await add_recipients(*recipients)
This function is a coroutine.
Adds recipients to this group.
A group can only have a maximum of 10 members. Attempting to add more ends up in an exception. To add a recipient to the group, you must have a relationship with the user of type
RelationshipType.friend
.Deprecated since version 1.7.
- Parameters:
*recipients (
User
) – An argument list of users to add to this group.- Raises:
HTTPException – Adding a recipient to this group failed.
- await remove_recipients(*recipients)
This function is a coroutine.
Removes recipients from this group.
Deprecated since version 1.7.
- Parameters:
*recipients (
User
) – An argument list of users to remove from this group.- Raises:
HTTPException – Removing a recipient from this group failed.
- await edit(**fields)
This function is a coroutine.
Edits the group.
Deprecated since version 1.7.
- Parameters:
name (Optional[
str
]) – The new name to change the group to. Could beNone
to remove the name.icon (Optional[
bytes
]) – A bytes-like object representing the new icon. Could beNone
to remove the icon.
- Raises:
HTTPException – Editing the group failed.
- await leave()
This function is a coroutine.
Leave the group.
If you are the only one in the group, this deletes it as well.
- Raises:
HTTPException – Leaving the group failed.
- await fetch_message(id)
This function is a coroutine.
Retrieves a single
Message
from the destination.This can only be used by bot accounts.
- Parameters:
id (
int
) – The message ID to look for.- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- Returns:
The message asked for.
- Return type:
- await pins()
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Message
objects returned by this method do not contain completeMessage.reactions
data.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message
]
- await send(content=None, *, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content)
. If the content is set toNone
(the default), then theembed
parameter must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects.If the
embed
parameter is provided, it must be of typeEmbed
and it must be a rich embed type.- Parameters:
content (
str
) – The content of the message to send.tts (
bool
) – Indicates if the message should be sent using text-to-speech.embed (
Embed
) – The rich embed for the content.embeds (List[
Embed
]) – A list containing up to ten embedscomponents (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) – A list of up to fiveButton
’s or oneBaseSelect
like object.file (
File
) – The file to upload.files (List[
File
]) – Alist
of files to upload. Must be a maximum of 10.stickers (List[
GuildSticker
]) – A list of up to 3discord.GuildSticker
that should be sent with the message.nonce (
int
) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.delete_after (
float
) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions
) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
]) –A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.New in version 1.6.
suppress_embeds (
bool
) – Whether to supress embeds send with the message, default toFalse
suppress_notifications (
bool
) –Whether to suppress desktop- & push-notifications for this message, default to
False
Users will still see a ping-symbol when they are mentioned in the message, or the message is in a dm channel.
New in version 2.0.
- 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, you specified bothfile
andfiles
, or thereference
object is not aMessage
orMessageReference
.
- Returns:
The message that was sent.
- Return type:
- await trigger_typing()
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
PartialInviteGuild
- defbanner_url_as
- deficon_url_as
- defis_icon_animated
- defsplash_url_as
- class discord.PartialInviteGuild
Represents a “partial” invite guild.
This model will be given when the user is not part of the guild the
Invite
resolves to.- x == y
Checks if two partial guilds are the same.
- x != y
Checks if two partial guilds are not the same.
- hash(x)
Return the partial guild’s hash.
- str(x)
Returns the partial guild’s name.
- features
A list of features the guild has. See
Guild.features
for more information.- Type:
List[
str
]
- icon
The partial guild’s icon.
- Type:
Optional[
str
]
- banner
The partial guild’s banner.
- Type:
Optional[
str
]
- splash
The partial guild’s invite splash.
- Type:
Optional[
str
]
- description
The partial guild’s description.
- Type:
Optional[
str
]
- is_icon_animated()
bool
: ReturnsTrue
if the guild has an animated icon.New in version 1.4.
- icon_url_as(*, format=None, static_format='webp', size=1024)
The same operation as
Guild.icon_url_as()
.- Returns:
The resulting CDN asset.
- Return type:
- banner_url_as(*, format='webp', size=2048)
The same operation as
Guild.banner_url_as()
.- Returns:
The resulting CDN asset.
- Return type:
- splash_url_as(*, format='webp', size=2048)
The same operation as
Guild.splash_url_as()
.- Returns:
The resulting CDN asset.
- Return type:
PartialInviteChannel
- class discord.PartialInviteChannel
Represents a “partial” invite channel.
This model will be given when the user is not part of the guild the
Invite
resolves to.- x == y
Checks if two partial channels are the same.
- x != y
Checks if two partial channels are not the same.
- hash(x)
Return the partial channel’s hash.
- str(x)
Returns the partial channel’s name.
Invite
- asyncdelete
- class discord.Invite
Represents a Discord
Guild
orabc.GuildChannel
invite.Depending on the way this object was created, some of the attributes can have a value of
None
.- x == y
Checks if two invites are equal.
- x != y
Checks if two invites are not equal.
- hash(x)
Returns the invite hash.
- str(x)
Returns the invite URL.
The following table illustrates what methods will obtain the attributes:
Attribute
Method
If it’s not in the table above then it is available by all methods.
- max_age
How long the before the invite expires in seconds. A value of
0
indicates that it doesn’t expire.- Type:
- guild
The guild the invite is for. Can be
None
if it’s from a group direct message.- Type:
Optional[Union[
Guild
,Object
,PartialInviteGuild
]]
- temporary
Indicates that the invite grants temporary membership. If
True
, members who joined via this invite will be kicked upon disconnect.- Type:
- max_uses
How many times the invite can be used. A value of
0
indicates that it has unlimited uses.- Type:
- approximate_member_count
The approximate number of members in the guild.
- Type:
Optional[
int
]
- approximate_presence_count
The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded.
- Type:
Optional[
int
]
- channel
The channel the invite is for.
- Type:
Union[
abc.GuildChannel
,Object
,PartialInviteChannel
]
- await delete(*, reason=None)
This function is a coroutine.
Revokes the instant invite.
You must have the
manage_channels
permission to do this.- Parameters:
reason (Optional[
str
]) – The reason for deleting this invite. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to revoke invites.
NotFound – The invite is invalid or expired.
HTTPException – Revoking the invite failed.
Template
- asynccreate_guild
- asyncdelete
- asyncedit
- asyncsync
- class discord.Template
Represents a Discord template.
New in version 1.4.
- await create_guild(name, region=None, icon=None)
This function is a coroutine.
Creates a
Guild
using the template.Bot accounts in more than 10 guilds are not allowed to create guilds.
- Parameters:
name (
str
) – The name of the guild.region (
VoiceRegion
) – The region for the voice communication server. Defaults toVoiceRegion.us_west
.icon (
bytes
) – The bytes-like object representing the icon. SeeClientUser.edit()
for more details on what is expected.
- Raises:
HTTPException – Guild creation failed.
InvalidArgument – Invalid icon image format given. Must be PNG or JPG.
- Returns:
The guild created. This is not the same guild that is added to cache.
- Return type:
- await sync()
This function is a coroutine.
Sync the template to the guild’s current state.
You must have the
manage_guild
permission in the source guild to do this.New in version 1.7.
- Raises:
HTTPException – Editing the template failed.
Forbidden – You don’t have permissions to edit the template.
NotFound – This template does not exist.
- await edit(**kwargs)
This function is a coroutine.
Edit the template metadata.
You must have the
manage_guild
permission in the source guild to do this.New in version 1.7.
- Parameters:
- Raises:
HTTPException – Editing the template failed.
Forbidden – You don’t have permissions to edit the template.
NotFound – This template does not exist.
- await delete()
This function is a coroutine.
Delete the template.
You must have the
manage_guild
permission in the source guild to do this.New in version 1.7.
- Raises:
HTTPException – Editing the template failed.
Forbidden – You don’t have permissions to edit the template.
NotFound – This template does not exist.
WidgetChannel
- class discord.WidgetChannel
Represents a “partial” widget channel.
- x == y
Checks if two partial channels are the same.
- x != y
Checks if two partial channels are not the same.
- hash(x)
Return the partial channel’s hash.
- str(x)
Returns the partial channel’s name.
WidgetMember
- defavatar_url_as
- defbanner_url_as
- defis_avatar_animated
- defis_banner_animated
- defmentioned_in
- defpermissions_in
- class discord.WidgetMember
Represents a “partial” member of the widget’s guild.
- x == y
Checks if two widget members are the same.
- x != y
Checks if two widget members are not the same.
- hash(x)
Return the widget member’s hash.
- str(x)
Returns the widget member’s name#discriminator.
- nick
The member’s nickname.
- Type:
Optional[
str
]
- avatar
The member’s avatar hash.
- Type:
Optional[
str
]
- activity
The member’s activity.
- Type:
Optional[Union[
BaseActivity
,Spotify
]]
- deafened
Whether the member is currently deafened.
- Type:
Optional[
bool
]
- muted
Whether the member is currently muted.
- Type:
Optional[
bool
]
- suppress
Whether the member is currently being suppressed.
- Type:
Optional[
bool
]
- connected_channel
Which channel the member is connected to.
- Type:
Optional[
VoiceChannel
]
- property avatar_url
Returns an
Asset
for the avatar the user has.If the user does not have a traditional avatar, an asset for the default avatar is returned instead.
This is equivalent to calling
avatar_url_as()
with the default parameters (i.e. webp/gif detection and a size of 1024).- Type:
- avatar_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the avatar the user has.If the user does not have a traditional avatar, an asset for the default avatar is returned instead.
The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated avatars. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the avatar to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the avatar being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated avatars to. Defaults to ‘webp’size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
, or invalidsize
.- Returns:
The resulting CDN asset.
- Return type:
- property banner_url
Returns an asset for the banner the user has, if any. This is equal to calling
banner_url_as()
with the default arguments.
- banner_url_as(*, format=None, static_format='webp', size=1024)
Returns an
Asset
for the banner the user has. Could beNone
.The format must be one of ‘webp’, ‘jpeg’, ‘jpg’, ‘png’ or ‘gif’, and ‘gif’ is only valid for animated banners. The size must be a power of 2 between 16 and 4096.
- Parameters:
format (Optional[
str
]) – The format to attempt to convert the banner to. If the format isNone
, then it is automatically detected into either ‘gif’ or static_format depending on the banner being animated or not.static_format (Optional[
str
]) – Format to attempt to convert only non-animated banner to. Defaults to ‘webp’size (
int
) – The size of the image to display.
- Raises:
InvalidArgument – Bad image format passed to
format
orstatic_format
, or invalidsize
.- Returns:
The resulting CDN asset if any.
- Return type:
Optional[
Asset
]
- property color
A property that returns a color denoting the rendered color for the user. This always returns
Colour.default()
.There is an alias for this named
colour
.- Type:
- property colour
A property that returns a colour denoting the rendered colour for the user. This always returns
Colour.default()
.There is an alias for this named
color
.- Type:
- property created_at
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
- Type:
- property default_avatar
Returns the default avatar for a given user. This is calculated by the user’s discriminator.
- Type:
- is_avatar_animated()
bool
: Indicates if the user has an animated avatar.
- is_banner_animated()
bool
: Indicates if the user has an animated banner.
- permissions_in(channel)
An alias for
abc.GuildChannel.permissions_for()
.Basically equivalent to:
channel.permissions_for(self)
- Parameters:
channel (
abc.GuildChannel
) – The channel to check your permissions for.
Widget
- asyncfetch_invite
- class discord.Widget
Represents a
Guild
widget.- x == y
Checks if two widgets are the same.
- x != y
Checks if two widgets are not the same.
- str(x)
Returns the widget’s JSON URL.
- channels
The accessible voice channels in the guild.
- Type:
Optional[List[
WidgetChannel
]]
- members
The online members in the server. Offline members do not appear in the widget.
Note
Due to a Discord limitation, if this data is available the users will be “anonymized” with linear IDs and discriminator information being incorrect. Likewise, the number of members retrieved is capped.
- Type:
Optional[List[
Member
]]
- property invite_url
The invite URL for the guild, if available.
- Type:
Optional[
str
]
- await fetch_invite(*, with_counts=True)
This function is a coroutine.
Retrieves an
Invite
from a invite URL or ID. This is the same asClient.fetch_invite()
; the invite code is abstracted away.- Parameters:
with_counts (
bool
) – Whether to include count information in the invite. This fills theInvite.approximate_member_count
andInvite.approximate_presence_count
fields.- Returns:
The invite from the URL/ID.
- Return type:
StickerPack
- defbanner_url_as
- defget_sticker
- class discord.StickerPack
Represents a pack of build-in stickers
- cover_sticker_id
The id of a sticker in the pack which is shown in the client as the pack’s icon.
- Type:
Optional[
int
]
- property stickers
The stickers of the pack
- Type:
Tuple[
Sticker
]
- property banner_url
Returns an
Asset
for the sticker pack’s banner.- Returns:
The resulting CDN asset.
- Return type:
- banner_url_as(format='png', size=1024)
Returns an
Asset
for the sticker pack’s banner.The size must be a power of 2 between 16 and 4096.
- Returns:
The resulting CDN asset.
- Return type:
Sticker
- defimage_url_as
- class discord.Sticker
Represents a sticker.
New in version 1.6.
- str(x)
Returns the name of the sticker.
- x == y
Checks if the sticker is equal to another sticker.
- x != y
Checks if the sticker is not equal to another sticker.
- tags
A list of tags for the sticker.
- Type:
List[
str
]
- pack
The pack the sticker belongs to. Could be
None
even ifSticker.pack_id
is present.- Type:
Optional[
StickerPack
]
- sort_value
The sticker’s sort order within its
Sticker.pack
.- Type:
- asyncdelete
- asyncedit
- defimage_url_as
- class discord.GuildSticker
Represents a “custom” sticker in a guild
- tags
A list of tags for the sticker.
- Type:
List[
str
]
- available
Whether this guild sticker can be used, may be
False
due to loss of Server Boosts- Type:
- await edit(*, reason=None, **fields)
This function is a coroutine.
Modify the sticker.
Requires the
MANAGE_EMOJIS_AND_STICKERS
permission.- Parameters:
name (
str
) – The name of the sticker; 2-30 characters long.description (Optional[
str
]) – The description of the sticker;None
or 2-100 characters long.tags (Union[
str
, List[str
]]) – The autocomplete/suggestion tags for the sticker. A string in which the individual tags are separated by,
or a list of tags; (max 200 characters).reason (Optional[
str
]) – The reason for modifying the sticker, shows up in the audit-log.
- Raises:
discord.Forbidden: – You don’t have the required permission to edit the sticker.
discord.HTTPException: – Editing the sticker failed.
ValueError: – Any of name, description or tags is invalid.
- Returns:
The updated sticker on success.
- Return type:
- await delete(*, reason)
This function is a coroutine.
Delete the sticker.
Requires the
MANAGE_EMOJIS_AND_STICKERS
permission.- Parameters:
reason (Optional[
str
]) – The reason for deleting the sticker, shows up in the audit-log.- Raises:
discord.Forbidden: – You don’t have the required permissions to delete the sticker.
discord.HTTPException: – Deleting the sticker failed.
- Returns:
The sticker that was deleted.
- Return type:
RawMessageDeleteEvent
- class discord.RawMessageDeleteEvent
Represents the event payload for a
on_raw_message_delete()
event.- guild_id
The guild ID where the deletion took place, if applicable.
- Type:
Optional[
int
]
- cached_message
The cached message, if found in the internal message cache.
- Type:
Optional[
Message
]
RawBulkMessageDeleteEvent
- class discord.RawBulkMessageDeleteEvent
Represents the event payload for a
on_raw_bulk_message_delete()
event.- guild_id
The guild ID where the message got deleted, if applicable.
- Type:
Optional[
int
]
- cached_messages
The cached messages, if found in the internal message cache.
- Type:
List[
Message
]
RawMessageUpdateEvent
- class discord.RawMessageUpdateEvent
Represents the payload for a
on_raw_message_edit()
event.- guild_id
The guild ID where the message got updated, if applicable.
New in version 1.7.
- Type:
Optional[
int
]
- cached_message
The cached message, if found in the internal message cache. Represents the message before it is modified by the data in
RawMessageUpdateEvent.data
.- Type:
Optional[
Message
]
RawReactionActionEvent
- class discord.RawReactionActionEvent
Represents the payload for a
on_raw_reaction_add()
oron_raw_reaction_remove()
event.- guild_id
The guild ID where the reaction got added or removed, if applicable.
- Type:
Optional[
int
]
- member
The member who added the reaction. Only available if event_type is REACTION_ADD and the reaction is inside a guild.
New in version 1.3.
- Type:
Optional[
Member
]
RawReactionClearEvent
- class discord.RawReactionClearEvent
Represents the payload for a
on_raw_reaction_clear()
event.- guild_id
The guild ID where the reactions got cleared.
- Type:
Optional[
int
]
RawReactionClearEmojiEvent
- class discord.RawReactionClearEmojiEvent
Represents the payload for a
on_raw_reaction_clear_emoji()
event.New in version 1.3.
- guild_id
The guild ID where the reactions got cleared.
- Type:
Optional[
int
]
Data Classes
Some classes are just there to be data containers, this lists them.
Unlike models you are allowed to create most of 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 abc.Snowflake
, which is made with
dynamic attributes in mind.
Object
- class discord.Object(id, type=MISSING, *, state=MISSING)
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.
Embed
- clsEmbed.from_dict
- defadd_field
- defclear_fields
- defcopy
- definsert_field_at
- defremove_author
- defremove_field
- defset_author
- defset_field_at
- defset_footer
- defset_image
- defset_thumbnail
- defto_dict
- class discord.Embed(*, title=Embed.Empty, description=Embed.Empty, color=Embed.Empty, timestamp=Embed.Empty, url=Embed.Empty, type='rich', colour=Embed.Empty)
Represents a Discord embed.
- len(x)
Returns the total size of the embed. Useful for checking if it’s within the 6000-character limit.
Certain properties return an
EmbedProxy
, a type that acts similar to a regulardict
except using 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 cast tostr
for you.- type
The type of embed. Usually “rich”. This can be set during initialisation. Possible strings for embed types can be found on discord’s api docs
- Type:
- colour
The colour code of the embed. Aliased to
color
as well. This can be set during initialisation.
- Empty
A special sentinel value used by
EmbedProxy
and this class to denote that the value or attribute is empty.
- classmethod from_dict(data)
Converts a
dict
to aEmbed
provided it is in the format that Discord expects it to be in.You can find out about this format in the official Discord documentation.
- Parameters:
data (
dict
) – The dictionary to convert into an embed.
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.- Type:
Union[
EmbedProxy
,Empty
]
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
- property 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.- Type:
Union[
EmbedProxy
,Empty
]
- set_image(*, url)
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing
Empty
removes the image.- Parameters:
url (
str
) – The source URL for the image. Only HTTP(S) and discords attachment:// protocol is supported.
- property 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.- Type:
Union[
EmbedProxy
,Empty
]
- set_thumbnail(*, url)
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing
Empty
removes the thumbnail.- Parameters:
url (
str
) – The source URL for the thumbnail. Only HTTP(S) and discords attachment:// protocol is supported.
- property 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.- Type:
Union[
EmbedProxy
,Empty
]
- property provider
Returns an
EmbedProxy
denoting the provider contents.The only attributes that might be accessed are
name
andurl
.If the attribute has no value then
Empty
is returned.- Type:
Union[
EmbedProxy
,Empty
]
- property 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.- Type:
Union[
EmbedProxy
,Empty
]
- 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.
- remove_author()
Clears embed’s author information.
This function returns the class instance to allow for fluent-style chaining.
New in version 1.4.
- property fields
Returns a
list
ofEmbedProxy
denoting the field contents.See
add_field()
for possible values you can access.If the attribute has no value then
Empty
is returned.- Type:
List[Union[
EmbedProxy
,Empty
]]
- 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.
- insert_field_at(index, *, name, value, inline=True)
Inserts a field before a specified index to the embed.
This function returns the class instance to allow for fluent-style chaining.
New in version 1.2.
- 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:
- Raises:
IndexError – An invalid index was provided.
AllowedMentions
- class discord.AllowedMentions(*, everyone=True, users=True, roles=True, replied_user=True)
A class that represents what mentions are allowed in a message.
This class can be set during
Client
initialisation to apply to every message sent. It can also be applied on a per message basis viaabc.Messageable.send()
for more fine-grained control.- users
Controls the users being mentioned. If
True
(the default) then users are mentioned based on the message content. IfFalse
then users are not mentioned at all. If a list ofabc.Snowflake
is given then only the users provided will be mentioned, provided those users are in the message content.- Type:
Union[
bool
, List[abc.Snowflake
]]
- roles
Controls the roles being mentioned. If
True
(the default) then roles are mentioned based on the message content. IfFalse
then roles are not mentioned at all. If a list ofabc.Snowflake
is given then only the roles provided will be mentioned, provided those roles are in the message content.- Type:
Union[
bool
, List[abc.Snowflake
]]
- replied_user
Whether to mention the author of the message being replied to. Defaults to
True
.New in version 1.6.
- Type:
- classmethod all()
A factory method that returns a
AllowedMentions
with all fields explicitly set toTrue
New in version 1.5.
- classmethod none()
A factory method that returns a
AllowedMentions
with all fields set toFalse
New in version 1.5.
MessageReference
- class discord.MessageReference(*, message_id, channel_id, guild_id=None, fail_if_not_exists=True)
Represents a reference to a
Message
.New in version 1.5.
Changed in version 1.6: This class can now be constructed by users.
- message_id
The id of the message referenced.
- Type:
Optional[
int
]
- guild_id
The guild id of the message referenced.
- Type:
Optional[
int
]
- fail_if_not_exists
Whether replying to the referenced message should raise
HTTPException
if the message no longer exists or Discord could not fetch the message.New in version 1.7.
- Type:
- resolved
The message that this reference resolved to. If this is
None
then the original message was not fetched either due to the Discord API not attempting to resolve it or it not being available at the time of creation. If the message was resolved at a prior point but has since been deleted then this will be of typeDeletedReferencedMessage
.Currently, this is mainly the replied to message when a user replies to a message.
New in version 1.6.
- Type:
Optional[Union[
Message
,DeletedReferencedMessage
]]
- classmethod from_message(message, *, fail_if_not_exists=True)
Creates a
MessageReference
from an existingMessage
.New in version 1.6.
- Parameters:
message (
Message
) – The message to be converted into a reference.fail_if_not_exists (
bool
) –Whether replying to the referenced message should raise
HTTPException
if the message no longer exists or Discord could not fetch the message.New in version 1.7.
- Returns:
A reference to the message.
- Return type:
- property cached_message
The cached message, if found in the internal message cache.
- Type:
Optional[
Message
]
PartialMessage
- asyncadd_reaction
- asyncclear_reaction
- asyncclear_reactions
- asynccreate_thread
- asyncdelete
- asyncedit
- asyncfetch
- asyncpin
- asyncpublish
- asyncremove_reaction
- asyncreply
- defto_reference
- asyncunpin
- class discord.PartialMessage(*, channel, id)
Represents a partial message to aid with working messages when only a message and channel ID are present.
There are two ways to construct this class. The first one is through the constructor itself, and the second is via
TextChannel.get_partial_message()
orDMChannel.get_partial_message()
.Note that this class is trimmed down and has no rich attributes.
New in version 1.6.
- x == y
Checks if two partial messages are equal.
- x != y
Checks if two partial messages are not equal.
- hash(x)
Returns the partial message’s hash.
- channel
The channel associated with this partial message.
- Type:
Union[
TextChannel
,ThreadChannel
,DMChannel
]
- guild
The guild that the partial message belongs to, if applicable.
- Type:
Optional[
Guild
]
- await fetch()
This function is a coroutine.
Fetches the partial message to a full
Message
.- Raises:
NotFound – The message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- Returns:
The full message.
- Return type:
- await edit(*, content=MISSING, embed=MISSING, embeds=MISSING, components=MISSING, attachments=MISSING, delete_after=None, allowed_mentions=MISSING, suppress_embeds=MISSING)
This function is a coroutine.
Edits the message.
The content must be able to be transformed into a string via
str(content)
.Changed in version 1.3: The
suppress
keyword-only parameter was added.Changed in version 2.0: The
components
andattachments
parameters were added.Changed in version 2.0: The
suppress
keyword-only parameter was renamed tosuppress_embeds
.Warning
Since API v10, the
attachments
(when passed) must contain all attachments that should be present after edit, including retained and new attachments.As this requires to know the current attachments consider either storing the attachments that were sent with a message or using a fetched version of the message to edit it.
- Parameters:
content (Optional[
str
]) – The new content to replace the message with. Could beNone
to remove the content.embed (Optional[
Embed
]) – The new embed to replace the original with. Could beNone
to remove all embeds.embeds (Optional[List[
Embed
]]) –A list containing up to 10 embeds`to send. If
None
or empty, all embeds will be removed.If passed,
embed
does also count towards the limit of 10 embeds.components (List[Union[
ActionRow
, List[Union[Button
,BaseSelect
]]]]) – A list of up to fiveButton
’s or oneBaseSelect
like object.attachments (List[Union[
Attachment
,File
]]) –A list containing previous attachments to keep as well as new files to upload.
When
None
or empty, all attachment will be removed.Note
New files will always appear under existing ones.
suppress_embeds (
bool
) – Whether to suppress embeds for the message. This removes all the embeds if set toTrue
. If set toFalse
this brings the embeds back if they were suppressed. Requiresmanage_messages
for messages that aren’t from the bot.delete_after (Optional[
float
]) – If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.allowed_mentions (Optional[
AllowedMentions
]) – Controls the mentions being processed in this message. If this is passed, then the object is merged withallowed_mentions
. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions
. If no object is passed at all then the defaults given byallowed_mentions
are used instead.
- Raises:
NotFound – The message was not found.
HTTPException – Editing the message failed.
Forbidden – Tried to suppress the embeds a message without permissions or edited a message’s content or embed that isn’t yours.
- Returns:
The message that was edited.
- Return type:
Optional[
Message
]
- await add_reaction(emoji)
This function is a coroutine.
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild
Emoji
.You must have the
read_message_history
permission to use this. If nobody else has reacted to the message using this emoji, theadd_reactions
permission is required.- Parameters:
emoji (Union[
Emoji
,Reaction
,PartialEmoji
,str
]) – The emoji to react with.- Raises:
HTTPException – Adding the reaction failed.
Forbidden – You do not have the proper permissions to react to the message.
NotFound – The emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- await clear_reaction(emoji)
This function is a coroutine.
Clears a specific reaction from the message.
The emoji may be a unicode emoji or a custom guild
Emoji
.You need the
manage_messages
permission to use this.New in version 1.3.
- Parameters:
emoji (Union[
Emoji
,Reaction
,PartialEmoji
,str
]) – The emoji to clear.- Raises:
HTTPException – Clearing the reaction failed.
Forbidden – You do not have the proper permissions to clear the reaction.
NotFound – The emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- await clear_reactions()
This function is a coroutine.
Removes all the reactions from the message.
You need the
manage_messages
permission to use this.- Raises:
HTTPException – Removing the reactions failed.
Forbidden – You do not have the proper permissions to remove all the reactions.
- await create_thread(name, auto_archive_duration=None, slowmode_delay=0, reason=None)
This function is a coroutine.
Creates a new thread in the channel of the message with this message as the
starter_message
.- Parameters:
name (
str
) – The name of the thread.auto_archive_duration (Optional[
AutoArchiveDuration
]) – Amount of time after that the thread will auto-hide from the channel listslowmode_delay (
int
) – Amount of seconds a user has to wait before sending another message (0-21600)reason (Optional[
str
]) – The reason for creating the thread. Shows up in the audit log.
- Raises:
TypeError – The channel of the message is not a text or news channel, or the message has already a thread, or
auto_archive_duration
is not a valid member ofAutoArchiveDuration
ValueError – The
name
is of invalid lengthForbidden – The bot is missing permissions to create threads in this channel
HTTPException – Creating the thread failed
- Returns:
The created thread on success
- Return type:
- await delete(*, delay=None)
This function is a coroutine.
Deletes the message.
Your own messages could be deleted without any proper permissions. However, to delete other people’s messages, you need the
manage_messages
permission.Changed in version 1.1: Added the new
delay
keyword-only parameter.- Parameters:
delay (Optional[
float
]) – If provided, the number of seconds to wait in the background before deleting the message. If the deletion fails then it is silently ignored.- Raises:
Forbidden – You do not have proper permissions to delete the message.
NotFound – The message was deleted already
HTTPException – Deleting the message failed.
- await pin(*, reason=None)
This function is a coroutine.
Pins the message.
You must have the
manage_messages
permission to do this in a non-private channel context.- Parameters:
reason (Optional[
str
]) –The reason for pinning the message. Shows up on the audit log.
New in version 1.4.
- Raises:
Forbidden – You do not have permissions to pin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Pinning the message failed, probably due to the channel having more than 50 pinned messages.
- await publish()
This function is a coroutine.
Publishes this message to your announcement channel.
If the message is not your own then the
manage_messages
permission is needed.- Raises:
Forbidden – You do not have the proper permissions to publish this message.
HTTPException – Publishing the message failed.
- await 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 themanage_messages
permission is needed.The
member
parameter must represent a member and meet theabc.Snowflake
abc.- Parameters:
emoji (Union[
Emoji
,Reaction
,PartialEmoji
,str
]) – The emoji to remove.member (
abc.Snowflake
) – The member for which to remove the reaction.
- Raises:
HTTPException – Removing the reaction failed.
Forbidden – You do not have the proper permissions to remove the reaction.
NotFound – The member or emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- await reply(content=None, tts=False, embed=None, embeds=None, components=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, mention_author=None, suppress_embeds=False, suppress_notifications=False)
This function is a coroutine.
A shortcut method to
abc.Messageable.send()
to reply to theMessage
.New in version 1.6.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
files
list is not of the appropriate size or you specified bothfile
andfiles
.
- Returns:
The message that was sent.
- Return type:
- to_reference(*, fail_if_not_exists=True)
Creates a
MessageReference
from the current message.New in version 1.6.
- Parameters:
fail_if_not_exists (
bool
) –Whether replying using the message reference should raise
HTTPException
if the message no longer exists or Discord could not fetch the message.New in version 1.7.
- Returns:
The reference to this message.
- Return type:
- await unpin(*, reason=None)
This function is a coroutine.
Unpins the message.
You must have the
manage_messages
permission to do this in a non-private channel context.- Parameters:
reason (Optional[
str
]) –The reason for unpinning the message. Shows up on the audit log.
New in version 1.4.
- Raises:
Forbidden – You do not have permissions to unpin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Unpinning the message failed.
Intents
- clsIntents.all
- clsIntents.default
- clsIntents.none
- class discord.Intents(**kwargs)
Wraps up a Discord gateway intent flag.
Similar to
Permissions
, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the
intents
keyword argument ofClient
.New in version 1.5.
- x == y
Checks if two flags are equal.
- x != y
Checks if two flags are not equal.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)
pairs. This allows it to be, for example, constructed as a dict or a list of pairs.
- value
The raw value. You should query flags via the properties rather than using this raw value.
- Type:
- classmethod all()
A factory method that creates a
Intents
with everything enabled.
- classmethod none()
A factory method that creates a
Intents
with everything disabled.
- classmethod default()
A factory method that creates a
Intents
with everything enabled exceptpresences
,members
andmessage_content
(privileged intents).
- guilds
Whether guild related events are enabled.
This corresponds to the following events:
This also corresponds to the following attributes and classes in terms of cache:
Guild
and all its attributes.
It is highly advisable to leave this intent enabled for your bot to function.
- Type:
- members
Whether guild member related events are enabled.
This corresponds to the following events:
on_member_update()
(nickname, roles)
This also corresponds to the following attributes and classes in terms of cache:
For more information go to the member intent documentation.
Note
Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification.
- Type:
- bans
Whether guild ban related events are enabled.
This corresponds to the following events:
This does not correspond to any attributes or classes in the library in terms of cache.
- Type:
- emojis
Whether guild emoji related events are enabled.
This corresponds to the following events:
This also corresponds to the following attributes and classes in terms of cache:
- Type:
- integrations
Whether guild integration related events are enabled.
This corresponds to the following events:
This does not correspond to any attributes or classes in the library in terms of cache.
- Type:
- webhooks
Whether guild webhook related events are enabled.
This corresponds to the following events:
This does not correspond to any attributes or classes in the library in terms of cache.
- Type:
- invites
Whether guild invite related events are enabled.
This corresponds to the following events:
This does not correspond to any attributes or classes in the library in terms of cache.
- Type:
- voice_states
Whether guild voice state related events are enabled.
This corresponds to the following events:
This also corresponds to the following attributes and classes in terms of cache:
- Type:
- presences
Whether guild presence related events are enabled.
This corresponds to the following events:
on_member_update()
(activities, status)
This also corresponds to the following attributes and classes in terms of cache:
For more information go to the presence intent documentation.
Note
Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification.
- Type:
- messages
Whether guild and direct message related events are enabled.
This is a shortcut to set or get both
guild_messages
anddm_messages
.This corresponds to the following events:
on_message()
(both guilds and DMs)on_message_edit()
(both guilds and DMs)on_message_delete()
(both guilds and DMs)on_raw_message_delete()
(both guilds and DMs)on_raw_message_edit()
(both guilds and DMs)
This also corresponds to the following attributes and classes in terms of cache:
Note that due to an implicit relationship this also corresponds to the following events:
on_reaction_add()
(both guilds and DMs)on_reaction_remove()
(both guilds and DMs)on_reaction_clear()
(both guilds and DMs)
- Type:
- guild_messages
Whether guild message related events are enabled.
See also
dm_messages
for DMs ormessages
for both.This corresponds to the following events:
on_message()
(only for guilds)on_message_edit()
(only for guilds)on_message_delete()
(only for guilds)on_raw_message_delete()
(only for guilds)on_raw_message_edit()
(only for guilds)
This also corresponds to the following attributes and classes in terms of cache:
Client.cached_messages
(only for guilds)
Note that due to an implicit relationship this also corresponds to the following events:
on_reaction_add()
(only for guilds)on_reaction_remove()
(only for guilds)on_reaction_clear()
(only for guilds)
- Type:
- dm_messages
Whether direct message related events are enabled.
See also
guild_messages
for guilds ormessages
for both.This corresponds to the following events:
on_message()
(only for DMs)on_message_edit()
(only for DMs)on_message_delete()
(only for DMs)on_raw_message_delete()
(only for DMs)on_raw_message_edit()
(only for DMs)
This also corresponds to the following attributes and classes in terms of cache:
Client.cached_messages
(only for DMs)
Note that due to an implicit relationship this also corresponds to the following events:
on_reaction_add()
(only for DMs)on_reaction_remove()
(only for DMs)on_reaction_clear()
(only for DMs)
- Type:
- reactions
Whether guild and direct message reaction related events are enabled.
This is a shortcut to set or get both
guild_reactions
anddm_reactions
.This corresponds to the following events:
on_reaction_add()
(both guilds and DMs)on_reaction_remove()
(both guilds and DMs)on_reaction_clear()
(both guilds and DMs)on_raw_reaction_add()
(both guilds and DMs)on_raw_reaction_remove()
(both guilds and DMs)on_raw_reaction_clear()
(both guilds and DMs)
This also corresponds to the following attributes and classes in terms of cache:
Message.reactions
(both guild and DM messages)
- Type:
- guild_reactions
Whether guild message reaction related events are enabled.
See also
dm_reactions
for DMs orreactions
for both.This corresponds to the following events:
on_reaction_add()
(only for guilds)on_reaction_remove()
(only for guilds)on_reaction_clear()
(only for guilds)on_raw_reaction_add()
(only for guilds)on_raw_reaction_remove()
(only for guilds)on_raw_reaction_clear()
(only for guilds)
This also corresponds to the following attributes and classes in terms of cache:
Message.reactions
(only for guild messages)
- Type:
- dm_reactions
Whether direct message reaction related events are enabled.
See also
guild_reactions
for guilds orreactions
for both.This corresponds to the following events:
on_reaction_add()
(only for DMs)on_reaction_remove()
(only for DMs)on_reaction_clear()
(only for DMs)on_raw_reaction_add()
(only for DMs)on_raw_reaction_remove()
(only for DMs)on_raw_reaction_clear()
(only for DMs)
This also corresponds to the following attributes and classes in terms of cache:
Message.reactions
(only for DM messages)
- Type:
- typing
Whether guild and direct message typing related events are enabled.
This is a shortcut to set or get both
guild_typing
anddm_typing
.This corresponds to the following events:
on_typing()
(both guilds and DMs)
This does not correspond to any attributes or classes in the library in terms of cache.
- Type:
- guild_typing
Whether guild and direct message typing related events are enabled.
See also
dm_typing
for DMs ortyping
for both.This corresponds to the following events:
on_typing()
(only for guilds)
This does not correspond to any attributes or classes in the library in terms of cache.
- Type:
- dm_typing
Whether guild and direct message typing related events are enabled.
See also
guild_typing
for guilds ortyping
for both.This corresponds to the following events:
on_typing()
(only for DMs)
This does not correspond to any attributes or classes in the library in terms of cache.
- Type:
- message_content
Whether to receive the content, embeds, attachments and components of a message.
Note
The bot will still receive these fields when the message is in a privat chat with the bot, or the bot is mentioned in the message.
This corresponds to the following events:
on_message()
(content, embeds, attachments, components)on_message_edit()
(content, embeds, attachments, components)on_raw_message_edit()
(cached_message)on_message_delete()
(content, embeds, attachments, components)on_raw_message_delete()
(cached_message)on_bulk_message_delete()
(content, embeds, attachments, components)on_raw_bulk_message_delete()
(cached_messages)on_auto_moderation_action()
(content, matched_content)
This also corresponds to the following attributes and classes:
For more information go to the message-content intent documentation .
Note
Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification.
- Type:
- scheduled_events
Whether to receive events related to creating, updating and deleting scheduled events. Also, whether to receive events when a user is added or removed (interested).
This corresponds to the following events:
on_scheduled_event_create()
on_scheduled_event_update()
on_scheduled_event_delete()
on_scheduled_event_user_add()
on_scheduled_event_user_remove()
- Type:
- auto_moderation_configurations
Whether to receive events related to creating, updating and deleting auto moderation rules.
This corresponds to the following events:
on_auto_moderation_rule_create()
on_auto_moderation_rule_update()
on_auto_moderation_rule_delete()
- Type:
MemberCacheFlags
- class discord.MemberCacheFlags(**kwargs)
Controls the library’s cache policy when it comes to members.
This allows for finer grained control over what members are cached. Note that the bot’s own member is always cached. This class is passed to the
member_cache_flags
parameter inClient
.Due to a quirk in how Discord works, in order to ensure proper cleanup of cache resources it is recommended to have
Intents.members
enabled. Otherwise the library cannot know when a member leaves a guild and is thus unable to cleanup after itself.To construct an object you can pass keyword arguments denoting the flags to enable or disable.
The default value is all flags enabled.
New in version 1.5.
- x == y
Checks if two flags are equal.
- x != y
Checks if two flags are not equal.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)
pairs. This allows it to be, for example, constructed as a dict or a list of pairs.
- value
The raw value. You should query flags via the properties rather than using this raw value.
- Type:
- classmethod all()
A factory method that creates a
MemberCacheFlags
with everything enabled.
- classmethod none()
A factory method that creates a
MemberCacheFlags
with everything disabled.
- online
Whether to cache members with a status.
For example, members that are part of the initial
GUILD_CREATE
or become online at a later point. This requiresIntents.presences
.Members that go offline are no longer cached.
- Type:
- voice
Whether to cache members that are in voice.
This requires
Intents.voice_states
.Members that leave voice are no longer cached.
- Type:
- joined
Whether to cache members that joined the guild or are chunked as part of the initial log in flow.
This requires
Intents.members
.Members that leave the guild are no longer cached.
- Type:
- classmethod from_intents(intents)
A factory method that creates a
MemberCacheFlags
based on the currently selectedIntents
.- Parameters:
intents (
Intents
) – The intents to select from.- Returns:
The resulting member cache flags.
- Return type:
File
- class discord.File(fp, filename=None, description=None, *, spoiler=False)
A parameter object used for
abc.Messageable.send()
for sending file objects.Note
File objects are single use and are not meant to be reused in multiple
abc.Messageable.send()
s.- fp
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
.- Type:
Union[
str
,io.BufferedIOBase
]
- filename
The filename to display when uploading to Discord. If this is not given then it defaults to
fp.name
or iffp
is a string then thefilename
will default to the string given.- Type:
Optional[
str
]
- description
The file description can be set to attached images to show a alternative text.
- Type:
Optional[
str
:]
ForumTag
- class discord.ForumTag
Represents a tag in a
ForumChannel
.Note
The
id
andguild
attributes are only available if the instance is not self created.- property emoji
The emoji that is set for this post, if any
- Type:
Optional[
PartialEmoji
]
Colour
- clsColour.blue
- clsColour.blurple
- clsColour.dark_blue
- clsColour.dark_gold
- clsColour.dark_gray
- clsColour.dark_green
- clsColour.dark_grey
- clsColour.dark_magenta
- clsColour.dark_orange
- clsColour.dark_purple
- clsColour.dark_red
- clsColour.dark_teal
- clsColour.dark_theme
- clsColour.darker_gray
- clsColour.darker_grey
- clsColour.default
- clsColour.from_hsv
- clsColour.from_rgb
- clsColour.gold
- clsColour.green
- clsColour.greyple
- clsColour.light_gray
- clsColour.light_grey
- clsColour.lighter_gray
- clsColour.lighter_grey
- clsColour.magenta
- clsColour.orange
- clsColour.purple
- clsColour.random
- clsColour.red
- clsColour.teal
- defto_rgb
- class discord.Colour(value)
Represents a Discord role colour. This class is similar to a (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.
- 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 of0
.
- classmethod random(*, seed=None)
A factory method that returns a
Colour
with a random hue.Note
The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value.
New in version 1.6.
- classmethod teal()
A factory method that returns a
Colour
with a value of0x1abc9c
.
- classmethod dark_teal()
A factory method that returns a
Colour
with a value of0x11806a
.
- classmethod green()
A factory method that returns a
Colour
with a value of0x2ecc71
.
- classmethod dark_green()
A factory method that returns a
Colour
with a value of0x1f8b4c
.
- classmethod blue()
A factory method that returns a
Colour
with a value of0x3498db
.
- classmethod dark_blue()
A factory method that returns a
Colour
with a value of0x206694
.
- classmethod purple()
A factory method that returns a
Colour
with a value of0x9b59b6
.
- classmethod dark_purple()
A factory method that returns a
Colour
with a value of0x71368a
.
- classmethod magenta()
A factory method that returns a
Colour
with a value of0xe91e63
.
- classmethod dark_magenta()
A factory method that returns a
Colour
with a value of0xad1457
.
- classmethod gold()
A factory method that returns a
Colour
with a value of0xf1c40f
.
- classmethod dark_gold()
A factory method that returns a
Colour
with a value of0xc27c0e
.
- classmethod orange()
A factory method that returns a
Colour
with a value of0xe67e22
.
- classmethod dark_orange()
A factory method that returns a
Colour
with a value of0xa84300
.
- classmethod red()
A factory method that returns a
Colour
with a value of0xe74c3c
.
- classmethod dark_red()
A factory method that returns a
Colour
with a value of0x992d22
.
- classmethod lighter_grey()
A factory method that returns a
Colour
with a value of0x95a5a6
.
- classmethod lighter_gray()
A factory method that returns a
Colour
with a value of0x95a5a6
.
- classmethod dark_grey()
A factory method that returns a
Colour
with a value of0x607d8b
.
- classmethod dark_gray()
A factory method that returns a
Colour
with a value of0x607d8b
.
- classmethod light_grey()
A factory method that returns a
Colour
with a value of0x979c9f
.
- classmethod light_gray()
A factory method that returns a
Colour
with a value of0x979c9f
.
- classmethod darker_grey()
A factory method that returns a
Colour
with a value of0x546e7a
.
- classmethod darker_gray()
A factory method that returns a
Colour
with a value of0x546e7a
.
- classmethod blurple()
A factory method that returns a
Colour
with a value of0x7289da
.
- classmethod greyple()
A factory method that returns a
Colour
with a value of0x99aab5
.
- classmethod dark_theme()
A factory method that returns a
Colour
with a value of0x36393F
. This will appear transparent on Discord’s dark theme.New in version 1.5.
BaseActivity
- class discord.BaseActivity(**kwargs)
The base activity that all user-settable activities inherit from. A user-settable activity is one that can be used in
Client.change_presence()
.The following types currently count as user-settable:
Note that although these types are considered user-settable by the library, Discord typically ignores certain combinations of activity depending on what is currently set. This behaviour may change in the future so there are no guarantees on whether Discord will actually let you set these types.
New in version 1.3.
- property created_at
When the user started doing this activity in UTC.
New in version 1.3.
- Type:
Optional[
datetime.datetime
]
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:
- timestamps
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.
- Type:
- assets
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.
- Type:
- party
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).
- Type:
- emoji
The emoji that belongs to this activity.
- Type:
Optional[
PartialEmoji
]
- property start
When the user started doing this activity in UTC, if applicable.
- Type:
Optional[
datetime.datetime
]
- property end
When the user will stop doing this activity in UTC, if applicable.
- Type:
Optional[
datetime.datetime
]
- property large_image_url
Returns a URL pointing to the large image asset of this activity if applicable.
- Type:
Optional[
str
]
- property small_image_url
Returns a URL pointing to the small image asset of this activity if applicable.
- Type:
Optional[
str
]
- property large_image_text
Returns the large image asset hover text of this activity if applicable.
- Type:
Optional[
str
]
- property small_image_text
Returns the small image asset hover text of this activity if applicable.
- Type:
Optional[
str
]
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.
- property type
Returns the game’s type. This is for compatibility with
Activity
.It always returns
ActivityType.playing
.- Type:
- property start
When the user started playing this game in UTC, if applicable.
- Type:
Optional[
datetime.datetime
]
- property end
When the user will stop playing this game in UTC, if applicable.
- Type:
Optional[
datetime.datetime
]
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
The stream’s name.
- Type:
Optional[
str
]
- game
The game being streamed.
New in version 1.3.
- Type:
Optional[
str
]
- assets
A dictionary comprising of similar keys than those in
Activity.assets
.- Type:
- property type
Returns the game’s type. This is for compatibility with
Activity
.It always returns
ActivityType.streaming
.- Type:
- property twitch_name
If provided, the twitch name of the user streaming.
This corresponds to the
large_image
key of theStreaming.assets
dictionary if it starts withtwitch:
. Typically set by the Discord client.- Type:
Optional[
str
]
CustomActivity
- class discord.CustomActivity(name, *, emoji=None, **extra)
Represents a Custom activity from Discord.
- 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 custom status text.
New in version 1.3.
- name
The custom activity’s name.
- Type:
Optional[
str
]
- emoji
The emoji to pass to the activity, if any.
- Type:
Optional[
PartialEmoji
]
- property type
Returns the activity’s type. This is for compatibility with
Activity
.It always returns
ActivityType.custom
.- Type:
Permissions
- add_reactions
- administrator
- attach_files
- ban_members
- change_nickname
- connect
- create_instant_invite
- create_private_threads
- create_public_threads
- deafen_members
- embed_links
- external_emojis
- kick_members
- manage_channels
- manage_emojis
- manage_emojis_and_stickers
- manage_events
- manage_guild
- manage_messages
- manage_nicknames
- manage_permissions
- manage_roles
- manage_stickers
- manage_threads
- manage_webhooks
- mention_everyone
- moderate_members
- move_members
- mute_members
- priority_speaker
- read_message_history
- read_messages
- request_to_speak
- send_messages
- send_messages_in_threads
- send_thread_messages
- send_tts_messages
- speak
- start_embedded_activities
- start_voice_activities
- stream
- timeout_members
- use_application_commands
- use_external_emojis
- use_external_stickers
- use_slash_commands
- use_voice_activation
- value
- view_audit_log
- view_channel
- view_guild_insights
- clsPermissions.advanced
- clsPermissions.all
- clsPermissions.all_channel
- clsPermissions.general
- clsPermissions.membership
- clsPermissions.none
- clsPermissions.stage
- clsPermissions.stage_moderator
- clsPermissions.text
- clsPermissions.voice
- defis_strict_subset
- defis_strict_superset
- defis_subset
- defis_superset
- defupdate
- class discord.Permissions(permissions=0, **kwargs)
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.
Changed in version 1.3: You can now use keyword arguments to initialize
Permissions
similar toupdate()
.- 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. Note that aliases are not shown.
- value
The raw value. This value is a bit array field of a 53-bit integer representing the currently available permissions. You should query permissions via the properties rather than using this raw value.
- Type:
- 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 toFalse
.
- classmethod all()
A factory method that creates a
Permissions
with all permissions set toTrue
.
- classmethod all_channel()
A
Permissions
with all channel-specific permissions set toTrue
and the guild-specific ones set toFalse
. The guild-specific permissions are currently:Changed in version 1.7: Added
stream
,priority_speaker
anduse_slash_commands
permissions.Changed in version 2.0: Added
start_embedded_activities
,moderate_members
,manage_events
,create_private_threads
,create_puplic_threads
,manage_threads
,send_messages_in_threads
,request_to_speak
anduse_external_stickers
- classmethod general()
A factory method that creates a
Permissions
with all “General” permissions from the official Discord UI set toTrue
.Changed in version 1.7: Permission
read_messages
is now included in the general permissions, but permissionsadministrator
,create_instant_invite
,kick_members
,ban_members
,change_nickname
andmanage_nicknames
are no longer part of the general permissions.
- classmethod membership()
A factory method that creates a
Permissions
with all “Membership” permissions from the official Discord UI set toTrue
.New in version 1.7.
- classmethod text()
A factory method that creates a
Permissions
with all “Text” permissions from the official Discord UI set toTrue
.Changed in version 1.7: Permission
read_messages
is no longer part of the text permissions. Addeduse_slash_commands
permission.
- classmethod voice()
A factory method that creates a
Permissions
with all “Voice” permissions from the official Discord UI set toTrue
.
- classmethod stage()
A factory method that creates a
Permissions
with all “Stage Channel” permissions from the official Discord UI set toTrue
.New in version 1.7.
- classmethod stage_moderator()
A factory method that creates a
Permissions
with all “Stage Moderator” permissions from the official Discord UI set toTrue
.New in version 1.7.
- classmethod advanced()
A factory method that creates a
Permissions
with all “Advanced” permissions from the official Discord UI set toTrue
.New in version 1.7.
- 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.
- administrator
Returns
True
if a user is an administrator. This role overrides all other permissions.This also bypasses all channel-specific overrides.
- Type:
- 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.
- Type:
- view_channel
An alias for
read_messages
.New in version 1.3.
- Type:
- send_tts_messages
Returns
True
if a user can send TTS messages from all or specific text channels.- Type:
- manage_messages
Returns
True
if a user can delete or pin messages in a text channel.Note
Note that there are currently no ways to edit other people’s messages.
- Type:
- mention_everyone
Returns
True
if a user’s @everyone or @here will mention everyone in the text channel.- Type:
- use_external_emojis
An alias for
external_emojis
.New in version 1.3.
- Type:
- 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.
- Type:
- manage_permissions
An alias for
manage_roles
.New in version 1.3.
- Type:
- manage_emojis_and_stickers
An aliase for
manage_emojis
- Type:
- manage_stickers
An aliase for
manage_emojis
- Type:
- use_slash_commands
Returns
True
if a user can use slash commands and context-menu commands.New in version 1.7.
- Type:
- use_application_commands
An aliase for
use_slash_commands
- Type:
- request_to_speak
Returns
True
if a user can request to speak in a stage channel.New in version 1.7.
- Type:
- manage_threads
Returns
True
if a user can delete and archive threads and viewing all private threads- Type:
- send_thread_messages
An alias for
send_messages_in_threads
.- Type:
- start_embedded_activities
Returns
True
if a user can start embedded activities in a voice channel (e.g. voice-activities).- Type:
- start_voice_activities
An alias for
start_embedded_activities
.- Type:
- moderate_members
Returns
True
if a user can moderate other members (like timeout or verify them).- Type:
- timeout_members
An alias for
moderate_members
.- Type:
PermissionOverwrite
- clsPermissionOverwrite.from_pair
- defis_empty
- defpair
- defupdate
- 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 toNone
and notFalse
. Setting a value toFalse
is explicitly denying that permission, while setting a value toTrue
is explicitly allowing that permission.The values supported by this are the same as
Permissions
with the added possibility of it being set toNone
.- x == y
Checks if two overwrites are equal.
- x != y
Checks if two overwrites are not equal.
- iter(x)
Returns an iterator of
(perm, value)
pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
- Parameters:
**kwargs – Set the value of permissions by their name.
- pair()
Tuple[
Permissions
,Permissions
]: Returns the (allow, deny) pair from this overwrite.
- 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
orFalse
.- Returns:
Indicates if the overwrite is empty.
- Return type:
- 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.
SystemChannelFlags
- class discord.SystemChannelFlags
Wraps up a Discord system channel flag value.
Similar to
Permissions
, 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 the system flags easily.To construct an object you can pass keyword arguments denoting the flags to enable or disable.
- x == y
Checks if two flags are equal.
- x != y
Checks if two flags are not equal.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)
pairs. This allows it to be, for example, constructed as a dict or a list of pairs.
- value
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type:
Returns
True
if the system channel is used for Nitro boosting notifications.- Type:
ChannelFlags
- class discord.ChannelFlags
Wraps up a Discord Channel flag value
- removed_from_active_now
Returns
True
if the channel is removed from the active now section in the guild’s home feed.- Type:
- require_tags
bool
: ReturnsTrue
if this channel is aForumChannel
that requires providing at least one tag when creating a post.
MessageFlags
- class discord.MessageFlags
Wraps up a Discord Message flag value.
See
SystemChannelFlags
.- x == y
Checks if two flags are equal.
- x != y
Checks if two flags are not equal.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)
pairs. This allows it to be, for example, constructed as a dict or a list of pairs.
New in version 1.3.
- value
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type:
- source_message_deleted
Returns
True
if the source message for this crosspost has been deleted.- Type:
- urgent
Returns
True
if the source message is an urgent message.An urgent message is one sent by Discord Trust and Safety.
- Type:
- has_thread
Returns
True
if the source message is associated with a thread.This message has an associated thread, with the same id as the message.
- Type:
- ephemeral
Returns
True
if the message ist ephemeral (hidden).This message is only visible to the user who invoked the Interaction.
- Type:
- loading
Returns
True
if the message is an interaction response and the bot is “thinking”.This message is an interaction response and the bot is “thinking”
- Type:
- failed_to_mention_some_roles_in_thread
Returns
True
if the message failed to mention some roles and add their members to the thread.- Type:
- suppress_notifications
Returns
True
if the message is “silent”.The user(s) will still see a mention in the channel, but no push or desktop notification will be sent.
- Type:
PublicUserFlags
- defall
- class discord.PublicUserFlags
Wraps up the Discord User Public flags.
- x == y
Checks if two PublicUserFlags are equal.
- x != y
Checks if two PublicUserFlags are not equal.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)
pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 1.4.
- value
The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value.
- Type:
- early_verified_bot_developer
An alias for
verified_bot_developer
.New in version 1.5.
- Type:
- bot_http_interactions
Returns
True
if a bot-user uses only HTTP interactions and is shown in the online member list- Type:
AutoModAction
- class discord.AutoModAction
Represents an action which will execute whenever a rule is triggered.
- Parameters:
type (
AutoModActionType
) – The type of actionchannel_id (Optional[
int
]) –The channel to which user content should be logged.
Note
This field is only required
type
is :attr:~`AutoModActionType.send_alert_message`timeout_duration (Optional[Union[
int
,datetime.timedelta
]]) –Duration in seconds (
int
) or a timerange (timedelta
) for wich the user should be timeouted.The maximum value is ``2419200`` seconds (4 weeks)
Note
This field is only required if
type
isAutoModActionType.timeout_user
AutoModTriggerMetadata
- class discord.AutoModTriggerMetadata
Additional data used to determine whether a rule should be triggered. Different fields are relevant based on the value of
AutoModRule.trigger_type
- Parameters:
keyword_filter (Optional[List[
str
]]) –Substrings which will be searched for in content
Note
This field is only present if
trigger_type
isAutoModTriggerType.keyword
regex_patterns (Optional[List[
Pattern
]]) –Regular expression patterns which will be matched against content (Maximum of 10, each max. 75 characters long)
Note
This field is only present if
trigger_type
iskeyword
presets (Optional[List[
AutoModKeywordPresetType
]]) –The internally pre-defined word sets which will be searched for in content
Note
This field is only present if
trigger_type
isAutoModTriggerType.keyword_preset
exempt_words (Optional[List[
str
]]) –Substrings which should be excluded from the blacklist.
Note
This field is only present if
trigger_type
isAutoModTriggerType.keyword_preset
total_mentions_limit (Optional[
int
]) –Total number of unique role and user mentions allowed per message (Maximum of 50)
Note
This field is only present if
trigger_type
isAutoModTriggerType.mention_spam
Additional data used to determine whether a rule should be triggered. Different fields are relevant based on the value of
AutoModRule.trigger_type
- Parameters:
keyword_filter (Optional[List[
str
]]) –Substrings which will be searched for in content
Note
This field is only allowed if
trigger_type
iskeyword
regex_patterns (Optional[List[Union[
str
, :class`~re.Pattern`]]]) –Regular expression patterns which will be matched against content (Maximum of 10, each max. 260 characters long)
Warning
Only <Rust https://docs.rs/regex/latest/regex/>_ flowered RegEx patterns are currently supported by Discord. So things like lookarounds are not allowed as they are not supported in Rust.
Note
This field is only allowed if
trigger_type
iskeyword
presets (Optional[List[
AutoModKeywordPresetType
]]) –The internally pre-defined word sets which will be searched for in content
Note
This field is only required if
trigger_type
iskeyword_preset
exempt_words (Optional[List[
str
]]) –Substrings which should be excluded from the blacklist.
Note
This field is only allowed if
trigger_type
iskeyword_preset
keyword
total_mentions_limit (Optional[
int
]) –Total number of unique role and user mentions allowed per message (Maximum of 50)
Note
This field is only allowed if
trigger_type
isAutoModTriggerType.mention_spam
- Raises:
TypeError – Both of keyword_filter and presets was passed
- property prefix_keywords
Returns all keywords for words that must start with the keyword.
Note
This is equal to
for keyword in self.keyword_filter: if keyword[0] != '*' and keyword[-1] == '*': yield keyword
- Yields:
str
– A keyword
- property suffix_keywords
Returns all keywords for words that must end with the keyword.
Note
This is equal to
for keyword in self.keyword_filter: if keyword[0] == '*' and keyword[-1] != '*': yield keyword
- Yields:
str
– A keyword
- property anywhere_keywords
Returns all keywords which can appear anywhere in a word
Note
This is equal to
for keyword in self.keyword_filter: if keyword[0] == '*' and keyword[-1] == '*': yield keyword
- Yields:
str
– A keyword
- property whole_word_keywords
Returns all keywords that must occur as a whole in a word or phrase and must be surrounded by spaces.
Note
This is equal to
for keyword in self.keyword_filter: if keyword[0] != '*' and keyword[-1] != '*': yield keyword
- Yields:
str
– A keyword
WelcomeScreenChannel
- class discord.WelcomeScreenChannel
Represents a channel shown in a welcome screen.
- emoji
The emoji that is shown on the left side of the welcome screen channel
- Type:
Optional[
PartialEmoji
]
Represents a channel shown in a welcome screen.
- Parameters:
channel (
Snowflake
) – The channel the welcome screen channel belongs todescription (
str
) – The description of the welcome screen channelemoji (Optional[Union[
PartialEmoji
,str
]) – The emoji that is shown on the left side of the welcome screen channel
- Members:
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
The response of the failed HTTP request. This is an instance of
aiohttp.ClientResponse
. In some cases this could also be arequests.Response
.- Type:
- exception discord.Unauthorized(response, message)
Exception that’s thrown for when status code 401 occurs.
Subclass of
HTTPException
New in version 2.0.
- 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.DiscordServerError(response, message)
Exception that’s thrown for when a 500 range status code occurs.
Subclass of
HTTPException
.New in version 1.5.
- exception discord.InvalidData
Exception that’s raised when the library encounters unknown or invalid data from Discord.
- 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
andTypeError
except inherited fromClientException
and thusDiscordException
.
- exception discord.GatewayNotFound
An exception that is usually thrown when the gateway hub for the
Client
websocket is not found.
- exception discord.ConnectionClosed(socket, *, shard_id, code=None)
Exception that’s thrown when the gateway connection is closed for reasons that could not be handled internally.
- shard_id
The shard ID that got closed if applicable.
- Type:
Optional[
int
]
- exception discord.PrivilegedIntentsRequired(shard_id)
Exception that’s thrown when the gateway is requesting privileged intents, but they’re not ticked in the developer page yet.
Go to https://discord.com/developers/applications/ and enable the intents that are required. Currently, these are as follows:
- shard_id
The shard ID that got closed if applicable.
- Type:
Optional[
int
]
- exception discord.AlreadyResponded(interaction_id)
Exception thrown when attempting to send the callback for an interaction that has already been responded to.’
- exception discord.opus.OpusError(code)
An exception that is thrown for libopus related errors.
- exception discord.DiscordWarning
Base warning class for discord.py
Ideally speaking, this could be caught to handle any warnings thrown from this library.
- exception discord.UnknownInteraction(interaction_id)
A warning that comes when you try to interact with an expired interaction.